Debian Codegraph @

test/conftest.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import os
5 import sys
6 from typing import TYPE_CHECKING
7
8 import pytest
9
10 from beets import logging
11 from beets.autotag import Distance
12 from beets.dbcore.query import Query
13 from beets.test._common import DummyIO
14 from beets.test.helper import RUNNING_IN_CI, ConfigMixin, TestHelper
15 from beets.test.helper import is_importable as check_import
16 from beets.util import cached_classproperty
17
18 if TYPE_CHECKING:
19 from typing import TextIO
20
21
22 def skip_marked_items(items: list[pytest.Item], marker_name: str, reason: str):
23 for item in (i for i in items if i.get_closest_marker(marker_name)):
24 test_name = item.nodeid.split("::", 1)[-1]
25 item.add_marker(pytest.mark.skip(f"{reason}: {test_name}"))
26
27
28 def pytest_collection_modifyitems(
29 config: pytest.Config, items: list[pytest.Item]
30 ):
31 if not os.environ.get("INTEGRATION_TEST") == "true":
32 skip_marked_items(
33 items, "integration_test", "INTEGRATION_TEST=1 required"
34 )
35
36 if not os.environ.get("LYRICS_UPDATED") == "true":
37 skip_marked_items(
38 items, "on_lyrics_update", "No change in lyrics source code"
39 )
40
41 for item in items:
42 if marker := item.get_closest_marker("requires_import"):
43 force_ci = marker.kwargs.get("force_ci", True)
44 if (
45 force_ci
46 and RUNNING_IN_CI
47 # only apply this to our repository, to allow other projects to
48 # run tests without installing all dependencies
49 and os.environ.get("GITHUB_REPOSITORY", "") == "beetbox/beets"
50 ):
51 continue
52
53 modname = marker.args[0]
54 if not check_import(modname):
55 test_name = item.nodeid.split("::", 1)[-1]
56 item.add_marker(
57 pytest.mark.skip(
58 f"{modname!r} is not installed: {test_name}"
59 )
60 )
61
62
63 def pytest_configure(config: pytest.Config) -> None:
64 config.addinivalue_line(
65 "markers", "integration_test: mark a test as an integration test"
66 )
67 config.addinivalue_line(
68 "markers",
69 "on_lyrics_update: run test only when lyrics source code changes",
70 )
71 config.addinivalue_line(
72 "markers",
73 (
74 "requires_import(module, force_ci=True): run test only if module"
75 " is importable (use force_ci=False to allow CI to skip the test too)"
76 ),
77 )
78
79
80 def pytest_make_parametrize_id(config, val, argname):
81 """Generate readable test identifiers for pytest parametrized tests.
82
83 Provides custom string representations for:
84 - Query classes/instances: use class name
85 - Lambda functions: show abbreviated source
86 - Other values: use standard repr()
87 """
88 if inspect.isclass(val) and issubclass(val, Query):
89 return val.__name__
90
91 if inspect.isfunction(val) and val.__name__ == "<lambda>":
92 return inspect.getsource(val).split("lambda")[-1][:30]
93
94 return repr(val)
95
96
97 def pytest_assertrepr_compare(op, left, right):
98 if isinstance(left, Distance) or isinstance(right, Distance):
99 return [f"Comparing Distance: {float(left)} {op} {float(right)}"]
100 return None
101
102
103 class _CurrentStderrHandler(logging.StreamHandler): # type: ignore[type-arg]
104 """Write CLI logs to the active standard error stream.
105
106 Logging is bootstrapped when the CLI runs instead of when this module is
107 imported. That startup can happen while callers have temporarily replaced
108 ``sys.stderr`` for capture or redirection, such as pytest's per-test capture
109 streams. The handler must not retain the stream that happened to be active
110 during the first command invocation because that stream may later be closed.
111 Resolving the stream for each record keeps logs attached to the current CLI
112 environment.
113 """
114
115 @property
116 def stream(self) -> TextIO:
117 return sys.stderr
118
119 @stream.setter
120 def stream(self, stream: TextIO) -> None:
121 pass
122
123
124 @pytest.fixture(autouse=True)
125 def patch_logging_handler(monkeypatch):
126 """Ensure that beets logs are captured by pytest's capture system."""
127 monkeypatch.setattr(
128 "beets.ui._get_logging_handler", lambda: _CurrentStderrHandler()
129 )
130
131
132 @pytest.fixture(autouse=True)
133 def do_not_log_sources(monkeypatch):
134 monkeypatch.setattr("beets.config.log_sources", lambda _: None)
135
136
137 @pytest.fixture(autouse=True)
138 def clear_cached_classproperty():
139 cached_classproperty.cache.clear()
140
141
142 @pytest.fixture
143 def config():
144 """Provide a fresh beets configuration when requested."""
145 return ConfigMixin().config
146
147
148 @pytest.fixture
149 def io(
150 request: pytest.FixtureRequest,
151 monkeypatch: pytest.MonkeyPatch,
152 capteesys: pytest.CaptureFixture[str],
153 ) -> DummyIO:
154 """Fixture for tests that need controllable stdin and captured stdout.
155
156 This fixture builds a per-test ``DummyIO`` helper and exposes it to the
157 test. When used on a test class, it attaches the helper as ``self.io``
158 attribute to make it available to all test methods, including
159 ``unittest.TestCase``-based ones.
160 """
161 io = DummyIO(monkeypatch, capteesys)
162
163 if request.instance:
164 request.instance.io = io
165
166 return io
167
168
169 @pytest.fixture
170 def is_importable():
171 """Fixture that provides a function to check if a module can be imported."""
172
173 return check_import
174
175
176 # Inheriting from TestHelper gives each test function isolated state. Use the
177 # fixtures below instead when a broader scope is safe and the suite benefits
178 # from reusing the same helper instance.
179 @pytest.fixture(scope="session")
180 def session_helper():
181 """Share beets test state across the full test session.
182
183 Use this for suites that tolerate shared library contents and global
184 configuration. Tests should target specific records rather than assume a
185 completely fresh overall state.
186 """
187 with TestHelper() as helper:
188 yield helper
189
190
191 @pytest.fixture(scope="module")
192 def module_helper():
193 """Share beets test state within one test module.
194
195 Use this when tests in the same file can reuse setup and side effects, but
196 later modules should still begin from a clean environment.
197 """
198 with TestHelper() as helper:
199 yield helper
200
201
202 @pytest.fixture(scope="class")
203 def class_helper():
204 """Share beets test state within one test class.
205
206 Use this when methods in a class can build on the same setup, while nearby
207 classes still need independent libraries, files, or configuration.
208 """
209 with TestHelper() as helper:
210 yield helper