2015-12-03 80 views
3

我正在使用django-pytest來測試Django Rest框架API。我有一個測試模塊,它看起來是這樣的:Django測試客戶端與Django-pytest

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'] == [] 

當我運行測試,我得到:

________________________________ 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([...]) 

如果我檢查與調試器返回的數據,我看到它的創建站在之前的測試中,即使數據庫似乎是空的:

ipdb> response.data['data'][0]['attributes']['name'] 
foo 
ipdb> len(Station.objects.all()) 
0 

我不知道,如果是pytest清除數據庫,或者沒有測試之間。我懷疑有多個數據庫正在使用,但我只有一個配置在我的設置中。我雖然也許有一些緩存,但我讀了Django測試客戶端文檔,並沒有發現太多。我可能會錯過什麼?

回答

1

pytest-django確實通過在每次測試結束時還原事務來隔離彼此的測試。

如果你想確保你的數據庫中沒有任何站測試在test_no_stations開頭添加前:

assert not Station.objects.all().exist() 

如果這被證明是錯誤的,要麼你錯過了你的pytest配置無論是東西問題出在你的代碼上。

4

找出問題所在。我們還使用django-cacheops,響應是擊中緩存而不是再次運行查詢。具有諷刺意味的是,我已經認爲這個問題可能與緩存有關,但是我禁用它的嘗試失敗了,並且誤導我將其排除爲導致問題的原因。最終我們想出瞭如何正確禁用它。

這裏是你,如果你正在使用cacheops和py.test禁用測試緩存的方式:

from cacheops import invalidate_all 

@pytest.fixture(scope='function', autouse=True) 
def invalidate_cache(): 
    invalidate_all()