Code-Apprentice
Code-Apprentice

Reputation: 83577

Parameterizing tests with pytest

I am learning about parameterized tests with pyest. After following the relevant pytest documentation, I came up with this simple example:

import unittest

import pytest


@pytest.fixture(autouse=True, params=['foo', 'bar'])
def foo(request):
    print('fixture')
    print(request.param)


class Foo(unittest.TestCase):
    def setUp(self):
        print('unittest setUp()')

    def test(self):
        print('test')

This gives the following error:

Failed: The requested fixture has no parameter defined for the current test.
E               
E               Requested fixture 'foo' defined in:
E               tests/fixture.py:7

Line 7 is def foo(request):.

What causes this error and how do I fix it?

Upvotes: 1

Views: 2533

Answers (1)

PRMoureu
PRMoureu

Reputation: 13347

The goal of fixtures is to pass objects to the test cases, but the fixture you've made doesn't return or yield anything.

Then I'm not sure you can pass objects to a unittest TestCase method, i think it may create some conflicts with the self parameter.

On the other side, it can work with a simple function :

@pytest.fixture(autouse=True, params=['foo', 'bar'])
def foo(request):
    print('fixture')
    print(request.param)
    yield request.param

# class Foo(unittest.TestCase):
#     def setUp(self):
#         print('unittest setUp()')
# 
#     def _test(self):
#         print('test')

def test_fixture(foo):
    assert foo == 'foo'

>>>  1 failed, 1 passed in 0.05 seconds
# test 1 run with foo : OK
# test 2 run with bar : FAILED

EDIT :

Indeed : Why cant unittest.TestCases see my py.test fixtures?

Upvotes: 1

Related Questions