gpt4 book ai didi

python - 如何以交互方式获取 pytest fixture?

转载 作者:太空狗 更新时间:2023-10-30 02:38:49 25 4
gpt4 key购买 nike

如何在不使用断点的情况下导入或绑定(bind) pytest fixture 以供交互使用?

例如,我想探索 tmpdir_factory 的一些行为REPL 中的 fixture 。

from pytest import tmpdir_factory  # note: this doesn't actually work

# setup / context has already been entered
tmpdir_factory.ensure('exists.txt', file=True) # I can use the fixture
del tmpdir_factory # teardown will eventually be called

tmpdir 的情况下,我已经知道它只是一个 py.path.local 实例,但我也对用户定义的固定装置的一般问题感兴趣。


编辑:另一个可接受的接口(interface):

from magical_module import inject_fixture
tmpdir_factory = inject_fixture('tmpdir_factory')

编辑一个 MCVE 以显示上下文是否已退出:

# conftest.py
from datetime import datetime
import pytest

@pytest.fixture
def my_fixture():
obj = {'setup': datetime.now()}
yield (obj, f'yielded @ {datetime.now()!r}')
obj['teardown'] = datetime.now()

最佳答案

Call IPython.embed() to drop into IPython's REPL ,并使用 request fixture's getfixturevalue()访问任意 fixture 值的方法

def test_stuff(request):
from IPython import embed
embed()

注意:pytest 必须使用-s 标志 运行到disable capturing of stdout/stderr

$ pytest -s
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: /home/they4kman/.virtualenvs/tmp-26171665bd77f5/src, inifile:
collected 1 item

test_stuff.py Python 3.6.2 (default, Jul 20 2017, 08:43:29)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: request.getfixturevalue('tmpdir_factory')
Out[1]: <_pytest.tmpdir.TempdirFactory at 0x7f71a7d501d0>

IPython must be installed , 当然 ;)

关于python - 如何以交互方式获取 pytest fixture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45970572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com