Skip to content

Commit a05c7d9

Browse files
committed
test: add test cases
Fix Repository throws exception when given a folder as path.
1 parent bfcca03 commit a05c7d9

File tree

4 files changed

+162
-2
lines changed

4 files changed

+162
-2
lines changed

grading_lib/repository.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self, path: str | Path, *args, **kwargs):
2929
if isinstance(path, str):
3030
path = Path(path)
3131

32-
if "".join(path.suffixes) == ".tar.gz":
32+
if path.is_file() and "".join(path.suffixes) == ".tar.gz":
3333
if sys.version_info < (3, 12, 0):
3434
self.temp_dir = tempfile.TemporaryDirectory()
3535
else:

tests/test_cli.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from click.testing import CliRunner
55

6+
from grading_lib.cli import summary_command
67
from grading_lib.cli.internal import collect_autograding_tests_command
78

89

@@ -39,3 +40,41 @@ def test_collect_autograding_tests_command():
3940
data = json.load(f)
4041
assert len(data["tests"]) == 1
4142
assert data["tests"][0]["name"] == "lorem-ipsum - cast some spells"
43+
44+
45+
def test_summary_command():
46+
runner = CliRunner()
47+
48+
# When there is no problem,
49+
result = runner.invoke(summary_command)
50+
assert result.exit_code == 0
51+
assert "Problem Count: 0" in result.output
52+
assert "Total Points: 0.0" in result.output
53+
54+
# When there is one problem,
55+
with runner.isolated_filesystem():
56+
problem_path = Path("lorem-ipsum")
57+
problem_path.mkdir()
58+
59+
with open(problem_path / "problem.toml", "w") as f:
60+
f.write("""
61+
[problem]
62+
name = "lorem-ipsum"
63+
difficulty = 1
64+
objective = "Example problem for testing the cli command"
65+
66+
[problem.tests.test-1]
67+
name = "cast some spells"
68+
setup = ""
69+
run = "python scripts/grade.py -k cast"
70+
input = ""
71+
output = ""
72+
comparison = "included"
73+
timeout = 10
74+
points = 25
75+
""")
76+
77+
result = runner.invoke(summary_command)
78+
assert result.exit_code == 0
79+
assert "Problem Count: 1" in result.output
80+
assert "Total Points: 25.0" in result.output

tests/test_common.py

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@
77

88
from grading_lib import is_debug_mode
99
from grading_lib.common import (
10+
BaseTestCase,
1011
get_mtime_as_datetime,
1112
get_seed_from_env,
1213
has_file_changed,
14+
populate_folder_with_filenames,
15+
run_executable,
1316
)
1417

1518

@@ -29,10 +32,23 @@ def test_is_debug_mode():
2932

3033

3134
def test_get_seed_from_env():
35+
"""
36+
If value is set, should properly parse and use it.
37+
38+
If not, the value should be the scaled time (to avoid same seed
39+
for multiple tests). Does not currently check if the return value is
40+
the scaled time.
41+
"""
3242
val = 123
3343
os.environ["test_SEED"] = str(val)
3444
assert get_seed_from_env("test_SEED") == val
3545

46+
val = "123not-a-number"
47+
os.environ["test_SEED"] = str(val)
48+
res = get_seed_from_env("test_SEED")
49+
assert isinstance(res, int)
50+
assert res != 0
51+
3652

3753
@pytest.fixture
3854
def a_temp_file():
@@ -45,9 +61,80 @@ def a_temp_file():
4561
def test_has_file_changed(a_temp_file):
4662
path = Path(a_temp_file.name)
4763

64+
# Take snapshot of the mtime.
4865
last_known_mtime = get_mtime_as_datetime(path)
4966
assert not has_file_changed(last_known_mtime, path)
5067

51-
time.sleep(2)
68+
# Modify the mtime and test.
69+
time.sleep(1.2)
5270
path.touch()
5371
assert has_file_changed(last_known_mtime, path)
72+
73+
# Take another snapshot.
74+
last_known_mtime = get_mtime_as_datetime(str(path))
75+
assert not has_file_changed(last_known_mtime, path)
76+
77+
78+
def test_populate_folder_with_filenames():
79+
with tempfile.TemporaryDirectory() as tmpdir:
80+
tmpdir_path = Path(tmpdir)
81+
82+
with pytest.raises(ValueError):
83+
(tmpdir_path / "a.txt").touch()
84+
populate_folder_with_filenames(tmpdir_path / "a.txt", ["a", "b", "c"])
85+
86+
with pytest.raises(ValueError):
87+
populate_folder_with_filenames(tmpdir_path / "src", ["a", "b", "c"])
88+
89+
with tempfile.TemporaryDirectory() as tmpdir:
90+
tmpdir_path = Path(tmpdir)
91+
92+
expected_files = ["a", "b", "c"]
93+
populate_folder_with_filenames(tmpdir, expected_files)
94+
95+
result_names = [item.name for item in tmpdir_path.iterdir()]
96+
97+
assert result_names == expected_files
98+
99+
100+
def test_run_executable():
101+
cmd_result = run_executable(["git", "version"])
102+
assert cmd_result.success
103+
assert "git version" in cmd_result.output
104+
105+
106+
def test_BaseTestCase():
107+
"""Tests for the BaseTestCase."""
108+
109+
# When with_temporary_dir is not specified,
110+
class ChildClsWithoutTempDir(BaseTestCase):
111+
pass
112+
113+
assert ChildClsWithoutTempDir.with_temporary_dir is False
114+
115+
# When with_temporary_dir is specified,
116+
class ChildClsWithTempDir(BaseTestCase):
117+
with_temporary_dir = True
118+
119+
instance = ChildClsWithTempDir()
120+
instance.setUp()
121+
try:
122+
assert instance.temporary_dir is not None
123+
assert isinstance(instance.temporary_dir_path, Path)
124+
finally:
125+
instance.tearDown()
126+
127+
128+
def test_BaseTestCase_assertArchiveFileIsGzip():
129+
class ChildClsWithTempDir(BaseTestCase):
130+
with_temporary_dir = True
131+
132+
instance = ChildClsWithTempDir()
133+
instance.setUp()
134+
135+
try:
136+
with tempfile.TemporaryFile() as tmp_file:
137+
with pytest.raises(AssertionError):
138+
instance.assertArchiveFileIsGzip(tmp_file)
139+
finally:
140+
instance.tearDown()

tests/test_repository.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import sys
2+
import tempfile
3+
from pathlib import Path
4+
5+
import pytest
6+
7+
from grading_lib.repository import Repository
8+
9+
10+
@pytest.fixture
11+
def an_empty_folder():
12+
if sys.version_info < (3, 12, 0):
13+
temp_dir = tempfile.TemporaryDirectory()
14+
else:
15+
temp_dir = tempfile.TemporaryDirectory(delete=False)
16+
yield temp_dir
17+
temp_dir.cleanup()
18+
19+
20+
def test_Repository_init(an_empty_folder):
21+
repo = Repository(an_empty_folder.name)
22+
assert isinstance(repo.working_tree_dir, Path)
23+
24+
25+
def test_Repository_create_and_add_random_file(an_empty_folder):
26+
repo = Repository(an_empty_folder.name)
27+
assert isinstance(repo.working_tree_dir, Path)
28+
29+
repo.create_and_add_random_file(name="a.txt")
30+
assert len(repo.repo.index.entries) == 1
31+
assert next(iter(repo.repo.index.entries.keys()))[0] == "a.txt"
32+
33+
repo.create_and_add_random_file()
34+
assert len(repo.repo.index.entries) == 2

0 commit comments

Comments
 (0)