[TIP] configure a pytest fixture

Bruno Oliveira nicoddemus at gmail.com
Mon Nov 14 14:40:10 PST 2016

On Mon, Nov 14, 2016 at 6:25 PM oliver oliver.schoenborn at gmail.com
<http://mailto:oliver.schoenborn@gmail.com> wrote:

I'd like to define a fixture that returns an object that depends on a
> parameter. The following can't work because the "a" parameter is expected
> to be another fixture:
> @pytest.fixture
> def some_fixture(a: int):
>       return something that depends on value of a
> class TestCase:
>     def test_1(self, some_fixture(a=123)):
>         use fixture return value for a=123
>     def test_2(self, some_fixture(a=456)):
>         use fixture return value for a=456
> Is my only option the good'ol function call, ie remove the fixture
> decorator and just call the some_fixture function from my tests?
One option is to return an object from the fixture, which you then can call
methods and pass the required parameter.

For example, instead of (which does not work btw):

@pytest.fixturedef makepyfile(filename, code):
    # creates a file with the given code
def test_1(makepyfile(filename='foo.py', code='print("hello")'):

Do this:

class Testdir:
    def __init__(self, tmpdir):
    def makepyfile(self, filename, code):
        # creates a file with the given code
@pytest.fixturedef testdir(tmpdir):
    return Testdir(tmpdir)
def test_1(testdir):
    testdir.makepyfile(filename='foo.py', code='print("hello")')

IOW, make an object which you can delay the desired call to inside a test

If you give a more concrete example I might make another example.

Hope that helps,

>-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20161114/274f51b8/attachment.htm>

More information about the testing-in-python mailing list