【发布时间】:2016-03-08 13:45:27
【问题描述】:
我有一个包含两个方法的测试类,并希望在两个方法之间共享一个保存的模型实例。
我的灯具:
@pytest.fixture(scope='class')
def model_factory():
class ModelFactory(object):
def get(self):
x = Model(email='test@example.org',
name='test')
x.save()
return x
return ModelFactory()
@pytest.fixture(scope='class')
def model(model_factory):
m = model_factory.get()
return m
我的期望是在(两种)我的测试方法上只收到model 固定装置,并让它保持不变,并保存在数据库中:
@pytest.mark.django_db
class TestModel(object):
def test1(self, model):
assert model.pk is not None
Model.objects.get(pk=model.pk) # Works, instance is in the db
def test2(self, model):
assert model.pk is not None # model.pk is the same as in test1
Model.objects.get(pk=model.pk) # Fails:
# *** DoesNotExist: Model matching query does not exist
我已经使用--pdb 验证,在test1 结束时,运行Model.objects.all() 会返回我创建的单个实例。同时,psql 显示没有记录:
test_db=# select * from model_table;
id | ··· fields
(0 rows)
在test2 末尾的pdb 中运行Model.objects.all() 会返回一个空列表,考虑到该表是空的,这可能是正确的。
- 为什么我的模型没有被持久化,而查询仍然返回一个实例?
- 如果我的
model夹具标记为scope='class'并保存,为什么第二个测试中查询没有返回实例? (这是我最初的问题,直到我发现保存模型对数据库没有任何作用)
使用django 1.6.1、pytest-django 2.9.1、pytest 2.8.5
谢谢
【问题讨论】:
标签: django pytest pytest-django