forked from rustic-ai/rustic-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
177 lines (137 loc) · 5.08 KB
/
Copy pathconftest.py
File metadata and controls
177 lines (137 loc) · 5.08 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
import gc
import multiprocessing
import os
import threading
import time
import uuid
import pytest
from rustic_ai.core.guild.dsl import AgentSpec
# Configure multiprocessing early to avoid fork() warnings in multi-threaded test environments
try:
multiprocessing.set_start_method("spawn", force=True)
except RuntimeError:
# Start method may already be set, which is fine
pass
from rustic_ai.core.agents.testutils.probe_agent import ProbeAgent
from rustic_ai.core.guild.builders import AgentBuilder
from rustic_ai.core.guild.execution.sync.sync_exec_engine import SyncExecutionEngine
from rustic_ai.core.guild.guild import Guild
from rustic_ai.core.guild.metastore.database import Metastore
from rustic_ai.core.messaging.core.messaging_config import MessagingConfig
from rustic_ai.core.utils.gemstone_id import GemstoneGenerator
# Global counter for unique guild IDs
TEST_GUILD_COUNT = 0
@pytest.fixture(scope="session", autouse=True)
def cleanup_aiosqlite():
"""Auto-cleanup fixture that runs after all tests."""
yield # Tests run here
# After all tests, cleanup aiosqlite connections
try:
import asyncio
import aiosqlite
gc.collect()
connections = [obj for obj in gc.get_objects() if isinstance(obj, aiosqlite.Connection)]
if connections:
print(f"\n[Cleanup] Closing {len(connections)} aiosqlite connection(s)...")
async def close_all():
for conn in connections:
try:
await conn.close()
except Exception:
pass
await asyncio.sleep(0.5)
asyncio.run(close_all())
print("[Cleanup] Done")
except ImportError:
pass
def pytest_sessionfinish(session, exitstatus):
"""Report any remaining blocked threads."""
main_thread = threading.main_thread()
blocked = [t for t in threading.enumerate() if not t.daemon and t != main_thread]
if blocked:
print(f"\n⚠ WARNING: {len(blocked)} thread(s) still blocking:")
for t in blocked:
print(f" - {t.name}")
else:
print("\n✓ All threads cleaned up successfully")
@pytest.fixture(scope="session")
def org_id():
return "acmeorganizationid"
@pytest.fixture
def database(request):
"""Database fixture with test-name-derived filename."""
# Create filename from test name (sanitize for filesystem)
test_name = request.node.name.replace(":", "_").replace("[", "_").replace("]", "_").replace("/", "_")
# Add worker ID for pytest-xdist parallel execution
worker_id = os.environ.get("PYTEST_XDIST_WORKER", "master")
db_file = f"test_rustic_app_{test_name}_{worker_id}.db"
db = f"sqlite:///{db_file}"
print(f"Worker '{worker_id}' test '{request.node.name}' using database {db_file}")
# Clean up any existing database file
if os.path.exists(db_file):
os.remove(db_file)
# Initialize the database properly
Metastore.initialize_engine(db)
Metastore.get_engine(db)
Metastore.create_db()
yield db
# Cleanup
try:
Metastore.drop_db()
except Exception:
# If cleanup fails, just remove the file
pass
finally:
try:
if os.path.exists(db_file):
os.remove(db_file)
except Exception:
# Ignore file removal errors
pass
@pytest.fixture
def guild(org_id, database):
global TEST_GUILD_COUNT
TEST_GUILD_COUNT += 1
# Use a unique guild ID that includes timestamp and UUID to ensure complete isolation
guild_id = f"test_guild_{TEST_GUILD_COUNT}_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
# Use InMemoryMessagingBackend as default for tests
messaging_config: MessagingConfig = MessagingConfig(
backend_module="rustic_ai.core.messaging.backend",
backend_class="InMemoryMessagingBackend",
backend_config={},
)
# Create and return a Guild
guild = Guild(
id=guild_id,
name=f"Test Guild {TEST_GUILD_COUNT}",
description=f"A test guild {guild_id}",
execution_engine_clz=SyncExecutionEngine.get_qualified_class_name(),
messaging_config=messaging_config,
organization_id=org_id,
)
yield guild
# Thorough cleanup to ensure test isolation
try:
# Just shutdown the guild - it will handle agent cleanup internally
# Don't try to remove agents individually as that causes async/sync issues
guild.shutdown()
# Give some time for async cleanup
time.sleep(0.2)
except Exception:
# Log but don't fail test cleanup
pass
@pytest.fixture
def generator():
return GemstoneGenerator(1)
@pytest.fixture
def probe_spec():
# Create a unique probe agent for each test to avoid state sharing
probe_id = f"test_agent_{int(time.time() * 1000000) % 1000000}_{uuid.uuid4().hex[:8]}"
probe_spec: AgentSpec = (
AgentBuilder(ProbeAgent)
.set_id(probe_id)
.set_name(f"Test Agent {probe_id}")
.set_description("A test agent")
.build_spec()
)
return probe_spec