""" pytest fixtures for NexusCRM E2E API tests. Provides setup and teardown helpers for the configured database and server. """ import pytest import time import os import sys # Add parent directory to path for imports sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import config import api import db E2E_CONNECTED_APP_ID = "test-gosf-client" E2E_CONNECTED_APP_NAME = "Test GoSF Client" E2E_CONNECTED_APP_SECRET = "test-gosf-secret-123" @pytest.fixture(scope="session") def db_instance(): """ Uses the configured TiDB connection for the test session. """ print("\n=== Using configured TiDB connection ===") manager = db.TiDBManager() conn_info = manager.create_instance(tag="nexus-e2e") print(f"Connection info: {conn_info}") if manager.wait_for_ready(timeout=300): print("Database is reachable") else: raise Exception("Configured database is not reachable") # Insert admin user and test-gosf-client connected app if they don't exist print("\n=== Initializing admin user and test-gosf-client connected app ===") try: # Insert admin user if it doesn't exist admin_user = manager.execute_query(""" SELECT Id FROM `User` WHERE Email = 'admin@test.com' """) if not admin_user: print("Inserting admin@test.com user...") manager.execute_query(""" INSERT INTO `User` ( `Id`, `Email`, `Username`, `FirstName`, `LastName`, `Password`, `IsActive`, `IsDeleted`, `CreatedDate`, `LastModifiedDate`, `CreatedById`, `LastModifiedById` ) VALUES ( '10000000-0000-0000-0000-000000000001', 'admin@test.com', 'admin', 'System', 'Administrator', '$2a$10$kjUgeoFlBhW3CxluLzIoI.vYtMpSJWJ3yA.M5E8sGAEZxXEleMRuy', 1, 0, NOW(), NOW(), '10000000-0000-0000-0000-000000000001', '10000000-0000-0000-0000-000000000001' ) """) print("Admin user inserted successfully") else: print("Admin user already exists") # Keep the OAuth test client in the current system table schema. try: connected_app_table = manager.execute_query(""" SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = '_System_ConnectedApp' """) if connected_app_table and connected_app_table[0]['count'] > 0: print("Upserting test-gosf-client connected app...") manager.execute_query(f""" INSERT INTO `_System_ConnectedApp` ( `Id`, `Name`, `ConsumerKey`, `ConsumerSecret`, `IsActive`, `CreatedDate`, `LastModifiedDate` ) VALUES ( '{E2E_CONNECTED_APP_ID}', '{E2E_CONNECTED_APP_NAME}', '{E2E_CONNECTED_APP_ID}', '{E2E_CONNECTED_APP_SECRET}', 1, NOW(), NOW() ) ON DUPLICATE KEY UPDATE `Name` = VALUES(`Name`), `ConsumerSecret` = VALUES(`ConsumerSecret`), `IsActive` = VALUES(`IsActive`), `LastModifiedDate` = NOW() """) print("test-gosf-client connected app ready") else: print("_System_ConnectedApp table does not exist") except Exception as e: print(f"Error checking/inserting connected app: {str(e)}") raise except Exception as e: print(f"Error initializing admin user and connected app: {str(e)}") raise yield conn_info print("\n=== Finished using configured TiDB connection ===") @pytest.fixture(scope="session") def nexus_server(db_instance): """ Placeholder fixture for a NexusCRM backend connected to db_instance. """ print("\n=== Starting NexusCRM backend ===") # In a real implementation, this would: # 1. Set environment variables for the server # 2. Start the server process # 3. Wait for it to be healthy # For testing purposes, we just yield the db info # The server is assumed to already be running or started externally yield { "host": db_instance["host"], "port": db_instance["port"], "database": db_instance.get("database", "nexuscrm") } print("\n=== Stopping NexusCRM backend ===") @pytest.fixture(scope="session") def auth_token(nexus_server): """ Authenticates with NexusCRM and provides the auth token. Uses the configured credentials from config.py. """ print("\n=== Authenticating with NexusCRM ===") client = api.NexusAPIClient() # Trigger authentication client._authenticate() print(f"Authentication successful, token: {client.token[:20]}...") return client.token @pytest.fixture def api_client(auth_token): """ Provides an authenticated API client for each test. """ client = api.NexusAPIClient() client._authenticate() return client @pytest.fixture def clean_db(db_instance): """ Fixture that clears test data after each test. This is a placeholder - actual cleanup logic would be implemented based on the test data created. """ yield # Cleanup logic would go here # For example, delete records created during the test print("\n=== Cleaning up test data ===") # Hooks for pytest def pytest_sessionstart(session): """Called before test session starts.""" print("\n" + "=" * 60) print("NexusCRM E2E API Test Session") print("=" * 60) def pytest_sessionfinish(session, exitstatus): """Called after test session finishes.""" print("\n" + "=" * 60) print(f"Test session finished with exit status: {exitstatus}") print("=" * 60)