Buckets:

download
raw
15.5 kB
"""
Configuration for integration tests.
Provides fixtures for database connections and test environments.
NO MOCKING POLICY: All integration tests must use real infrastructure.
This conftest enforces the policy at test collection time by scanning
every test module under ``tests/integration/`` for imports of
``unittest.mock`` and refusing to collect the module if found. Tests
that need mocks MUST live under ``tests/unit/``.
"""
import ast
import asyncio
import logging
import os
import time
from pathlib import Path
from typing import Any, Dict, Optional
import asyncpg
import pytest
# Configure test logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
_INTEGRATION_DIR = Path(__file__).parent.resolve()
# Mocking PRIMITIVES from unittest.mock — importing any of these implies
# the test constructs a test double rather than exercising real infra. The
# AST gate fails collection on these names.
_MOCKING_PRIMITIVES: frozenset[str] = frozenset(
{
"Mock",
"MagicMock",
"AsyncMock",
"NonCallableMock",
"NonCallableMagicMock",
"patch",
"patch.object",
"patch.dict",
"patch.multiple",
"PropertyMock",
"seal",
"create_autospec",
}
)
# Non-primitive helpers from unittest.mock — argument-equality sentinels
# and call-record types. Importing these does NOT imply mocking; they are
# stdlib utilities legitimately used in real-infrastructure tests for
# partial-call-equality matching (e.g. mock_calls assertions, ANY in dict
# comparisons, sentinel.UNSET defaults).
_MOCKING_NON_PRIMITIVES: frozenset[str] = frozenset(
{
"ANY",
"sentinel",
"DEFAULT",
"call",
"mock_open", # file-stub helper; integration tests may use against real fs paths
}
)
def _module_imports_unittest_mock(path: Path) -> bool:
"""Return True if ``path`` imports a mocking PRIMITIVE from unittest.mock.
Uses AST parsing so comments / docstrings that mention the string
``unittest.mock`` do not trigger false positives.
Whitelisted non-primitive exports (``ANY``, ``sentinel``, ``DEFAULT``,
``call``, ``mock_open``) are stdlib equality-matcher helpers compatible
with real-infrastructure tests and do NOT trigger the gate. Module-level
rebinds (``from unittest import mock``, ``import unittest.mock as m``)
are blocked because the rebinding makes downstream primitive use
unauditable at the import site.
See rules/testing.md § Tier 2 and issue #979 S3 Finding C for the
full rationale.
"""
try:
source = path.read_text(encoding="utf-8")
except Exception:
return False
try:
tree = ast.parse(source, filename=str(path))
except SyntaxError:
return False
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
# `from unittest.mock import X, Y, Z` — examine names.
if node.module and node.module.startswith("unittest.mock"):
for alias in node.names:
if alias.name in _MOCKING_PRIMITIVES:
return True
# Wildcard import pulls EVERYTHING including primitives.
if alias.name == "*":
return True
# All imported names were non-primitives (ANY, sentinel, ...).
continue
# `from unittest import mock` — the bare-module rebind makes
# downstream `mock.MagicMock(...)` calls unauditable; block.
if node.module == "unittest":
for alias in node.names:
if alias.name == "mock":
return True
elif isinstance(node, ast.Import):
for alias in node.names:
# `import unittest.mock` or `import unittest.mock as m` —
# bare-module rebind; same reason as `from unittest import
# mock` above.
if alias.name and alias.name.startswith("unittest.mock"):
return True
return False
def pytest_collectstart(collector):
"""Abort collection for integration tests that import ``unittest.mock``.
Fires before any test in an integration module runs; ``pytest.fail``
inside ``pytest_collectstart`` raises a collection error that surfaces
immediately with a clear, actionable message.
"""
path = getattr(collector, "path", None)
if path is None:
return
try:
resolved = Path(path).resolve()
except Exception:
return
if resolved.suffix != ".py":
return
if _INTEGRATION_DIR not in resolved.parents and resolved != _INTEGRATION_DIR:
return
if _module_imports_unittest_mock(resolved):
pytest.fail(
f"NO MOCKING POLICY VIOLATION (Tier 2): {resolved.relative_to(_INTEGRATION_DIR.parent)} "
f"imports unittest.mock. Integration tests must use real "
f"infrastructure. Move mock-based tests to tests/unit/ or rewrite "
f"against real backends (see rules/testing.md § Tier 2).",
pytrace=False,
)
@pytest.fixture(scope="function", autouse=True)
def no_mocking_policy_integration():
"""Autouse policy fixture for every Tier 2 integration test.
Complements the ``pytest_collectstart`` AST gate above — if a future
test body constructs a mocking-library double via dynamic
``importlib.import_module`` bypassing the module-level import check,
this fixture catches the unexpected runtime binding and raises.
"""
import sys as _sys
mock_mod = _sys.modules.get("unittest.mock")
if mock_mod is not None:
# Snapshot current Mock identity; tests that subsequently import
# unittest.mock at runtime and use it will have their own names
# bound to these classes, which is caught by the AST scan for
# module-level imports. The runtime guard is a belt-and-braces
# layer that leaves unit tests (not under this conftest) alone.
_ = mock_mod.Mock # reference to prevent tree-shaking
yield
@pytest.fixture(scope="session")
def test_database_config() -> Dict[str, Any]:
"""Provide centralized database configuration for integration tests."""
# Primary configuration from environment
if os.getenv("TEST_DATABASE_URL"):
return {"url": os.getenv("TEST_DATABASE_URL"), "type": "custom"}
# Standard SDK Docker infrastructure (port 5434)
db_host = os.getenv("DB_HOST", "localhost")
db_port = os.getenv("DB_PORT", "5434") # SDK standard port
db_user = os.getenv("DB_USER", "test_user")
db_password = os.getenv("DB_PASSWORD", "test_password")
db_name = os.getenv("DB_NAME", "kailash_test")
return {
"url": f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}",
"type": "postgresql",
"host": db_host,
"port": int(db_port),
"user": db_user,
"password": db_password,
"database": db_name,
}
@pytest.fixture(scope="session")
async def db_url(test_database_config):
"""Provide database URL for integration tests."""
return test_database_config["url"]
@pytest.fixture(scope="function")
async def shared_connection_pool(test_database_config):
"""Create connection pool for integration tests with proper cleanup."""
try:
# Test connection first
test_conn = await asyncpg.connect(test_database_config["url"])
await test_conn.fetchval("SELECT 1")
await test_conn.close()
logger.info(
f"Connected to test database: {test_database_config['type']} on port {test_database_config.get('port', 'unknown')}"
)
# Create connection pool with smaller size for better isolation
pool = await asyncpg.create_pool(
test_database_config["url"], min_size=1, max_size=5, command_timeout=10
)
yield pool
# Ensure all connections are closed
await pool.close()
except Exception as e:
pytest.skip(
f"Cannot connect to test database: {e}. Ensure PostgreSQL is running on port {test_database_config.get('port', 5434)}"
)
@pytest.fixture
async def postgres_connection(shared_connection_pool):
"""Provide individual PostgreSQL connection for each test."""
async with shared_connection_pool.acquire() as connection:
yield connection
class DatabaseConnectionManager:
"""Standardized connection manager for NOT NULL handler integration tests."""
def __init__(self, database_url: str):
self.database_url = database_url
self._connection = None
async def get_connection(self) -> asyncpg.Connection:
"""Get database connection."""
if self._connection is None or self._connection.is_closed():
self._connection = await asyncpg.connect(self.database_url)
return self._connection
async def close(self):
"""Close database connection."""
if self._connection and not self._connection.is_closed():
await self._connection.close()
@pytest.fixture
async def connection_manager(db_url):
"""Create connection manager for NOT NULL handler tests."""
manager = DatabaseConnectionManager(db_url)
yield manager
await manager.close()
@pytest.fixture
async def unique_table_name():
"""Generate unique table name for test isolation."""
return f"test_table_{int(time.time() * 1000000)}"
@pytest.fixture
async def clean_test_table(postgres_connection, unique_table_name):
"""Create and clean up a basic test table with standard schema."""
table_name = unique_table_name
# Create standard test table
await postgres_connection.execute(
f"""
CREATE TABLE {table_name} (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
# Insert standard test data
await postgres_connection.execute(
f"""
INSERT INTO {table_name} (name, email) VALUES
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')
"""
)
yield table_name
# Clean up
await postgres_connection.execute(f"DROP TABLE IF EXISTS {table_name} CASCADE")
@pytest.fixture
async def test_suite():
"""Integration test suite per ``tests/CLAUDE.md``.
Every integration test that exercises real infrastructure SHOULD use
``test_suite`` — it owns the PostgreSQL config, connection pool, and
database cleanup. Promoted from per-file fixture definitions to this
shared conftest because ~40 test files under ``tests/integration/``
previously defined local copies (or forgot to, causing
``fixture 'test_suite' not found`` errors for ~60 tests).
"""
from tests.infrastructure.test_harness import IntegrationTestSuite
suite = IntegrationTestSuite()
async with suite.session():
yield suite
@pytest.fixture
async def memory_test_suite():
"""Memory-backed SQLite test suite (unit-tier harness exposed at
integration tier for error-validation tests that don't need real
PostgreSQL but still want to exercise the DataFlow engine).
Tests under ``tests/integration/`` that request ``memory_dataflow``
(e.g. ``test_nodes_enhanced_errors.py``, ``test_jsonb_bug_reproduction.py``)
will receive a SQLite-memory engine here — matching the fixture's
semantics in ``tests/unit/conftest.py``.
"""
from tests.fixtures.unit_test_harness import UnitTestDatabaseConfig, UnitTestSuite
config = UnitTestDatabaseConfig.memory_database()
suite = UnitTestSuite(config)
async with suite.session():
yield suite
@pytest.fixture
async def memory_dataflow(memory_test_suite):
"""DataFlow against memory_test_suite (SQLite in-memory).
Cleanup on exit per rules/testing.md § "Fixtures Yield + Cleanup"
— explicit ``close_async()`` avoids the GC-finalizer deadlock.
"""
dataflow = memory_test_suite.dataflow_harness.create_dataflow()
try:
yield dataflow
finally:
await dataflow.close_async()
@pytest.fixture
async def test_table_with_constraints(postgres_connection):
"""Create test table with various constraint types."""
table_name = f"constrained_test_{int(time.time() * 1000000)}"
category_table = f"categories_{int(time.time() * 1000000)}"
# Create category table first
await postgres_connection.execute(
f"""
CREATE TABLE {category_table} (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE,
active BOOLEAN DEFAULT true
)
"""
)
# Insert categories
await postgres_connection.execute(
f"""
INSERT INTO {category_table} (name) VALUES ('general'), ('premium'), ('vip')
"""
)
# Create main table with constraints
await postgres_connection.execute(
f"""
CREATE TABLE {table_name} (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
age INTEGER CHECK (age >= 0 AND age <= 150),
category_id INTEGER REFERENCES {category_table}(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
# Insert test data with category references
await postgres_connection.execute(
f"""
INSERT INTO {table_name} (name, email, age, category_id) VALUES
('Alice', 'alice@example.com', 25, 1),
('Bob', 'bob@example.com', 30, 2),
('Charlie', 'charlie@example.com', 35, 1)
"""
)
yield {"main_table": table_name, "category_table": category_table}
# Clean up (order matters due to foreign key)
await postgres_connection.execute(f"DROP TABLE IF EXISTS {table_name} CASCADE")
await postgres_connection.execute(f"DROP TABLE IF EXISTS {category_table} CASCADE")
@pytest.fixture
async def large_test_table(postgres_connection):
"""Create large test table for performance testing."""
table_name = f"large_test_{int(time.time() * 1000000)}"
await postgres_connection.execute(
f"""
CREATE TABLE {table_name} (
id SERIAL PRIMARY KEY,
data VARCHAR(100),
value INTEGER
)
"""
)
# Insert test data in batches for performance
for batch_start in range(0, 10000, 1000):
values = ", ".join(
[
f"('data_{i}', {i % 100})"
for i in range(batch_start, min(batch_start + 1000, 10000))
]
)
await postgres_connection.execute(
f"INSERT INTO {table_name} (data, value) VALUES {values}"
)
yield table_name
# Clean up
await postgres_connection.execute(f"DROP TABLE IF EXISTS {table_name} CASCADE")
# Performance testing utilities
@pytest.fixture
def performance_timeout():
"""Standard performance timeout for integration tests."""
return 30 # seconds
@pytest.fixture
def batch_size_config():
"""Standard batch size configuration for testing."""
return {"small": 100, "medium": 1000, "large": 10000}
@pytest.fixture
async def postgresql_db_url(test_database_config):
"""Provide PostgreSQL database URL for integration tests."""
return test_database_config["url"]

Xet Storage Details

Size:
15.5 kB
·
Xet hash:
fa7405f32649e9a5f79a32da0997d329accf7d2d5a57e49795ecc19bab0f1ed6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.