Ari*_*iel 3 python django pytest django-rest-framework pytest-django
我正在使用 django-pytest 来测试 Django Rest Framework API。我有一个看起来像这样的测试模块:
class TestClass:
def test_station_is_created(self, db, api_client):
StationFactory(name='foo')
response = api_client.get(reverse('api:stations'))
assert response.status_code == 200
...
def test_no_stations(self, db, api_client):
response = api_client.get(reverse('api:stations'))
assert response.data['data'] == []
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我得到:
________________________________ TestClass.test_no_stations________________________________
path/to/test/module.py:11: in test_no_stations
E assert [OrderedDict(...01251d92f')])] == []
E Left contains more items, first extra item: OrderedDict([...])
Run Code Online (Sandbox Code Playgroud)
如果我检查使用调试器返回的数据,我会看到它是在先前测试中创建的站,即使数据库似乎是空的:
ipdb> response.data['data'][0]['attributes']['name']
foo
ipdb> len(Station.objects.all())
0
Run Code Online (Sandbox Code Playgroud)
我不知道 pytest 是否在测试之间清除数据库。我怀疑正在使用多个数据库,但我的设置中只配置了一个。我虽然可能有一些缓存,但我阅读了 Django 测试客户端文档,但没有找到太多内容。我可能会错过什么?
发现问题所在了。我们也在使用django-cacheops,响应正在命中缓存,而不是再次运行查询。具有讽刺意味的是,我已经认为问题可能与缓存有关,但我禁用它的尝试失败了,并误导我排除它是问题的原因。最终我们找到了如何正确禁用它。
如果您使用cacheops和py.test,可以通过以下方法禁用测试缓存:
from cacheops import invalidate_all
@pytest.fixture(scope='function', autouse=True)
def invalidate_cache():
invalidate_all()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2265 次 |
| 最近记录: |