How to import or otherwise bind a pytest
fixture for interactive use, without using breakpoints?
For example, I want to explore some behaviours of the tmpdir_factory
fixture in the REPL.
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
In the case of tmpdir
I already know it's just a py.path.local
instance, but I'm interested in the general question for user defined fixtures too.
edit: Another acceptable interface:
from magical_module import inject_fixture
tmpdir_factory = inject_fixture('tmpdir_factory')
edit: an MCVE to show whether context has exited or not:
# 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()
Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests.
Pytest fixtures have five different scopes: function, class, module, package, and session. The scope basically controls how often each fixture will be executed.
A fixture can use multiple other fixtures. Just like a test method can take multiple fixtures as arguments, a fixture can take multiple other fixtures as arguments and use them to create the fixture value that it returns.
Call IPython.embed()
to drop into IPython's REPL, and use the request
fixture's getfixturevalue()
method to access arbitrary fixture values
def test_stuff(request):
from IPython import embed
embed()
Note: pytest must be run with the -s
flag to 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, of course ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With