[TIP] configure a pytest fixture

oliver oliver.schoenborn at gmail.com
Tue Nov 15 18:32:04 PST 2016


Thanks for the reply Bruno. I've used something like that in some fixtures
(actually returning a closure / lambda which, when called from the test,
returns a configured object), but it seems a little counter-intuitive (the
premise being that fixtures return objects ready to be used). How about
overloading the item operator [], so "def test(fixture[a,b])" would be
implemented in a similar way to annotations like "Map[str, int]" but
fixture[a,b] would allow the fixture function to receive a, b as
parameters.
Oliver

On Mon, 14 Nov 2016 at 17:40 Bruno Oliveira <nicoddemus at gmail.com> wrote:

> 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")'):
>     pass
>
> Do this:
>
> class Testdir:
>     def __init__(self, tmpdir):
>         pass
>     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
> function.
>
> If you give a more concrete example I might make another example.
>
> Hope that helps,
> Bruno.
>
>
>>
-- 
Oliver
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20161116/c3ebcfc5/attachment-0001.htm>


More information about the testing-in-python mailing list