-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pre_commit_setup.py
More file actions
273 lines (214 loc) · 7.82 KB
/
Copy pathtest_pre_commit_setup.py
File metadata and controls
273 lines (214 loc) · 7.82 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
#!/usr/bin/env python3
"""
Test script to validate pre-commit hooks and CI setup for the Trading Platform.
This script tests:
1. JSON linting and formatting
2. Schema validation
3. Unit tests execution
4. Configuration loading
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List
def run_command(cmd: List[str], cwd: str = None) -> tuple[bool, str, str]:
"""Run a command and return success status, stdout, stderr"""
try:
result = subprocess.run(
cmd, capture_output=True, text=True, cwd=cwd, timeout=60
)
return result.returncode == 0, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return False, "", "Command timed out"
except Exception as e:
return False, "", str(e)
def test_json_validation():
"""Test JSON file validation"""
print("🔍 Testing JSON validation...")
# Test valid JSON
valid_json = {"test": "value", "number": 123, "array": [1, 2, 3]}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(valid_json, f)
temp_file = Path(f.name)
try:
# Test JSON syntax validation
success, stdout, stderr = run_command(
["python", "-m", "json.tool", str(temp_file)]
)
if success:
print(" ✅ JSON syntax validation passed")
else:
print(f" ❌ JSON syntax validation failed: {stderr}")
return False
finally:
temp_file.unlink()
return True
def test_schema_validation():
"""Test JSON schema validation"""
print("🔍 Testing schema validation...")
schema_path = Path("trading_platform.schema.json")
if not schema_path.exists():
print(" ⚠️ Schema file not found, skipping schema validation")
return True
try:
# Import required modules
from jsonschema import Draft7Validator, ValidationError, validate
# Load schema
with open(schema_path, "r") as f:
schema = json.load(f)
# Validate schema itself
try:
Draft7Validator.check_schema(schema)
print(" ✅ Schema is valid JSON Schema")
except Exception as e:
print(f" ❌ Schema validation failed: {e}")
return False
# Test config files
config_files = list(Path(".").glob("*example*.json"))
for config_file in config_files:
try:
with open(config_file, "r") as f:
config = json.load(f)
validate(instance=config, schema=schema)
print(f" ✅ {config_file.name} is valid")
except ValidationError as e:
print(f" ❌ {config_file.name} validation failed: {e.message}")
return False
except Exception as e:
print(f" ❌ Error validating {config_file.name}: {str(e)}")
return False
except ImportError:
print(" ⚠️ jsonschema not installed, installing...")
success, _, stderr = run_command(
[sys.executable, "-m", "pip", "install", "jsonschema"]
)
if not success:
print(f" ❌ Failed to install jsonschema: {stderr}")
return False
return test_schema_validation() # Retry after installation
return True
def test_unit_tests():
"""Test unit test execution"""
print("🔍 Testing unit tests...")
test_files = ["test_config_loader.py"]
for test_file in test_files:
if Path(test_file).exists():
success, stdout, stderr = run_command(
[sys.executable, "-m", "pytest", test_file, "-v", "--tb=short"]
)
if success:
print(f" ✅ Unit tests in {test_file} passed")
else:
print(f" ❌ Unit tests in {test_file} failed:")
print(f" stdout: {stdout}")
print(f" stderr: {stderr}")
return False
else:
print(f" ⚠️ Test file {test_file} not found")
return True
def test_config_loading():
"""Test configuration loading"""
print("🔍 Testing configuration loading...")
try:
from config_loader import ConfigurationLoader, create_default_config
# Test default config creation
try:
default_config = create_default_config()
print(" ✅ Default config created successfully")
except Exception as e:
print(f" ❌ Failed to create default config: {e}")
return False
# Test loading example configs
example_configs = list(Path(".").glob("*example*.json"))
for config_file in example_configs:
try:
loader = ConfigurationLoader(str(config_file))
config = loader.load_config()
print(f" ✅ {config_file.name} loaded successfully")
except Exception as e:
print(f" ❌ Failed to load {config_file.name}: {e}")
return False
except ImportError as e:
print(f" ⚠️ Could not import config_loader: {e}")
return True
def test_linting():
"""Test code linting with flake8"""
print("🔍 Testing code linting...")
python_files = list(Path(".").glob("*.py"))
if not python_files:
print(" ⚠️ No Python files found")
return True
# Test flake8 (exclude virtual environment and cache directories)
success, stdout, stderr = run_command(
[
"flake8",
".",
"--count",
"--select=E9,F63,F7,F82",
"--show-source",
"--statistics",
"--exclude=trading_env,venv,.venv,.git,.pytest_cache,__pycache__",
]
)
if success:
print(" ✅ Flake8 critical checks passed")
else:
print(f" ❌ Flake8 critical checks failed: {stdout} {stderr}")
return False
return True
def test_formatting():
"""Test code formatting with black"""
print("🔍 Testing code formatting...")
success, stdout, stderr = run_command(["black", "--check", "--diff", "."])
if success:
print(" ✅ Code formatting is correct")
else:
print(" ⚠️ Code formatting issues found (not critical for testing)")
return True
def run_pre_commit_test():
"""Run a subset of pre-commit hooks for testing"""
print("🔍 Testing pre-commit hooks...")
success, stdout, stderr = run_command(
["pre-commit", "run", "--all-files", "check-json"]
)
if success:
print(" ✅ Pre-commit JSON check passed")
else:
print(f" ❌ Pre-commit JSON check failed: {stdout} {stderr}")
return False
return True
def main():
"""Run all tests"""
print("🚀 Testing Trading Platform Pre-commit and CI Setup\n")
tests = [
("JSON Validation", test_json_validation),
("Schema Validation", test_schema_validation),
("Unit Tests", test_unit_tests),
("Configuration Loading", test_config_loading),
("Code Linting", test_linting),
("Code Formatting", test_formatting),
("Pre-commit Hooks", run_pre_commit_test),
]
passed = 0
failed = 0
for test_name, test_func in tests:
try:
if test_func():
passed += 1
else:
failed += 1
except Exception as e:
print(f" ❌ {test_name} failed with exception: {e}")
failed += 1
print()
print(f"📊 Test Results: {passed} passed, {failed} failed")
if failed == 0:
print("🎉 All tests passed! Pre-commit and CI setup is working correctly.")
return 0
else:
print("💥 Some tests failed. Please review the setup.")
return 1
if __name__ == "__main__":
sys.exit(main())