Reputation: 9213
I am using pytest to and would like to use a parameterized pytest fixture. If I don't use a class and run pytest, both tests pass, but when inside a test class, the tests both fail, but I cannot figure out what is wrong.
Working Code:
import pytest
@pytest.fixture
def db_fixture():
def insert_records(data):
return data
db = insert_records
yield db
db = {} # reset fixture
def test_create_record_one(db_fixture):
result = db_fixture({"id": 1})
assert result == {"id": 1}
def test_create_record_two(db_fixture):
result = db_fixture({"id": 2})
assert result == {"id": 2}
Code that doesn't work:
import pytest
import unittest
class TestSample(unittest.TestCase):
@staticmethod
@pytest.fixture
def db_fixture():
def insert_records(data):
return data
db = insert_records
yield db
db = {} # reset fixture
@staticmethod
def test_create_record_one(db_fixture):
result = db_fixture({"id": 1})
assert result == {"id": 1}
@staticmethod
def test_create_record_two(db_fixture):
result = db_fixture({"id": 2})
assert result == {"id": 2}
Error:
TypeError: test_create_record_one() missing 1 required positional argument: 'db_fixture'
Upvotes: 1
Views: 1526
Reputation: 16815
You cannot mix unittest.TestCase
with pytest
fixtures. While pytest
knows about unittest
and can execute valid unit tests based on unittest.TestCase
, the reverse is not true.
In your case, simply do not derive from unittest.TestCase
:
class TestSample:
@staticmethod
@pytest.fixture
def db_fixture():
def insert_records(data):
return data
db = insert_records
yield db
db = {} # reset fixture
@staticmethod
def test_create_record_one(db_fixture):
result = db_fixture({"id": 1})
assert result == {"id": 1}
...
Upvotes: 1