File: test_plugins.py

package info (click to toggle)
drgn 0.0.33-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,892 kB
  • sloc: python: 59,081; ansic: 51,400; awk: 423; makefile: 339; sh: 113
file content (218 lines) | stat: -rw-r--r-- 7,505 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# SPDX-License-Identifier: LGPL-2.1-or-later

import logging
import os
from pathlib import Path
import sys
import tempfile
import unittest.mock

import _drgn_util.plugins
from _drgn_util.plugins import call_plugins
from tests import TestCase, modifyenv


class TestPlugins(TestCase):
    def setUp(self):
        # Clear the plugin and hook caches before each test.
        _drgn_util.plugins._plugins = None
        _drgn_util.plugins._hooks.clear()

        # pkg_resources caches distributions on import. Delete it before each
        # test so that it is reloaded.
        sys.modules.pop("pkg_resources", None)

        # These tests change these environment variables and sys.path, so
        # restore them after each test.
        self.enterContext(
            modifyenv({"DRGN_PLUGINS": None, "DRGN_DISABLE_PLUGINS": None})
        )
        self.addCleanup(setattr, sys, "path", list(sys.path))

        # Delete modules imported by each test so that we can reuse the same
        # module names.
        def restore_modules(old_modules):
            for new_module in set(sys.modules) - old_modules:
                sys.modules.pop(new_module, None)

        self.addCleanup(restore_modules, set(sys.modules))

    @staticmethod
    def _create_plugin(dir):
        plugin_path = Path(dir) / "test_plugin.py"
        plugin_path.write_text(
            """\
def drgn_test_hook(call_me):
    call_me()
"""
        )
        return plugin_path

    @staticmethod
    def _create_dist_info(dir, module_name="test_plugin", entry_point_name="test"):
        dist_info_dir = Path(dir) / f"{module_name}-1.0.dist-info"
        dist_info_dir.mkdir()
        (dist_info_dir / "METADATA").write_text(
            f"""\
Metadata-Version: 1.1
Name: {module_name}
Version: 1.0
"""
        )
        (dist_info_dir / "entry_points.txt").write_text(
            f"""\
[drgn.plugins]
{entry_point_name} = {module_name}
"""
        )

    def test_entry_point(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            self._create_plugin(temp_dir)
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_called_once()

    def test_drgn_disable_plugins_envvar_all(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            self._create_plugin(temp_dir)
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)
            os.environ["DRGN_DISABLE_PLUGINS"] = "*"

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_not_called()

    def test_drgn_disable_plugins_envvar_specific(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            self._create_plugin(temp_dir)
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)
            os.environ["DRGN_DISABLE_PLUGINS"] = "foo,test"

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_not_called()

    def test_drgn_plugins_envvar_path(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            plugin_path = self._create_plugin(temp_dir)
            os.environ["DRGN_PLUGINS"] = f"test={plugin_path}"

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_called_once()

    def test_drgn_plugins_envvar_module(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            plugin_path = self._create_plugin(temp_dir)
            sys.path.insert(0, temp_dir)
            os.environ["DRGN_PLUGINS"] = f"test={plugin_path.stem}"

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_called_once()

    def test_drgn_plugins_envvar_precedence(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            self._create_plugin(temp_dir)
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)
            os.environ["DRGN_DISABLE_PLUGINS"] = "*"
            os.environ["DRGN_PLUGINS"] = "test"

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            call_me.assert_called_once()

    def test_priority(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            (Path(temp_dir) / "test_plugin1.py").write_text(
                """\
def drgn_test_hook(call_me):
    call_me(1)
drgn_test_hook.drgn_priority = 75
"""
            )
            (Path(temp_dir) / "test_plugin2.py").write_text(
                """\
def drgn_test_hook(call_me):
    call_me(2)
drgn_test_hook.drgn_priority = 25
"""
            )
            (Path(temp_dir) / "test_plugin3.py").write_text(
                """\
def drgn_test_hook(call_me):
    call_me(3)
"""
            )
            self._create_dist_info(temp_dir, "test_plugin1", "test1")
            self._create_dist_info(temp_dir, "test_plugin2", "test2")
            self._create_dist_info(temp_dir, "test_plugin3", "test3")
            sys.path.insert(0, temp_dir)

            call_me = unittest.mock.Mock()
            call_plugins("drgn_test_hook", call_me)
            self.assertEqual(
                call_me.call_args_list,
                [unittest.mock.call(2), unittest.mock.call(3), unittest.mock.call(1)],
            )

    def test_plugin_exception(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            (Path(temp_dir) / "test_plugin.py").write_text('raise Exception("foo")\n')
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)

            with self.assertLogs(logging.getLogger("drgn.plugins"), "WARNING") as cm:
                call_plugins("drgn_test_hook")
            self.assertTrue(
                any(
                    message.startswith("WARNING:drgn.plugins:failed to load 'test")
                    for message in cm.output
                ),
                msg=f"no match in {cm.output}",
            )

    def test_hook_exception(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            (Path(temp_dir) / "test_plugin.py").write_text(
                """\
def drgn_test_hook():
    raise Exception("foo")
"""
            )
            self._create_dist_info(temp_dir)
            sys.path.insert(0, temp_dir)

            with self.assertLogs(logging.getLogger("drgn.plugins"), "WARNING") as cm:
                call_plugins("drgn_test_hook")
            self.assertTrue(
                any(
                    message.startswith(
                        "WARNING:drgn.plugins:'test' drgn_test_hook failed:"
                    )
                    for message in cm.output
                ),
                msg=f"no match in {cm.output}",
            )

    def test_missing_entry_point(self):
        os.environ["DRGN_PLUGINS"] = "__non__existent__entrypoint__"
        with self.assertLogs(logging.getLogger("drgn.plugins"), "WARNING") as cm:
            call_plugins("drgn_test_hook")
        self.assertTrue(
            any(
                message.startswith(
                    "WARNING:drgn.plugins:not found: '__non__existent__entrypoint__'"
                )
                for message in cm.output
            ),
            msg=f"no match in {cm.output}",
        )