Repository navigation
Expand file tree
/
Copy pathtest_base.py
More file actions
342 lines (283 loc) · 10.9 KB
/
Copy pathtest_base.py
File metadata and controls
342 lines (283 loc) · 10.9 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""
Test Base Class - Foundation for all test modules
Provides:
- Setup/teardown with database backup/restore
- Test mode configuration
- Common assertions and utilities
- Mock QMT trader when unavailable
"""
import unittest
import os
import sys
import shutil
import sqlite3
from datetime import datetime
import threading
import time
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import config
from logger import get_logger, set_log_file
logger = get_logger("test_base")
class TestBase(unittest.TestCase):
"""
Base class for all miniQMT tests
Features:
- Automatic database backup/restore
- Test mode configuration
- Common test utilities
- Cleanup after tests
"""
# Class-level flags
_db_backed_up = False
_original_db_path = None
_backup_db_path = None
@classmethod
def setUpClass(cls):
"""
Setup test environment (runs once per test class)
Actions:
1. Backup production database
2. Set test mode configuration
3. Initialize test database
"""
cls._setup_test_logging()
logger.info(f"=== Setting up test class: {cls.__name__} ===")
# Backup production database
cls._backup_database()
# Override config for test mode
cls._setup_test_config()
# Remove corrupted test database if it exists
cls._reset_test_db_if_corrupted()
logger.info(f"Test class {cls.__name__} setup complete")
@classmethod
def tearDownClass(cls):
"""
Cleanup test environment (runs once per test class)
Actions:
1. Restore production database
2. Clean up test artifacts
"""
logger.info(f"=== Tearing down test class: {cls.__name__} ===")
# Restore production database
cls._restore_database()
# Clean up test artifacts
cls._cleanup_test_artifacts()
logger.info(f"Test class {cls.__name__} teardown complete")
@classmethod
def _setup_test_logging(cls):
"""Redirect test logs before the first test setup log is emitted."""
config.LOG_FILE = "test/logs/test.log"
set_log_file(config.LOG_FILE)
def setUp(self):
"""Setup before each test method"""
logger.info(f"--- Running test: {self._testMethodName} ---")
self.start_time = time.time()
def tearDown(self):
"""Cleanup after each test method"""
duration = time.time() - self.start_time
logger.info(f"--- Test {self._testMethodName} completed in {duration:.2f}s ---")
@classmethod
def _backup_database(cls):
"""Backup production database before testing"""
if cls._db_backed_up:
return
db_path = config.DB_PATH
if not os.path.exists(db_path):
logger.warning(f"Production database not found: {db_path}")
return
# Create backup path
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = f"{db_path}.backup_{timestamp}"
try:
shutil.copy2(db_path, backup_path)
cls._original_db_path = db_path
cls._backup_db_path = backup_path
cls._db_backed_up = True
logger.info(f"Database backed up: {backup_path}")
except Exception as e:
logger.error(f"Failed to backup database: {str(e)}")
@classmethod
def _restore_database(cls):
"""Restore production database after testing"""
if not cls._db_backed_up or not cls._backup_db_path:
return
try:
if os.path.exists(cls._backup_db_path):
shutil.copy2(cls._backup_db_path, cls._original_db_path)
logger.info(f"Database restored from: {cls._backup_db_path}")
# Remove backup file
os.remove(cls._backup_db_path)
logger.info(f"Backup file removed: {cls._backup_db_path}")
except Exception as e:
logger.error(f"Failed to restore database: {str(e)}")
@classmethod
def _setup_test_config(cls):
"""Override configuration for test mode"""
# Force simulation mode
config.ENABLE_SIMULATION_MODE = True
config.ENABLE_AUTO_TRADING = False
config.DEBUG = True
# Use test database path
config.DB_PATH = "data/trading_test.db"
# Use test log file
config.LOG_FILE = "test/logs/test.log"
set_log_file(config.LOG_FILE)
# Set test simulation balance
config.SIMULATION_BALANCE = 100000.0
logger.info("Test configuration applied")
@classmethod
def _reset_test_db_if_corrupted(cls):
"""Delete or recreate test database if it is corrupted or malformed"""
test_db = "data/trading_test.db"
if not os.path.exists(test_db):
return
try:
conn = sqlite3.connect(test_db)
result = conn.execute("PRAGMA quick_check").fetchone()
conn.close()
if result and result[0] == 'ok':
return # DB is healthy
raise sqlite3.DatabaseError(f"Integrity check failed: {result[0] if result else 'unknown'}")
except Exception as e:
logger.warning(f"Test database corrupted ({e}), recreating: {test_db}")
# Try to delete first
for ext in ('', '-wal', '-shm'):
path = test_db + ext
if os.path.exists(path):
try:
os.remove(path)
except Exception:
pass
# If deletion failed (file still in use), overwrite with fresh empty DB
if os.path.exists(test_db):
try:
import shutil
new_conn = sqlite3.connect(test_db + '.new')
new_conn.close()
shutil.move(test_db + '.new', test_db)
logger.info(f"Recreated test database: {test_db}")
except Exception as e2:
logger.warning(f"Failed to recreate test database: {e2}")
else:
logger.info(f"Corrupted test database removed: {test_db}")
@classmethod
def _cleanup_test_artifacts(cls):
"""Clean up test-generated files"""
# Remove test database
test_db = "data/trading_test.db"
if os.path.exists(test_db):
try:
os.remove(test_db)
logger.info(f"Test database removed: {test_db}")
except Exception as e:
logger.warning(f"Failed to remove test database: {str(e)}")
# ==================== Helper Methods ====================
def create_test_db_connection(self):
"""Create a connection to test database"""
return sqlite3.connect(config.DB_PATH)
def create_memory_db(self):
"""Create an in-memory database for isolated testing"""
return sqlite3.connect(":memory:")
def create_test_position(self, conn, stock_code, volume, cost_price,
available=None, current_price=None):
"""
Insert a test position into database
Args:
conn: Database connection
stock_code: Stock code (e.g., '000001.SZ')
volume: Total volume
cost_price: Cost price
available: Available volume (defaults to volume)
current_price: Current price (defaults to cost_price)
Returns:
Position data dict
"""
if available is None:
available = volume
if current_price is None:
current_price = cost_price
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO positions
(stock_code, volume, available, cost_price, current_price, open_date)
VALUES (?, ?, ?, ?, ?, ?)
""", (stock_code, volume, available, cost_price, current_price,
datetime.now().strftime("%Y-%m-%d")))
conn.commit()
return {
'stock_code': stock_code,
'volume': volume,
'available': available,
'cost_price': cost_price,
'current_price': current_price
}
def assert_thread_running(self, thread_name, timeout=5):
"""
Assert that a specific thread is running
Args:
thread_name: Name of the thread to check
timeout: Maximum wait time in seconds
"""
start_time = time.time()
while time.time() - start_time < timeout:
for thread in threading.enumerate():
if thread_name.lower() in thread.name.lower():
logger.debug(f"Thread found: {thread.name}")
return True
time.sleep(0.1)
self.fail(f"Thread '{thread_name}' not found within {timeout}s")
def assert_thread_stopped(self, thread_name, timeout=5):
"""
Assert that a specific thread has stopped
Args:
thread_name: Name of the thread to check
timeout: Maximum wait time in seconds
"""
start_time = time.time()
while time.time() - start_time < timeout:
found = False
for thread in threading.enumerate():
if thread_name.lower() in thread.name.lower():
found = True
break
if not found:
logger.debug(f"Thread stopped: {thread_name}")
return True<
5BD1
/div>
time.sleep(0.1)
self.fail(f"Thread '{thread_name}' still running after {timeout}s")
def assert_file_exists(self, file_path):
"""Assert that a file exists"""
self.assertTrue(os.path.exists(file_path),
f"File not found: {file_path}")
def assert_database_table_exists(self, conn, table_name):
"""Assert that a database table exists"""
cursor = conn.cursor()
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name=?
""", (table_name,))
result = cursor.fetchone()
self.assertIsNotNone(result,
f"Table '{table_name}' does not exist")
def get_table_row_count(self, conn, table_name):
"""Get row count from a table"""
cursor = conn.cursor()
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
return cursor.fetchone()[0]
def wait_for_condition(self, condition_func, timeout=10, interval=0.1):
"""
Wait for a condition to become True
Args:
condition_func: Function that returns True when condition is met
timeout: Maximum wait time in seconds
interval: Check interval in seconds
Returns:
True if condition met, False otherwise
"""
start_time = time.time()
while time.time() - start_time < timeout:
if condition_func():
return True
time.sleep(interval)
return False