Skip to content

Commit 28b6d4c

Browse files
Allow Setup For Unittests
Adds the setup method as a special method for unittest question types. Additionally, a couple QoL fixes are included. I changed `unit` to `self` to clarify what it actually is, and I changed an `lstrip` to a `removeprefix` to avoid removing unintentional portions of the name (for instance `something` -> `omething`) Signed-off-by: Hassan Abouelela <hassan@hassanamr.com>
1 parent 7d4affd commit 28b6d4c

3 files changed

Lines changed: 10 additions & 6 deletions

File tree

backend/models/question.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ class Unittests(BaseModel):
1515
@validator("tests")
1616
def validate_tests(cls, value: _TESTS_TYPE) -> _TESTS_TYPE:
1717
"""Confirm that at least one test exists in a test suite."""
18-
if isinstance(value, dict) and len(value.keys()) == 0:
19-
raise ValueError("Must have at least one test in a test suite.")
18+
if isinstance(value, dict):
19+
keys = len(value.keys()) - (1 if "setUp" in value.keys() else 0)
20+
if keys == 0:
21+
raise ValueError("Must have at least one test in a test suite.")
2022

2123
return value
2224

backend/routes/forms/unittesting.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,10 @@ def _make_unit_code(units: dict[str, str]) -> str:
3636
result = ""
3737

3838
for unit_name, unit_code in units.items():
39+
test_prefix = "test_" if unit_name != "setUp" else ""
40+
3941
result += (
40-
f"\ndef test_{unit_name.lstrip('#')}(unit):" # Function definition
42+
f"\ndef {test_prefix}{unit_name.removeprefix('#')}(self):" # Function definition
4143
f"\n{indent(unit_code, ' ')}" # Unit code
4244
)
4345

@@ -83,7 +85,7 @@ async def execute_unittest(form_response: FormResponse, form: Form) -> list[Unit
8385
# Tests starting with an hashtag should have censored names.
8486
hidden_test_counter = count(1)
8587
hidden_tests = {
86-
test.lstrip("#").lstrip("test_"): next(hidden_test_counter)
88+
test.removeprefix("#").removeprefix("test_"): next(hidden_test_counter)
8789
for test in question.data["unittests"]["tests"].keys()
8890
if test.startswith("#")
8991
}

resources/unittest_template.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ def _main() -> None:
6464
if not result.wasSuccessful():
6565
RESULT.write(
6666
";".join(chain(
67-
(error[0]._testMethodName.lstrip("test_") for error in result.errors),
68-
(failure[0]._testMethodName.lstrip("test_") for failure in result.failures)
67+
(error[0]._testMethodName.removeprefix("test_") for error in result.errors),
68+
(failure[0]._testMethodName.removeprefix("test_") for failure in result.failures)
6969
))
7070
)
7171

0 commit comments

Comments
 (0)