我正在使用pytest,并且想使用参数化的pytest固定装置。如果我不使用类并运行pytest,则两个测试均会通过,但是在测试类中时,两个测试均会失败,但我无法弄清楚出了什么问题。
工作代码:
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}
无效的代码:
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}
错误:
TypeError: test_create_record_one() missing 1 required positional argument: 'db_fixture'
答案 0 :(得分:1)
您不能将unittest.TestCase
与pytest
固定装置混合使用。尽管pytest
知道unittest
并可以基于unittest.TestCase
执行有效的单元测试,但事实并非如此。
对于您而言,只需不要从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}
...