Repository navigation
Expand file tree
/
Copy pathbuild_workspace.py
More file actions
384 lines (304 loc) · 12.5 KB
/
Copy pathbuild_workspace.py
File metadata and controls
384 lines (304 loc) · 12.5 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""Build workspace.json and tests.json for BaiTapPyMi browser IDE.
workspace.json: Contains exercise file contents for loading into the editor.
tests.json: Maps each exercise filename to its adapted unittest code from
pyfml/tests, with imports rewritten for the browser's flat VFS.
"""
import ast
import glob
import json
import os
import re
import sys
# Modules/patterns that are incompatible with Pyodide's WASM sandbox.
# If a test method body references any of these, it will be marked as skipped.
INCOMPATIBLE_MARKERS = [
"tempfile.mkstemp",
"tempfile.mkstemp(",
"os.walk(",
"yaml.safe_load(",
"pickle.load(",
"configparser.ConfigParser",
"os.path.exists(",
'os.path.join(os.path.dirname(__file__)',
"os.path.dirname(__file__)",
"os.getcwd()",
'open(fn',
'open(__file__)',
"hashlib.md5(",
"os.__file__",
"time.sleep(",
"urllib.request.urlopen(",
"smtplib.",
]
def build_workspace():
"""Scan exercises/ directory and generate workspace.json."""
workspace = {}
exercises = glob.glob("exercises/*.py")
exercises.append("exercises/HUONGDAN.txt")
for ex in exercises:
if os.path.islink(ex):
continue
abs_ex = os.path.abspath(ex)
abs_dir = os.path.abspath("exercises")
if not abs_ex.startswith(abs_dir + os.sep):
continue
filename = os.path.basename(ex)
with open(ex, "r", encoding="utf-8") as f:
workspace[filename] = f.read()
with open("workspace.json", "w", encoding="utf-8") as f:
json.dump(workspace, f, indent=2)
print(f"Generated workspace.json with {len(workspace)} files.")
return workspace
def read_base_class():
"""Read the TestExercise base class from pyfml/tests/base.py and
enhance _test_all with subTest for per-case granular reporting."""
base_path = os.path.join("pyfml", "tests", "base.py")
if not os.path.exists(base_path):
print(f"Warning: {base_path} not found, tests.json will be empty.")
return None
with open(base_path, "r", encoding="utf-8") as f:
source = f.read()
# Remove the standalone 'import unittest' line since we'll add it ourselves
source = re.sub(r"^import unittest\s*$", "", source, flags=re.MULTILINE)
# Rewrite _test_all to use subTest for per-case reporting
source = source.replace(
""" def _test_all(self, func, cases):
for input_, expect in cases:
output = func(input_)
msg = self.MESSAGE_FMT.format(input_, expect, output)
self.assertEqual(output, expect, msg)""",
""" def _test_all(self, func, cases):
for input_, expect in cases:
with self.subTest(input=input_, expected=expect):
output = func(input_)
msg = self.MESSAGE_FMT.format(input_, expect, output)
self.assertEqual(output, expect, msg)"""
)
return source.strip()
def extract_test_methods(filepath):
"""Parse a test file and extract test class/method info using AST.
Returns a list of dicts:
[{"class_name": "TestExercise3", "method_name": "test_ex3_0",
"is_skipped": False, "source_lines": (start, end)}]
"""
with open(filepath, "r", encoding="utf-8") as f:
source = f.read()
try:
tree = ast.parse(source, filename=filepath)
except SyntaxError:
print(f"Warning: SyntaxError parsing {filepath}, skipping.")
return [], source
methods = []
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
class_name = node.name
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name.startswith(
"test_"
):
# Check for @unittest.skip decorator
is_skipped = False
for decorator in item.decorator_list:
if isinstance(decorator, ast.Attribute):
if decorator.attr == "skip":
is_skipped = True
elif isinstance(decorator, ast.Name):
if decorator.id == "skip":
is_skipped = True
methods.append(
{
"class_name": class_name,
"method_name": item.name,
"is_skipped": is_skipped,
"lineno": item.lineno,
"end_lineno": getattr(item, "end_lineno", None),
}
)
return methods, source
def method_name_to_exercise_file(method_name):
"""Convert a test method name to an exercise filename.
e.g. 'test_ex3_0' -> 'ex3_0.py'
'test_ex35_1' -> 'ex35_1.py'
'test_ex69_1' -> 'ex69_1.py'
"""
# Strip leading 'test_'
ex_name = method_name[5:] # remove 'test_'
return f"{ex_name}.py"
def adapt_test_source(source, base_class_code, target_exercise=None):
"""Transform test file source code for browser Pyodide execution.
- Replace 'from tests.base import TestExercise' -> inline base class
- Replace 'import exercises.X as X' -> 'import X'
- Strip imports for exercises OTHER than target_exercise to avoid
cross-contamination (e.g. importing browser-incompatible modules)
- Remove 'if __name__' blocks
- Remove standalone 'import unittest' (we prepend it)
"""
# Remove 'from tests.base import TestExercise'
adapted = re.sub(
r"^from tests\.base import TestExercise\s*$",
"",
source,
flags=re.MULTILINE,
)
# Determine the target module name (e.g. 'ex6_1' from 'ex6_1.py')
target_module = None
if target_exercise:
target_module = target_exercise.replace(".py", "")
# Transform 'import exercises.ex3_0 as ex3_0' -> 'import ex3_0'
# But strip imports for exercises OTHER than the target to prevent
# cross-contamination from incompatible modules in the same test file.
def _replace_exercise_import(match):
module_name = match.group(1)
if target_module and module_name != target_module:
return "" # Strip unrelated exercise import
return f"import {match.group(1)} as {match.group(2)}"
adapted = re.sub(
r"^import exercises\.(\w+) as (\w+)\s*$",
_replace_exercise_import,
adapted,
flags=re.MULTILINE,
)
# Remove standalone 'import unittest' (we'll prepend it)
adapted = re.sub(r"^import unittest\s*$", "", adapted, flags=re.MULTILINE)
# Remove 'if __name__ == "__main__":' block at the end
adapted = re.sub(
r'\nif __name__\s*==\s*["\']__main__["\']\s*:\s*\n\s*unittest\.main\(\)\s*$',
"",
adapted,
)
# Remove 'import sys' and sys.path hacks (from test_ex8.py)
adapted = re.sub(
r"^# hack path for importing.*$", "", adapted, flags=re.MULTILINE
)
adapted = re.sub(
r"^sys\.path\.insert\(.*\).*# NOQA\s*$",
"",
adapted,
flags=re.MULTILINE,
)
# Build final adapted source
final = f"import unittest\n\n{base_class_code}\n\n{adapted}"
# Clean up excessive blank lines
final = re.sub(r"\n{4,}", "\n\n\n", final)
return final
def check_method_compatibility(source, method_name, class_name):
"""Check if a specific test method uses browser-incompatible operations.
We extract the method body text and check for incompatible patterns.
"""
# Find the method body in the source
# Use a regex pattern to find the method definition and its body
pattern = rf"def {re.escape(method_name)}\(self\):"
match = re.search(pattern, source)
if not match:
return True, None # Can't find method, assume compatible
# Get text from method start to the next 'def ' or class end
start = match.start()
rest = source[start:]
# Find next method or class definition
next_def = re.search(r"\n def |\nclass |\Z", rest[1:])
if next_def:
method_body = rest[: next_def.start() + 1]
else:
method_body = rest
# Check for incompatible patterns
for marker in INCOMPATIBLE_MARKERS:
if marker in method_body:
return False, f"Uses incompatible operation: {marker}"
return True, None
def check_exercise_compatibility(exercise_file):
"""Check if an exercise source file uses browser-incompatible operations.
Scans the exercise source (not just the test) for patterns that won't
work in Pyodide/WASM, such as file I/O, network calls, or OS operations.
"""
exercise_path = os.path.join("exercises", exercise_file)
if not os.path.exists(exercise_path):
return True, None
with open(exercise_path, "r", encoding="utf-8") as f:
source = f.read()
for marker in INCOMPATIBLE_MARKERS:
if marker in source:
return False, f"Exercise uses incompatible operation: {marker}"
return True, None
def build_test_registry(workspace_files):
"""Scan pyfml/tests/ and generate the test registry.
Returns a dict mapping exercise filenames to test metadata.
"""
base_class_code = read_base_class()
if base_class_code is None:
return {}
test_files = sorted(glob.glob(os.path.join("pyfml", "tests", "test_ex*.py")))
if not test_files:
print("Warning: No test files found in pyfml/tests/")
return {}
registry = {}
abs_tests_dir = os.path.abspath(os.path.join("pyfml", "tests"))
for test_file in test_files:
# Defense-in-depth: skip symlinks and validate path stays within tests/
if os.path.islink(test_file):
continue
abs_test = os.path.abspath(test_file)
if not abs_test.startswith(abs_tests_dir + os.sep):
continue
methods, raw_source = extract_test_methods(test_file)
if not methods:
continue
# NOTE: adapted source is now generated per-exercise below
# to strip unrelated imports and avoid cross-contamination.
for method_info in methods:
exercise_file = method_name_to_exercise_file(method_info["method_name"])
# Skip if this exercise isn't in our workspace
if exercise_file not in workspace_files:
continue
# Determine skip status
skip = method_info["is_skipped"]
skip_reason = "Skipped by @unittest.skip decorator" if skip else None
# Check browser compatibility of the TEST method
if not skip:
compatible, reason = check_method_compatibility(
raw_source,
method_info["method_name"],
method_info["class_name"],
)
if not compatible:
skip = True
skip_reason = f"Browser incompatible: {reason}"
# Also check the EXERCISE source file for incompatible ops
if not skip:
compatible, reason = check_exercise_compatibility(exercise_file)
if not compatible:
skip = True
skip_reason = f"Browser incompatible: {reason}"
# Generate per-exercise adapted source (strips unrelated imports)
adapted_source = adapt_test_source(
raw_source, base_class_code, target_exercise=exercise_file
)
registry[exercise_file] = {
"testClass": method_info["class_name"],
"testMethod": method_info["method_name"],
"testCode": adapted_source,
"sourceFile": os.path.basename(test_file),
"skip": skip,
"skipReason": skip_reason,
}
return registry
def main():
# Phase 1: Build workspace.json
workspace = build_workspace()
# Phase 2: Build tests.json
registry = build_test_registry(workspace)
with open("tests.json", "w", encoding="utf-8") as f:
json.dump(registry, f, indent=2, ensure_ascii=False)
# Report summary
total = len(registry)
skipped = sum(1 for v in registry.values() if v["skip"])
runnable = total - skipped
print(f"Generated tests.json with {total} test entries:")
print(f" ✅ Runnable: {runnable}")
print(f" ⏭️ Skipped: {skipped}")
if skipped > 0:
print("\nSkipped tests:")
for ex_file, entry in sorted(registry.items()):
if entry["skip"]:
print(f" - {ex_file}: {entry['skipReason']}")
if __name__ == "__main__":
main()