Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a pytest fixture interactively?

Tags:

python

pytest

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()
like image 882
wim Avatar asked Aug 30 '17 22:08

wim


People also ask

Can a pytest fixture be a test?

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.

What is pytest fixture scope session?

Pytest fixtures have five different scopes: function, class, module, package, and session. The scope basically controls how often each fixture will be executed.

Can pytest fixtures use other fixtures?

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.


1 Answers

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 ;)

like image 55
theY4Kman Avatar answered Sep 21 '22 00:09

theY4Kman