File: test_scopes.py

package info (click to toggle)
picobox 4.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 248 kB
  • sloc: python: 1,666; makefile: 16
file content (287 lines) | stat: -rw-r--r-- 6,909 bytes parent folder | download
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"""Test picobox's scopes implementations."""

import contextvars as _contextvars
import threading

import pytest

import picobox


@pytest.fixture()
def singleton():
    return picobox.singleton()


@pytest.fixture()
def threadlocal():
    return picobox.threadlocal()


@pytest.fixture()
def contextvars():
    return picobox.contextvars()


@pytest.fixture()
def noscope():
    return picobox.noscope()


@pytest.fixture()
def exec_thread():
    """Run a given callback in a separate OS thread."""

    def executor(callback, *args, **kwargs):
        closure = {}

        def target():
            try:
                closure["ret"] = callback(*args, **kwargs)
            except Exception as e:
                closure["exc"] = e

        worker = threading.Thread(target=target)
        worker.start()
        worker.join()

        if "exc" in closure:
            raise closure["exc"]
        return closure["ret"]

    return executor


@pytest.fixture()
def exec_coroutine(request):
    """Run a given coroutine function in a separate event loop."""

    asyncio = pytest.importorskip("asyncio")
    loop = asyncio.new_event_loop()

    def executor(function, *args, **kwargs):
        if not asyncio.iscoroutinefunction(function):

            async def coroutine_function(*args, **kwargs):
                return function(*args, **kwargs)

        else:
            coroutine_function = function
        return loop.run_until_complete(coroutine_function(*args, **kwargs))

    try:
        yield executor
    finally:
        loop.close()


@pytest.fixture()
def exec_context():
    """Run a given callback in a separate context (PEP 567)."""

    def executor(callback, *args, **kwargs):
        context = _contextvars.copy_context()
        return context.run(callback, *args, **kwargs)

    return executor


@pytest.mark.parametrize(
    "scopename",
    [
        "singleton",
        "threadlocal",
        "contextvars",
    ],
)
def test_scope_set(request, scopename, supported_key, supported_value):
    scope = request.getfixturevalue(scopename)

    scope.set(supported_key, supported_value)
    assert scope.get(supported_key) is supported_value


def test_scope_set_noscope(supported_key, supported_value):
    scope = picobox.noscope()
    scope.set(supported_key, supported_value)

    with pytest.raises(KeyError, match=str(supported_key)):
        scope.get(supported_key)


@pytest.mark.parametrize(
    "scopename",
    [
        "singleton",
        "threadlocal",
        "contextvars",
    ],
)
def test_scope_set_overwrite(request, scopename):
    scope = request.getfixturevalue(scopename)
    value = object()

    scope.set("the-key", value)
    assert scope.get("the-key") is value

    scope.set("the-key", "overwrite")
    assert scope.get("the-key") == "overwrite"


@pytest.mark.parametrize(
    "scopename",
    [
        "singleton",
        "threadlocal",
        "contextvars",
        "noscope",
    ],
)
def test_scope_get_keyerror(request, scopename, supported_key):
    scope = request.getfixturevalue(scopename)

    with pytest.raises(KeyError, match=repr(supported_key)):
        scope.get(supported_key)


@pytest.mark.parametrize(
    "scopename",
    [
        "singleton",
        "threadlocal",
        "contextvars",
    ],
)
def test_scope_state_not_leaked(request, scopename):
    scope_a = request.getfixturevalue(scopename)
    value_a = object()

    scope_b = type(scope_a)()
    value_b = object()

    scope_a.set("the-key", value_a)
    assert scope_a.get("the-key") is value_a

    with pytest.raises(KeyError, match="the-key"):
        scope_b.get("the-key")

    scope_b.set("the-key", value_b)
    assert scope_b.get("the-key") is value_b

    scope_a.set("the-key", value_a)
    assert scope_a.get("the-key") is value_a


@pytest.mark.parametrize(
    ("scopename", "executor"),
    [
        ("singleton", "exec_thread"),
        ("singleton", "exec_coroutine"),
        ("singleton", "exec_context"),
        ("threadlocal", "exec_coroutine"),
        ("threadlocal", "exec_context"),
    ],
)
def test_scope_value_shared(request, scopename, executor):
    scope = request.getfixturevalue(scopename)
    value = object()
    exec_ = request.getfixturevalue(executor)

    exec_(scope.set, "the-key", value)
    assert exec_(scope.get, "the-key") is value


@pytest.mark.parametrize(
    ("scopename", "executor"),
    [
        ("threadlocal", "exec_thread"),
        ("contextvars", "exec_thread"),
        ("contextvars", "exec_coroutine"),
        ("contextvars", "exec_context"),
        ("noscope", "exec_thread"),
        ("noscope", "exec_coroutine"),
        ("noscope", "exec_context"),
    ],
)
def test_scope_value_not_shared(request, scopename, executor):
    scope = request.getfixturevalue(scopename)
    value = object()
    exec_ = request.getfixturevalue(executor)

    exec_(scope.set, "the-key", value)

    with pytest.raises(KeyError, match="the-key"):
        exec_(scope.get, "the-key")


@pytest.mark.parametrize(
    ("scopename", "executor"),
    [
        ("singleton", "exec_thread"),
        ("singleton", "exec_coroutine"),
        ("singleton", "exec_context"),
        ("threadlocal", "exec_thread"),
        ("threadlocal", "exec_coroutine"),
        ("threadlocal", "exec_context"),
        ("contextvars", "exec_thread"),
        ("contextvars", "exec_coroutine"),
        ("contextvars", "exec_context"),
    ],
)
def test_scope_value_downstack_shared(request, scopename, executor):
    scope = request.getfixturevalue(scopename)
    value = object()
    exec_ = request.getfixturevalue(executor)

    def caller():
        scope.set("the-key", value)
        return callee()

    def callee():
        return scope.get("the-key")

    assert exec_(caller) is value


@pytest.mark.parametrize(
    ("scopename", "executor"),
    [
        ("noscope", "exec_thread"),
        ("noscope", "exec_coroutine"),
        ("noscope", "exec_context"),
    ],
)
def test_scope_value_downstack_not_shared(request, scopename, executor):
    scope = request.getfixturevalue(scopename)
    value = object()
    exec_ = request.getfixturevalue(executor)

    def caller():
        scope.set("the-key", value)
        return callee()

    def callee():
        return scope.get("the-key")

    with pytest.raises(KeyError, match="the-key"):
        exec_(caller)


@pytest.mark.parametrize(
    ("scopename", "executor"),
    [
        ("threadlocal", "exec_thread"),
        ("contextvars", "exec_thread"),
        ("contextvars", "exec_coroutine"),
        ("contextvars", "exec_context"),
    ],
)
def test_scope_not_leaked(request, scopename, executor):
    scope = request.getfixturevalue(scopename)
    exec_ = request.getfixturevalue(executor)

    scope.set("a-key", "a-value")
    exec_(scope.set, "the-key", "the-value")

    with pytest.raises(KeyError, match="the-key"):
        scope.get("the-key")