|
6 | 6 |
|
7 | 7 | from django.conf import settings |
8 | 8 | from django.core.management import call_command |
9 | | -from django.db import connections, connection |
| 9 | +from django.db import connections |
10 | 10 | from django.test import override_settings |
11 | 11 | from pathlib import Path |
12 | 12 |
|
| 13 | +from usaspending_api.common.helpers.sql_helpers import execute_sql_simple |
13 | 14 | from usaspending_api.common.elasticsearch.elasticsearch_sql_helpers import ( |
14 | 15 | ensure_view_exists, |
15 | 16 | ensure_business_categories_functions_exist, |
@@ -46,14 +47,24 @@ def pytest_addoption(parser): |
46 | 47 | def delete_tables_for_tests(): |
47 | 48 | """ |
48 | 49 | Outside of testing, the transaction_search table is created by using a series of chunked matviews that are combined |
49 | | - into a Django managed table. When unit testing transaction_search is created as a single matview. To prevent a |
| 50 | + into a Django managed table. When unit testing transaction_search is created as a single view. To prevent a |
50 | 51 | naming conflict, the unused Django managed table is deleted while testing. |
51 | 52 | """ |
52 | | - with connection.cursor() as cursor: |
53 | | - try: |
54 | | - cursor.execute("DROP TABLE IF EXISTS transaction_search;") |
55 | | - except Exception: |
56 | | - pass |
| 53 | + try: |
| 54 | + execute_sql_simple("DROP TABLE IF EXISTS transaction_search;") |
| 55 | + except Exception: |
| 56 | + pass |
| 57 | + |
| 58 | + |
| 59 | +def add_view_protection(): |
| 60 | + """ |
| 61 | + When unit testing transaction_search is created as a single view. Views can't be deleted from, so a custom rule |
| 62 | + is added to transaction_search to prevent sql errors when deletes are attempted |
| 63 | + """ |
| 64 | + try: |
| 65 | + execute_sql_simple("CREATE RULE ts_del_protect AS ON DELETE TO transaction_search DO INSTEAD NOTHING;") |
| 66 | + except Exception: |
| 67 | + pass |
57 | 68 |
|
58 | 69 |
|
59 | 70 | @pytest.fixture(scope="session") |
@@ -108,6 +119,7 @@ def django_db_setup( |
108 | 119 | generate_matviews(materialized_views_as_traditional_views=True) |
109 | 120 | ensure_view_exists(settings.ES_TRANSACTIONS_ETL_VIEW_NAME) |
110 | 121 | ensure_view_exists(settings.ES_AWARDS_ETL_VIEW_NAME) |
| 122 | + add_view_protection() |
111 | 123 | ensure_business_categories_functions_exist() |
112 | 124 | call_command("load_broker_static_data") |
113 | 125 |
|
|
0 commit comments