File: test_check_dependencies.py

package info (click to toggle)
matrix-synapse 1.146.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 79,996 kB
  • sloc: python: 261,671; javascript: 7,230; sql: 4,758; sh: 1,302; perl: 626; makefile: 207
file content (243 lines) | stat: -rw-r--r-- 9,572 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright 2022 The Matrix.org Foundation C.I.C.
# Copyright (C) 2023 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
# Originally licensed under the Apache License, Version 2.0:
# <http://www.apache.org/licenses/LICENSE-2.0>.
#
# [This file includes modifications made by New Vector Limited]
#
#

from contextlib import contextmanager
from os import PathLike
from pathlib import Path
from typing import Generator, cast
from unittest.mock import patch

from packaging.markers import default_environment as packaging_default_environment

from synapse.util.check_dependencies import (
    DependencyException,
    check_requirements,
    metadata,
)

from tests.unittest import TestCase


class DummyDistribution(metadata.Distribution):
    def __init__(self, version: str):
        self._version = version

    @property
    def version(self) -> str:
        return self._version

    def locate_file(self, path: str | PathLike) -> Path:
        raise NotImplementedError()

    def read_text(self, filename: str) -> None:
        raise NotImplementedError()


old = DummyDistribution("0.1.2")
old_release_candidate = DummyDistribution("0.1.2rc3")
new = DummyDistribution("1.2.3")
new_release_candidate = DummyDistribution("1.2.3rc4")
distribution_with_no_version = DummyDistribution(None)  # type: ignore[arg-type]

# could probably use stdlib TestCase --- no need for twisted here


class TestDependencyChecker(TestCase):
    @contextmanager
    def mock_installed_package(
        self, distribution: DummyDistribution | None
    ) -> Generator[None, None, None]:
        """Pretend that looking up any package yields the given `distribution`.

        If `distribution = None`, we pretend that the package is not installed.
        """

        def mock_distribution(name: str) -> DummyDistribution:
            if distribution is None:
                raise metadata.PackageNotFoundError
            else:
                return distribution

        with patch(
            "synapse.util.check_dependencies.metadata.distribution",
            mock_distribution,
        ):
            yield

    @contextmanager
    def mock_python_version(self, version: str) -> Generator[None, None, None]:
        """Override the marker environment to report the supplied `python_version`."""

        def fake_default_environment() -> dict[str, str]:
            env = cast(dict[str, str], dict(packaging_default_environment()))
            env["python_version"] = version
            env["python_full_version"] = f"{version}.0"
            return env

        with patch(
            "synapse.util.check_dependencies.default_environment",
            side_effect=fake_default_environment,
        ):
            yield

    def test_mandatory_dependency(self) -> None:
        """Complain if a required package is missing or old."""
        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=["dummypkg >= 1"],
        ):
            with self.mock_installed_package(None):
                self.assertRaises(DependencyException, check_requirements)
            with self.mock_installed_package(old):
                self.assertRaises(DependencyException, check_requirements)
            with self.mock_installed_package(new):
                # should not raise
                check_requirements()

    def test_version_reported_as_none(self) -> None:
        """Complain if importlib.metadata.version() returns None.

        This shouldn't normally happen, but it was seen in the wild
        (https://github.com/matrix-org/synapse/issues/12223).
        """
        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=["dummypkg >= 1"],
        ):
            with self.mock_installed_package(distribution_with_no_version):
                self.assertRaises(DependencyException, check_requirements)

    def test_checks_ignore_dev_dependencies(self) -> None:
        """Both generic and per-extra checks should ignore dev dependencies."""
        with (
            patch(
                "synapse.util.check_dependencies.metadata.requires",
                return_value=["dummypkg >= 1; extra == 'mypy'"],
            ),
            patch("synapse.util.check_dependencies.RUNTIME_EXTRAS", {"cool-extra"}),
        ):
            # We're testing that none of these calls raise.
            with self.mock_installed_package(None):
                check_requirements()
                check_requirements("cool-extra")
            with self.mock_installed_package(old):
                check_requirements()
                check_requirements("cool-extra")
            with self.mock_installed_package(new):
                check_requirements()
                check_requirements("cool-extra")

    def test_generic_check_of_optional_dependency(self) -> None:
        """Complain if an optional package is old."""
        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=["dummypkg >= 1; extra == 'cool-extra'"],
        ):
            with self.mock_installed_package(None):
                # should not raise
                check_requirements()
            with self.mock_installed_package(old):
                self.assertRaises(DependencyException, check_requirements)
            with self.mock_installed_package(new):
                # should not raise
                check_requirements()

    def test_check_for_extra_dependencies(self) -> None:
        """Complain if a package required for an extra is missing or old."""
        with (
            patch(
                "synapse.util.check_dependencies.metadata.requires",
                return_value=["dummypkg >= 1; extra == 'cool-extra'"],
            ),
            patch("synapse.util.check_dependencies.RUNTIME_EXTRAS", {"cool-extra"}),
        ):
            with self.mock_installed_package(None):
                self.assertRaises(DependencyException, check_requirements, "cool-extra")
            with self.mock_installed_package(old):
                self.assertRaises(DependencyException, check_requirements, "cool-extra")
            with self.mock_installed_package(new):
                # should not raise
                check_requirements("cool-extra")

    def test_release_candidates_satisfy_dependency(self) -> None:
        """
        Tests that release candidates count as far as satisfying a dependency
        is concerned.
        (Regression test, see https://github.com/matrix-org/synapse/issues/12176.)
        """
        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=["dummypkg >= 1"],
        ):
            with self.mock_installed_package(old_release_candidate):
                self.assertRaises(DependencyException, check_requirements)

            with self.mock_installed_package(new_release_candidate):
                # should not raise
                check_requirements()

    def test_setuptools_rust_ignored(self) -> None:
        """
        Test a workaround for a `poetry build` problem. Reproduces
        https://github.com/matrix-org/synapse/issues/13926.
        """
        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=["setuptools_rust >= 1.3"],
        ):
            with self.mock_installed_package(None):
                # should not raise, even if setuptools_rust is not installed
                check_requirements()
            with self.mock_installed_package(old):
                # We also ignore old versions of setuptools_rust
                check_requirements()

    def test_python_version_markers_respected(self) -> None:
        """
        Tests that python_version markers are properly respected.

        Specifically that older versions of dependencies can be installed in
        environments with older Python versions.
        """
        requirements = [
            "pydantic ~= 2.8; python_version < '3.14'",
            "pydantic ~= 2.12; python_version >= '3.14'",
        ]

        with patch(
            "synapse.util.check_dependencies.metadata.requires",
            return_value=requirements,
        ):
            with self.mock_python_version("3.9"):
                with self.mock_installed_package(DummyDistribution("2.12.3")):
                    check_requirements()
                with self.mock_installed_package(DummyDistribution("2.8.1")):
                    check_requirements()
                with self.mock_installed_package(DummyDistribution("2.7.0")):
                    self.assertRaises(DependencyException, check_requirements)

            with self.mock_python_version("3.14"):
                with self.mock_installed_package(DummyDistribution("2.12.3")):
                    check_requirements()
                with self.mock_installed_package(DummyDistribution("2.8.1")):
                    self.assertRaises(DependencyException, check_requirements)
                with self.mock_installed_package(DummyDistribution("2.7.0")):
                    self.assertRaises(DependencyException, check_requirements)