fork/mons

git clone https://git.julia.blue/fork/mons

coloursofnoiseMerge branch 'version-parsing' into mainc43b1d6

fixes
5.4 KiB193 linesraw
1import argparse
2import os
3import sys
4import urllib.request
5import zipfile
6from contextlib import contextmanager
7
8import pytest
9
10from mons.install import find_celeste_asm
11from mons.version import Version
12
13PLATFORM_MARKS = set("darwin linux win32".split())
14
15
16def path_exists(path):
17    if os.path.exists(path):
18        try:
19            return find_celeste_asm(path)
20        except FileNotFoundError as e:
21            raise argparse.ArgumentTypeError(e)
22    raise argparse.ArgumentTypeError(f"Path {path} does not exist.")
23
24
25def pytest_addoption(parser: pytest.Parser, pluginmanager):
26    parser.addoption(
27        "--mons-test-install", "--mons", type=path_exists, dest="mons_test_install"
28    )
29
30
31def pytest_configure(config: pytest.Config):
32    for plat in PLATFORM_MARKS:
33        config.addinivalue_line(
34            "markers", f"{plat}: mark this test as platform-specific"
35        )
36    config.addinivalue_line("markers", "prioritize: prioritize this test")
37    config.addinivalue_line(
38        "markers", "must_pass: this test must pass in order to continue"
39    )
40    config.addinivalue_line(
41        "markers", "data_file_zip: pass arguments to the data_file_zip fixture"
42    )
43    config.addinivalue_line(
44        "markers",
45        "data_file_download: pass arguments to the data_file_download fixture",
46    )
47    config.addinivalue_line(
48        "markers",
49        "mock_filesystem: pass arguments to the mock_filesystem fixture",
50    )
51
52
53@pytest.hookimpl(tryfirst=True)  # pyright:ignore[reportUntypedFunctionDecorator]
54def pytest_collection_modifyitems(session, config, items):
55    items.sort(key=lambda i: 0 if i.get_closest_marker("prioritize") else 1)
56
57
58must_pass_failed = None
59
60
61# https://stackoverflow.com/a/59392344
62def pytest_runtest_makereport(item, call):
63    global must_pass_failed
64    if not must_pass_failed and item.get_closest_marker(name="must_pass"):
65        if call.excinfo is not None:
66            must_pass_failed = item
67
68
69def pytest_runtest_setup(item):
70    # must_pass test checks
71    if must_pass_failed is not None:
72        pytest.skip(f"must_pass test failed ({must_pass_failed.name})")
73
74    # platform-specific test checks
75    supported_platforms = PLATFORM_MARKS.intersection(
76        mark.name for mark in item.iter_markers()
77    )
78    plat = sys.platform
79    if supported_platforms and plat not in supported_platforms:
80        pytest.skip("cannot run on platform {}".format(plat))
81
82
83def pytest_make_parametrize_id(config, val, argname):
84    if isinstance(val, Version):
85        return str(val)
86
87
88@pytest.fixture
89def data_file(request, tmp_path):
90    data = request.param
91    data_file = os.path.join(tmp_path, "data_file")
92
93    # indicator for missing file
94    if data is None:
95        yield data_file
96        return
97
98    with open(data_file, "w") as file:
99        file.write(data)
100    yield data_file
101
102
103@pytest.fixture
104def data_file_zip(request: pytest.FixtureRequest, tmp_path):
105    marker = request.node.get_closest_marker("data_file_zip")
106    data = marker.args[0] if marker else request.param
107    filenames = []
108    for i, file in enumerate(data if isinstance(data, list) else [data]):
109        filenames.append(os.path.join(tmp_path, f"data_file_{i}.zip"))
110        # indicator for missing file
111        if data is None:
112            continue
113
114        with zipfile.ZipFile(filenames[i], "w") as zip:
115            for filename, filedata in file.items():
116                zip.writestr(filename, filedata)
117    yield tuple(filenames)
118
119
120@pytest.fixture
121def data_file_download(request: pytest.FixtureRequest, cache):
122    marker = request.node.get_closest_marker("data_file_download")
123    url, filename = marker.args if marker else request.param
124    dest = os.path.join(cache.mkdir("mons_" + request.module.__name__), filename)
125    if not os.path.exists(dest):
126        urllib.request.urlretrieve(url, dest)
127    assert os.path.isfile(dest), "File download failed"
128    yield dest
129
130
131@pytest.fixture
132def test_name(request):
133    yield request.node.name
134
135
136@pytest.fixture(autouse=True)
137def assertion_msg():
138    @contextmanager
139    def assertion_msg(msg: str):
140        try:
141            yield
142        except AssertionError as e:
143            e.args = (e.args[0] + "\n" + msg,)
144            raise
145
146    return assertion_msg
147
148
149@pytest.fixture()
150def mock_filesystem(request, tmp_path):
151    marker = request.node.get_closest_marker("mock_filesystem")
152    if marker:
153        mockup = marker.args[0]
154        walk = marker.kwargs.get("walk", False)
155    else:
156        mockup = request.param
157        walk = False
158    root = os.path.join(tmp_path, "mock_fs")
159    os.mkdir(root)
160
161    if not mockup:
162        yield root
163        return
164
165    paths = list()
166
167    def create_fs(root, mockup):
168        if isinstance(mockup, dict):
169            for dir, contents in mockup.items():
170                path = os.path.join(root, dir)
171                os.mkdir(path)
172                paths.append(path)
173                create_fs(path, contents)
174        elif isinstance(mockup, (list, tuple)):
175            for node in mockup:
176                create_fs(root, node)
177        else:
178            assert isinstance(mockup, str)
179            path = os.path.join(root, mockup)
180            if mockup.endswith("/"):
181                os.mkdir(path)
182            else:
183                with open(path, "x"):
184                    pass
185            paths.append(path)
186
187    create_fs(root, mockup)
188
189    # set consistent last modified/accessed times for created paths
190    for i, path in enumerate(paths):
191        os.utime(path, (i, i))
192
193    yield os.walk(root) if walk else root