Skip to content

Commit

Permalink
add unit test for threaded stack context
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Gaultney committed Sep 9, 2021
1 parent 6794cd5 commit f7c0239
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
long_description_content_type="text/markdown",
packages=find_packages(),
package_data={"": ["py.typed"]},
python_requires=">=3.6",
python_requires=">=3.7", # contextvars
install_requires=["boto3 >= 1.9", "typing-extensions >= 3.7",],
# it is important to keep these install_requires basically in sync with the Pipfile as well.
)
23 changes: 23 additions & 0 deletions tests/xoto3/utils/stack_context_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from contextvars import ContextVar
from datetime import datetime
from multiprocessing.pool import ThreadPool

from xoto3.utils.oncall_default import OnCallDefault
from xoto3.utils.stack_context import StackContext, stack_context, unwrap
Expand Down Expand Up @@ -67,3 +68,25 @@ def g():
with ConsistentReadContext.set(True):
assert g() is True
assert g() is False


NumberContext = ContextVar("Number", default=-1)


def test_threaded_stack_context():
"""The idea behind context vars is that each thread gets its own
without anyone having to use thread.locals directly, and when paired with stack_context,
you can have nested contexts easily within the same thread.
"""
vals = list(range(10))

def extract_from_context():
return NumberContext.get()

def put_in_context(val):
with stack_context(NumberContext, val):
return extract_from_context()

out = ThreadPool(3).map(put_in_context, vals)

assert out == vals

0 comments on commit f7c0239

Please sign in to comment.