Skip to content

Commit 7e635f2

Browse files
committedMar 10, 2025·
Attempted to add java to verifyer
1 parent 25a4500 commit 7e635f2

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed
 

‎teachprogramming/lib/verify_snippets/conftest.py

+23-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Inspired by
22
# https://docs.pytest.org/en/stable/example/nonpython.html#yaml-plugin
33

4+
import re
45
import json
56
from pathlib import Path
67
from typing import NamedTuple, Callable
@@ -46,6 +47,13 @@ def build_docker_language_runner(language) -> subprocess.CompletedProcess:
4647
# environ.get('TMPDIR') or environ.get('TEMP') or environ.get('TMP') or
4748
tempdir = Path('.').joinpath('_language_runner')
4849
tempdir.mkdir(exist_ok=True)
50+
def clear(path: Path):
51+
# https://docs.python.org/3/library/pathlib.html#pathlib.Path.walk
52+
for root, dirs, files in path.walk(top_down=False):
53+
for name in files:
54+
(root / name).unlink()
55+
for name in dirs:
56+
(root / name).rmdir()
4957

5058

5159
class ProjectItemSpec(NamedTuple):
@@ -90,18 +98,26 @@ def compile_test_python(spec: ProjectItemSpec):
9098
spec.exec_language(("python3", "-m", "py_compile", path_code_file.name))
9199

92100

93-
def compile_test_java(spec: ProjectItemSpec):
94-
# java? rename file?
95-
pass
101+
def get_java_main_classname(code: str) -> str:
102+
if match := re.search(r'class (\w+?) .*public static void main', code, re.DOTALL):
103+
return match.group(1)
104+
raise Exception('unable to find top level classname for filename')
96105

106+
def compile_test_java(spec: ProjectItemSpec):
107+
path_code_file = tempdir.joinpath(get_java_main_classname(spec.code) + ".java")
108+
path_code_file.write_text(spec.code)
109+
spec.exec_language(("javac", path_code_file.name))
97110

98111
def compile_test_csharp(spec: ProjectItemSpec):
99112
# csharp create manifest?
100113
pass
101114

102115

103116
LANGUAGES: MappingProxyType[str, Callable] = MappingProxyType(
104-
{"py": compile_test_python}
117+
{
118+
"py": compile_test_python,
119+
"java": compile_test_java,
120+
}
105121
)
106122

107123

@@ -127,9 +143,8 @@ def pytest_collect_file(parent: pytest.Dir, file_path: Path):
127143
# build_docker_language_runner(language)
128144

129145

130-
# TODO: correct hook for teardown
131-
#def pytest_teardown():
132-
# tempdir.cleanup()
146+
def pytest_sessionfinish(session: pytest.Session, exitstatus: int):
147+
clear(tempdir)
133148

134149

135150
class ProjectFile(pytest.File):
@@ -157,6 +172,7 @@ def runtest(self):
157172
if self.spec.language not in LANGUAGES.keys():
158173
raise pytest.skip.Exception(f"Unsupported language {self.spec.language}")
159174

175+
clear(tempdir)
160176
LANGUAGES[self.spec.language](self.spec)
161177

162178
# https://stackoverflow.com/questions/66037780/how-do-i-require-fixtures-in-a-pytest-plugin

0 commit comments

Comments
 (0)
Please sign in to comment.