|
| 1 | +"""Oracle TestContainer manager for integration tests.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine |
| 9 | +from testcontainers.oracle import OracleDbContainer |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from collections.abc import AsyncGenerator |
| 13 | + |
| 14 | +from datajam_sqlalchemy import create_oracle_connection_string |
| 15 | + |
| 16 | +from .container_constants import ( |
| 17 | + ORACLE_IMAGE, |
| 18 | + ORACLE_PASSWORD, |
| 19 | + ORACLE_PORT, |
| 20 | + ORACLE_SERVICE_NAME, |
| 21 | + ORACLE_USERNAME, |
| 22 | +) |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +class OracleContainerManager: |
| 28 | + """Manages Oracle TestContainer lifecycle for integration tests.""" |
| 29 | + |
| 30 | + def __init__(self) -> None: |
| 31 | + """Initialize the Oracle container manager.""" |
| 32 | + self._container: OracleDbContainer | None = None |
| 33 | + self._engine: AsyncEngine | None = None |
| 34 | + self._connection_string: str | None = None |
| 35 | + |
| 36 | + async def start_container(self) -> None: |
| 37 | + """Start the Oracle container and wait for it to be ready.""" |
| 38 | + if self._container is not None: |
| 39 | + logger.warning("Oracle container already started") |
| 40 | + return |
| 41 | + |
| 42 | + logger.info("Starting Oracle container...") |
| 43 | + |
| 44 | + # Create and start the Oracle container using the free image |
| 45 | + self._container = OracleDbContainer( |
| 46 | + image="gvenzl/oracle-free:slim" # Use the official free image |
| 47 | + ) |
| 48 | + |
| 49 | + # Start the container (this will block until ready) |
| 50 | + self._container.start() |
| 51 | + |
| 52 | + # Get connection URL directly from the container |
| 53 | + self._connection_string = self._container.get_connection_url() |
| 54 | + |
| 55 | + # For async support, convert the connection string to use async driver |
| 56 | + if self._connection_string.startswith("oracle+cx_oracle://"): |
| 57 | + async_connection_string = self._connection_string.replace("oracle+cx_oracle://", "oracle+oracledb_async://") |
| 58 | + elif self._connection_string.startswith("oracle+oracledb://"): |
| 59 | + async_connection_string = self._connection_string.replace("oracle+oracledb://", "oracle+oracledb_async://") |
| 60 | + else: |
| 61 | + async_connection_string = self._connection_string |
| 62 | + |
| 63 | + self._engine = create_async_engine( |
| 64 | + async_connection_string, |
| 65 | + echo=True, # Enable SQL logging for debugging |
| 66 | + future=True, |
| 67 | + ) |
| 68 | + |
| 69 | + logger.info(f"Oracle container started with connection: {self._connection_string}") |
| 70 | + |
| 71 | + # Test the connection |
| 72 | + await self._test_connection() |
| 73 | + |
| 74 | + async def _test_connection(self) -> None: |
| 75 | + """Test the Oracle connection.""" |
| 76 | + if not self._engine: |
| 77 | + raise RuntimeError("Engine not initialized") |
| 78 | + |
| 79 | + try: |
| 80 | + from sqlalchemy import text |
| 81 | + async with self._engine.begin() as conn: |
| 82 | + result = await conn.execute(text("SELECT 1 FROM DUAL")) |
| 83 | + row = result.fetchone() |
| 84 | + if row and row[0] == 1: |
| 85 | + logger.info("Oracle connection test successful") |
| 86 | + else: |
| 87 | + raise RuntimeError("Oracle connection test failed") |
| 88 | + except Exception as e: |
| 89 | + logger.error(f"Oracle connection test failed: {e}") |
| 90 | + raise |
| 91 | + |
| 92 | + async def stop_container(self) -> None: |
| 93 | + """Stop the Oracle container and clean up resources.""" |
| 94 | + if self._engine: |
| 95 | + await self._engine.dispose() |
| 96 | + self._engine = None |
| 97 | + |
| 98 | + if self._container: |
| 99 | + logger.info("Stopping Oracle container...") |
| 100 | + self._container.stop() |
| 101 | + self._container = None |
| 102 | + |
| 103 | + self._connection_string = None |
| 104 | + logger.info("Oracle container stopped") |
| 105 | + |
| 106 | + @property |
| 107 | + def connection_string(self) -> str: |
| 108 | + """Get the Oracle connection string.""" |
| 109 | + if not self._connection_string: |
| 110 | + raise RuntimeError("Oracle container not started") |
| 111 | + return self._connection_string |
| 112 | + |
| 113 | + @property |
| 114 | + def async_connection_string(self) -> str: |
| 115 | + """Get the Oracle async connection string.""" |
| 116 | + connection_string = self.connection_string |
| 117 | + return connection_string.replace("oracle+oracledb://", "oracle+oracledb_async://") |
| 118 | + |
| 119 | + @property |
| 120 | + def engine(self) -> AsyncEngine: |
| 121 | + """Get the SQLAlchemy async engine.""" |
| 122 | + if not self._engine: |
| 123 | + raise RuntimeError("Oracle container not started") |
| 124 | + return self._engine |
| 125 | + |
| 126 | + async def __aenter__(self) -> OracleContainerManager: |
| 127 | + """Enter async context manager.""" |
| 128 | + await self.start_container() |
| 129 | + return self |
| 130 | + |
| 131 | + async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: |
| 132 | + """Exit async context manager.""" |
| 133 | + await self.stop_container() |
| 134 | + |
| 135 | + |
| 136 | +# Global container manager instance |
| 137 | +_oracle_manager: OracleContainerManager | None = None |
| 138 | + |
| 139 | + |
| 140 | +async def get_oracle_container() -> OracleContainerManager: |
| 141 | + """Get or create the global Oracle container manager.""" |
| 142 | + global _oracle_manager |
| 143 | + |
| 144 | + if _oracle_manager is None: |
| 145 | + _oracle_manager = OracleContainerManager() |
| 146 | + await _oracle_manager.start_container() |
| 147 | + |
| 148 | + return _oracle_manager |
| 149 | + |
| 150 | + |
| 151 | +async def cleanup_oracle_container() -> None: |
| 152 | + """Clean up the global Oracle container manager.""" |
| 153 | + global _oracle_manager |
| 154 | + |
| 155 | + if _oracle_manager is not None: |
| 156 | + await _oracle_manager.stop_container() |
| 157 | + _oracle_manager = None |
| 158 | + |
| 159 | + |
| 160 | +# Pytest fixture for Oracle container |
| 161 | +async def oracle_container_fixture() -> AsyncGenerator[OracleContainerManager, None]: |
| 162 | + """Pytest fixture that provides an Oracle container for tests.""" |
| 163 | + async with OracleContainerManager() as container: |
| 164 | + yield container |
0 commit comments