fork/mons

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

coloursofnoiseMock all http requests in integration testse96fbdd

misc-fixes
3.0 KiB114 linesraw
1import json
2import os
3import pathlib
4from contextlib import contextmanager
5
6import click
7import pytest
8from click.testing import CliRunner
9
10from mons import downloading
11from mons import sources
12from mons.mons import cli as mons_cli
13
14
15def pytest_collection_modifyitems(session, config, items):
16    module = pathlib.Path(os.path.dirname(__file__))
17    for item in items:
18        if module == item.path.parent:
19            item.add_marker(pytest.mark.integration_test)
20
21
22def get_commands(cli, *, prefix=""):
23    for cmd in cli.commands.values():
24        if hasattr(cmd, "commands"):
25            yield from get_commands(cmd, prefix=prefix + f"{cmd.name} ")
26        else:
27            cmd.qualified_name = prefix + cmd.name
28            yield cmd
29
30
31@pytest.fixture(
32    scope="module",
33    params=list(get_commands(mons_cli)),
34    ids=lambda cmd: cmd.qualified_name,
35)
36def command(request):
37    yield request.param
38
39
40@pytest.fixture(scope="function")
41def ctx(runner):
42    @click.command
43    def cli():
44        pass
45
46    ctx = click.Context(cli)
47    with ctx:
48        yield ctx
49
50
51@pytest.fixture(scope="function")
52def runner():
53    """
54    runner.isolated_filesystem isn't necessary because mons never operates directly on the working directory
55    but if it did:
56
57    ```
58    with runner.isolated_filesystem(temp_dir=tmp_path):
59        yield runner
60    ```
61    """
62    return CliRunner()
63
64
65@pytest.fixture
66def runner_result(runner, assertion_msg):
67    @contextmanager
68    def runner_result(*args, **kwargs):
69        result = runner.invoke(*args, **kwargs)
70        error_msg = "=" * 10 + "\nCOMMAND OUTPUT\n\n" + result.output + "=" * 10
71        with assertion_msg(error_msg):
72            yield result
73
74    return runner_result
75
76
77@pytest.fixture(autouse=True)
78def mock_sources(monkeypatch, request: pytest.FixtureRequest):
79    _open_url = downloading.open_url
80
81    def mocked_open_url(request, *args, **kwargs):
82        if isinstance(request, str) and request.startswith("file://"):
83            return _open_url(request, *args, **kwargs)
84        pytest.fail(
85            f"Attempted to make a forbidden request. Currently patched: {implemented}"
86        )
87
88    implemented = list()
89    for module in (downloading, sources):
90        monkeypatch.setattr(
91            module,
92            "open_url",
93            mocked_open_url,
94        )
95
96    data_path = os.path.join(os.path.dirname(request.path), "_data")
97    requesters = [attr for attr in dir(sources) if attr.startswith("fetch_")]
98
99    for attr in requesters:
100        module_patch = getattr(request.module, attr, None)
101        if module_patch:
102            monkeypatch.setattr(sources, attr, module_patch)
103            implemented.append(attr)
104        elif os.path.exists(data_path) and attr[len("fetch_") :] in os.listdir(
105            data_path
106        ):
107            data_file = os.path.join(data_path, attr[len("fetch_") :])
108
109            def read_data_file(*args, **kwargs):
110                with open(data_file) as f:
111                    return json.load(f)
112
113            monkeypatch.setattr(sources, attr, read_data_file)
114            implemented.append(attr)