Skip to content

Commit

Permalink
Remove top level await xdoctest fixture (#1098)
Browse files Browse the repository at this point in the history
This is now natively supported since [xdoctest
#158](Erotemic/xdoctest#158) has been released
so no need for the monkey patching fixture anymore.
  • Loading branch information
sdb9696 authored Aug 22, 2024
1 parent 4669e08 commit ae1ee38
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 62 deletions.
48 changes: 1 addition & 47 deletions kasa/tests/test_readme_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def test_tutorial_examples(readmes_mock):


@pytest.fixture
async def readmes_mock(mocker, top_level_await):
async def readmes_mock(mocker):
fixture_infos = {
"127.0.0.1": get_fixture_info("KP303(UK)_1.0_1.0.3.json", "IOT"), # Strip
"127.0.0.2": get_fixture_info("HS110(EU)_1.0_1.2.5.json", "IOT"), # Plug
Expand All @@ -155,49 +155,3 @@ async def readmes_mock(mocker, top_level_await):
"127.0.0.5": get_fixture_info("HS220(US)_1.0_1.5.7.json", "IOT"), # Dimmer
}
yield patch_discovery(fixture_infos, mocker)


@pytest.fixture
def top_level_await(mocker):
"""Fixture to enable top level awaits in doctests.
Uses the async exec feature of python to patch the builtins xdoctest uses.
See https://github.com/python/cpython/issues/78797
"""
import ast
from inspect import CO_COROUTINE
from types import CodeType

orig_exec = exec
orig_eval = eval
orig_compile = compile

def patch_exec(source, globals=None, locals=None, /, **kwargs):
if (
isinstance(source, CodeType)
and source.co_flags & CO_COROUTINE == CO_COROUTINE
):
asyncio.run(orig_eval(source, globals, locals))
else:
orig_exec(source, globals, locals, **kwargs)

def patch_eval(source, globals=None, locals=None, /, **kwargs):
if (
isinstance(source, CodeType)
and source.co_flags & CO_COROUTINE == CO_COROUTINE
):
return asyncio.run(orig_eval(source, globals, locals, **kwargs))
else:
return orig_eval(source, globals, locals, **kwargs)

def patch_compile(
source, filename, mode, flags=0, dont_inherit=False, optimize=-1, **kwargs
):
flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
return orig_compile(
source, filename, mode, flags, dont_inherit, optimize, **kwargs
)

mocker.patch("builtins.eval", side_effect=patch_eval)
mocker.patch("builtins.exec", side_effect=patch_exec)
mocker.patch("builtins.compile", side_effect=patch_compile)
38 changes: 24 additions & 14 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ toml = "*"
tox = "*"
pytest-mock = "*"
codecov = "*"
xdoctest = "*"
xdoctest = ">=1.2.0"
coverage = {version = "*", extras = ["toml"]}
pytest-timeout = "^2"
pytest-freezer = "^0.4"
Expand Down

0 comments on commit ae1ee38

Please sign in to comment.