"""Integration test configuration.""" import os import boto3 import pytest from abacus_common_logic.connectors.database import db from botocore.exceptions import ClientError from core.config import Config from royalties.tests.integration.utils.ows_royalties_api_client import ( RoyaltiesAPIClient, ) ROYALTIES_API_BASE_URL = os.environ.get( 'ROYALTIES_API_BASE_URL', 'http://localhost:6052' ) print(f'Using royalties URL {ROYALTIES_API_BASE_URL}') def ows_royalties_api_client(headers): """Create ows-royalties APIClient object.""" return RoyaltiesAPIClient(ROYALTIES_API_BASE_URL, headers) @pytest.fixture(scope='session') def basic_headers(): """Return basic headers.""" return {'Content-Type': 'application/json'} class TestConfig(Config): """Test configuration.""" MYSQL_DB_NAME = os.environ.get('MYSQL_DB_NAME', Config.MYSQL_DB_NAME) MYSQL_DB_USER = os.environ.get('MYSQL_DB_USER', 'royalties') MYSQL_DB_HOST = os.environ.get('MYSQL_DB_HOST', 'mysql-royalties-container') MYSQL_DB_PORT = os.environ.get('MYSQL_DB_PORT', '3306') MYSQL_DB_PASS = os.environ.get('MYSQL_DB_PASS', '1234') @pytest.fixture(scope='session', autouse=True) def test_app(): """Create a test application.""" from core.app_factory import create_app return create_app(TestConfig) @pytest.mark.fixture @pytest.fixture(autouse=True) def test_app_in_context(test_app): """Push the test app onto the context.""" with test_app.app_context(): yield test_app @pytest.fixture() def clear_db_file_upload(): """Refresh the test database.""" top_level_tables = ( 'abacus_outbox', 'file_upload', 'file_upload_config', ) with db.engine.connect() as conn: conn.exec_driver_sql('SET FOREIGN_KEY_CHECKS=0') for table in top_level_tables: conn.exec_driver_sql(f'TRUNCATE TABLE {table}') conn.exec_driver_sql('SET FOREIGN_KEY_CHECKS=1') @pytest.fixture def delete_quarantine_file(): """Delete quarantine file from S3.""" bucket = 'qa-abacus-quarantine' s3 = boto3.client('s3') def _delete(file_key): key_prefix = f'test_fixtures/ows-royalties-integration-tests/{file_key}' key = key_prefix if key_prefix.endswith('.xlsx') else f'{key_prefix}.xlsx' try: expected_bucket_owner = os.environ.get('AWS_BUCKET_OWNER') if not expected_bucket_owner: raise RuntimeError( 'AWS_BUCKET_OWNER must be set to verify S3 bucket ownership' ) s3.delete_object( Bucket=bucket, Key=key, ExpectedBucketOwner=expected_bucket_owner ) print('Delete request sent') except ClientError as e: if e.response['Error']['Code'] == 'AccessDenied': raise yield _delete @pytest.fixture def insert_file_upload_fixture(): """Insert an entry into royalty_accounting.file_upload table.""" def _insert(file_upload_config_id: int): query = f""" INSERT INTO royalty_accounting.file_upload ( file_upload_config_id, file_key, original_file_name, file_size_bytes, file_type, s3_bucket, s3_key, created_by, last_modified_by ) VALUES ( {file_upload_config_id}, 'a58863c8-9f99-407c-85ab-75bd88201e9e', 'a58863c8-9f99-407c-85ab-75bd88201e9e.xlsx', 9991, 'xlsx', 'qa-abacus-adjustments', 'test_fixtures/ows-royalties-integration-tests/a58863c8-9f99-407c-85ab-75bd88201e9e.xlsx', 'integraton_tests', 'integraton_tests' ) """ db.engine.execute(query) return _insert @pytest.fixture def upload_xlsx_to_s3(): """Upload an xlsx file from fixtures/ to S3 and return the S3 URI.""" def _upload(local_filename: str, dest_filename: str = None): s3_bucket = 'qa-abacus-adjustments' s3_prefix = 'test_fixtures/ows-royalties-integration-tests/' s3_filename = dest_filename or os.path.basename(local_filename) s3_key = f'{s3_prefix}{s3_filename}' local_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'fixtures', local_filename) ) expected_bucket_owner = os.environ.get('AWS_BUCKET_OWNER') extra_args = ( {'ExpectedBucketOwner': expected_bucket_owner} if expected_bucket_owner else {} ) try: boto3.client('s3').upload_file( local_path, s3_bucket, s3_key, ExtraArgs=extra_args ) except ClientError as e: raise RuntimeError( f'Failed to upload {local_path} to s3://{s3_bucket}/{s3_key}: {e}' ) return f's3://{s3_bucket}/{s3_key}' return _upload def has_records_in_table(table_name: str) -> bool: """Check if a given table has any records.""" result = db.engine.execute(f'SELECT COUNT(*) FROM {table_name}') count = result.scalar() return count > 0