-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrun_tests.py
More file actions
249 lines (194 loc) Β· 7.16 KB
/
run_tests.py
File metadata and controls
249 lines (194 loc) Β· 7.16 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
#!/usr/bin/env python3
"""Test runner script for TFKit."""
import argparse
import os
import subprocess
import sys
from pathlib import Path
def run_unit_tests(verbose=False, coverage=True):
"""Run unit tests."""
print("π§ͺ Running unit tests...")
cmd = ["python", "-m", "pytest", "tests/", "-m", "unit"]
if verbose:
cmd.append("-v")
if coverage:
cmd.extend([
"--cov=tfkit",
"--cov-report=term-missing",
"--cov-report=html:htmlcov"
])
result = subprocess.run(cmd)
return result.returncode == 0
def run_integration_tests(verbose=False):
"""Run integration tests."""
print("π Running integration tests...")
cmd = ["python", "-m", "pytest", "tests/", "-m", "integration"]
if verbose:
cmd.append("-v")
result = subprocess.run(cmd)
return result.returncode == 0
def run_all_tests(verbose=False, coverage=True, slow=False):
"""Run all tests."""
print("π Running all tests...")
cmd = ["python", "-m", "pytest", "tests/"]
if not slow:
cmd.extend(["-m", "not slow"])
if verbose:
cmd.append("-v")
if coverage:
cmd.extend([
"--cov=tfkit",
"--cov-report=term-missing",
"--cov-report=html:htmlcov"
])
result = subprocess.run(cmd)
return result.returncode == 0
def run_linting():
"""Run code linting."""
print("π Running code linting...")
# Check if flake8 is available
try:
result = subprocess.run(["flake8", "tfkit/", "--max-line-length=100"],
capture_output=True, text=True)
if result.returncode == 0:
print("β
Linting passed!")
return True
else:
print("β Linting failed:")
print(result.stdout)
print(result.stderr)
return False
except FileNotFoundError:
print("β οΈ flake8 not found, skipping linting")
print(" Install with: pip install flake8")
return True
def run_type_checking():
"""Run type checking with mypy."""
print("π Running type checking...")
try:
result = subprocess.run(["mypy", "tfkit/", "--ignore-missing-imports"],
capture_output=True, text=True)
if result.returncode == 0:
print("β
Type checking passed!")
return True
else:
print("β Type checking failed:")
print(result.stdout)
print(result.stderr)
return False
except FileNotFoundError:
print("β οΈ mypy not found, skipping type checking")
print(" Install with: pip install mypy")
return True
def check_test_coverage():
"""Check test coverage and report."""
if not Path("htmlcov").exists():
print("β οΈ No coverage report found. Run tests with --coverage first.")
return
try:
# Open coverage report
coverage_file = Path("htmlcov/index.html")
if coverage_file.exists():
print(f"π Coverage report available at: {coverage_file.absolute()}")
# Show coverage summary
result = subprocess.run(["python", "-m", "coverage", "report"],
capture_output=True, text=True)
if result.returncode == 0:
print("π Coverage Summary:")
print(result.stdout)
except FileNotFoundError:
print("β οΈ coverage not found")
def setup_test_environment():
"""Setup test environment."""
print("π§ Setting up test environment...")
# Set environment variables for testing
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["OMP_NUM_THREADS"] = "1"
# Check if required packages are installed
required_packages = ["pytest", "torch", "transformers"]
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"β Missing required packages: {', '.join(missing_packages)}")
print(" Install with: pip install -r requirements.txt")
return False
print("β
Test environment ready!")
return True
def clean_test_artifacts():
"""Clean test artifacts."""
print("π§Ή Cleaning test artifacts...")
artifacts = [
".pytest_cache",
"htmlcov",
".coverage",
"__pycache__",
"*.pyc"
]
for artifact in artifacts:
path = Path(artifact)
if path.exists():
if path.is_dir():
import shutil
shutil.rmtree(path)
else:
path.unlink()
# Clean pycache directories recursively
for pycache in Path(".").rglob("__pycache__"):
import shutil
shutil.rmtree(pycache)
print("β
Test artifacts cleaned!")
def main():
"""Main test runner."""
parser = argparse.ArgumentParser(description="TFKit Test Runner")
parser.add_argument("--unit", action="store_true", help="Run unit tests only")
parser.add_argument("--integration", action="store_true", help="Run integration tests only")
parser.add_argument("--lint", action="store_true", help="Run linting only")
parser.add_argument("--type-check", action="store_true", help="Run type checking only")
parser.add_argument("--coverage", action="store_true", default=True, help="Generate coverage report")
parser.add_argument("--no-coverage", action="store_false", dest="coverage", help="Skip coverage report")
parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
parser.add_argument("--slow", action="store_true", help="Include slow tests")
parser.add_argument("--clean", action="store_true", help="Clean test artifacts and exit")
parser.add_argument("--setup", action="store_true", help="Setup test environment and exit")
args = parser.parse_args()
# Handle special commands
if args.clean:
clean_test_artifacts()
return 0
if args.setup:
success = setup_test_environment()
return 0 if success else 1
# Setup environment
if not setup_test_environment():
return 1
success = True
# Run specific tests
if args.unit:
success &= run_unit_tests(args.verbose, args.coverage)
elif args.integration:
success &= run_integration_tests(args.verbose)
elif args.lint:
success &= run_linting()
elif args.type_check:
success &= run_type_checking()
else:
# Run all tests and checks
success &= run_linting()
success &= run_type_checking()
success &= run_all_tests(args.verbose, args.coverage, args.slow)
# Show coverage report if generated
if args.coverage and (not args.lint and not args.type_check):
check_test_coverage()
# Summary
if success:
print("\nβ
All tests passed!")
return 0
else:
print("\nβ Some tests failed!")
return 1
if __name__ == "__main__":
sys.exit(main())