-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_conftest.patch
More file actions
273 lines (234 loc) · 16.7 KB
/
diff_conftest.patch
File metadata and controls
273 lines (234 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
diff --git a/tests/conftest.py b/tests/conftest.py
index d182d2ef..dc90fda8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,234 +1,250 @@
"""
Test configuration and fixtures for ICC Rule Engine
"""
import os
import asyncio
import pytest
import pytest_asyncio
import tempfile
from typing import Generator
+from uuid import uuid4
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from fastapi.testclient import TestClient
# Set test environment variables
os.environ["DATABASE_URL"] = "sqlite:///./test_icc_rules.db"
os.environ["OPENAI_API_KEY"] = "" # Disable LLM for most tests
os.environ["REDIS_URL"] = "" # Disable Redis for most tests
os.environ["METRICS_ENABLED"] = "false"
os.environ["LOGGING_ENABLED"] = "false"
os.environ["MULTI_TENANT_ENABLED"] = "true"
-os.environ["DEMO_MODE"] = "true"
+os.environ["DEMO_MODE"] = "false"
os.environ["API_KEY_USAGE_TRACKING_ENABLED"] = "false"
os.environ["API_KEY_ENFORCE_ROTATION"] = "false"
ASYNC_DATABASE_URL = "sqlite+aiosqlite:///./test_icc_rules.db"
from app.main import app
from app.db import get_db, get_async_db, Base
from app.middleware.dashboard_metrics import DashboardMetricsMiddleware
-from app.middleware.api_key_security import ApiKeySecurityMiddleware
-from app.middleware.tenant import TenantMiddleware
-from app.models.rules import Rule
+from app.models.api_keys import ApiKey
+from app.models.tenants import Tenant
+from app.utils.api_key_utils import generate_api_key
@pytest.fixture(scope="session")
def test_engine() -> Generator:
"""Create test database engine"""
engine = create_engine(
"sqlite:///./test_icc_rules.db",
echo=False,
connect_args={"check_same_thread": False},
)
Base.metadata.create_all(bind=engine)
yield engine
Base.metadata.drop_all(bind=engine)
engine.dispose()
@pytest.fixture(scope="session")
def async_engine(test_engine):
"""Async engine sharing the same SQLite database"""
engine = create_async_engine(ASYNC_DATABASE_URL, echo=False)
yield engine
asyncio.run(engine.dispose())
@pytest.fixture(scope="function")
def test_session(test_engine):
"""Create test database session"""
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
session = TestingSessionLocal()
yield session
session.close()
with test_engine.begin() as conn:
for table in reversed(Base.metadata.sorted_tables):
conn.execute(table.delete())
@pytest_asyncio.fixture(scope="function")
async def db_session(async_engine):
"""Async session fixture for async database usage"""
session_factory = async_sessionmaker(async_engine, expire_on_commit=False)
async with session_factory() as session:
try:
yield session
finally:
await session.rollback()
async with async_engine.begin() as conn:
for table in reversed(Base.metadata.sorted_tables):
await conn.execute(table.delete())
@pytest.fixture(scope="function")
def client(test_session, async_engine):
"""Create test client with overridden dependencies"""
def override_get_db():
try:
yield test_session
finally:
pass
async_session_factory = async_sessionmaker(async_engine, expire_on_commit=False)
async def override_get_async_db():
async with async_session_factory() as session:
try:
yield session
finally:
await session.rollback()
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_async_db] = override_get_async_db
original_logging_dispatch = DashboardMetricsMiddleware.dispatch
- original_security_dispatch = ApiKeySecurityMiddleware.dispatch
- original_tenant_dispatch = TenantMiddleware.dispatch
async def _noop_dispatch(self, request, call_next):
return await call_next(request)
- async def _noop_security(self, request, call_next):
- return await call_next(request)
-
- async def _noop_tenant(self, request, call_next):
- return await call_next(request)
-
DashboardMetricsMiddleware.dispatch = _noop_dispatch
- ApiKeySecurityMiddleware.dispatch = _noop_security
- TenantMiddleware.dispatch = _noop_tenant
try:
yield TestClient(app)
finally:
DashboardMetricsMiddleware.dispatch = original_logging_dispatch
- ApiKeySecurityMiddleware.dispatch = original_security_dispatch
- TenantMiddleware.dispatch = original_tenant_dispatch
app.dependency_overrides.clear()
+
+@pytest.fixture
+def admin_headers(test_session):
+ tenant = test_session.query(Tenant).filter_by(id="admin").first()
+ if tenant is None:
+ tenant = Tenant(
+ id="admin",
+ name="Admin Tenant",
+ plan="Bank",
+ environment="sandbox",
+ active=True,
+ )
+ test_session.add(tenant)
+
+ full_key, prefix, key_hash = generate_api_key()
+ api_key = ApiKey(
+ name=f"admin-test-{uuid4().hex[:6]}",
+ prefix=prefix,
+ key_hash=key_hash,
+ tenant_id=tenant.id,
+ active=True,
+ ip_whitelist=[],
+ )
+ test_session.add(api_key)
+ test_session.commit()
+ return {"X-API-Key": full_key}
+
@pytest.fixture
def sample_rule():
"""Sample rule for testing"""
return {
"source": "UCP600",
- "rule_id": "TEST_RULE_001",
+ "rule_id": f"TEST_RULE_{uuid4().hex[:8]}",
"article": "14",
"title": "Test Rule",
"text": "This is a test rule for validation.",
"condition": {
"type": "equality_match",
"left_path": "document_type",
"right_value": "letter_of_credit",
},
"expected_outcome": {
"action": "validate",
"result": "compliant",
},
"tags": ["test"],
"severity": "medium",
"deterministic": True,
"requires_llm": False,
}
@pytest.fixture
def sample_llm_rule():
"""Sample LLM rule for testing"""
return {
"source": "UCP600",
- "rule_id": "TEST_LLM_RULE_001",
+ "rule_id": f"TEST_LLM_RULE_{uuid4().hex[:8]}",
"article": "17",
"title": "Test LLM Rule",
"text": "Documents must be consistent on their face.",
"condition": None,
"expected_outcome": {
"action": "check_consistency",
"result": "consistent",
},
"tags": ["test", "llm"],
"severity": "medium",
"deterministic": False,
"requires_llm": True,
}
@pytest.fixture
def sample_document():
"""Sample document for validation testing"""
return {
"id": "TEST_DOC_001",
"document_type": "letter_of_credit",
"credit_amount": 100000,
"presentation_date": "2024-01-15",
"expiry_date": "2024-02-15",
"documents": {
"commercial_invoice": True,
"bill_of_lading": True,
},
}
@pytest.fixture
def sample_ruleset():
"""Sample ruleset for validation testing"""
return {
"source": "UCP600",
"article": "14",
}
@pytest.fixture
def mock_redis():
"""Mock Redis client for testing"""
class MockRedis:
def __init__(self):
self.data = {}
def get(self, key):
return self.data.get(key)
def setex(self, key, ttl, value):
self.data[key] = value
return True
def info(self):
return {}
def delete(self, *keys):
for key in keys:
self.data.pop(key, None)
def keys(self, pattern):
if pattern.endswith("*"):
prefix = pattern[:-1]
return [k for k in self.data.keys() if k.startswith(prefix)]
return list(self.data.keys())
def ping(self):
return True
return MockRedis()