Django test client vs. django-pytest

I'm using django-pytest to test a Django Rest Framework API. I have a test module that looks something like this:

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

When I run the tests, I get:

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

If I inspect the data returned with a debugger, I see it's the station created in the previous test, even though the database seems to be empty:

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

I don't know if pytest is clearing the database or not between tests. I suspected multiple databases are in use but I only have one configured in my settings. I though maybe there's some caching but I read the Django test client documentation and didn't find much. What could I be missing?

Answers


Found out what the problem was. We were also using django-cacheops and the response was hitting the cache instead of running the query again. The irony is I had already thought the problem could be cache related but my attempt of disabling it failed and misled me into ruling it out as the cause of the problem. Eventually we figured out how to properly disable it.

Here's a way you can disable caching for tests if you're using cacheops and py.test:

from cacheops import invalidate_all

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

pytest-django indeed isolate tests from each other by reverting transaction at the end of each test.

If you want to make sure your database doesn't have any Station before the test add at the beginning of test_no_stations:

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

If this is proven wrong, either you missed something in your pytest configuration either the issue is on your code.


Need Your Help

Get the index of the nth occurrence of a string?

c# .net string indexing indexof

Unless I am missing an obvious built-in method, what is the quickest way to get the nth occurrence of a string within a string?

Unfolding for processing 2.1 fails in JavaScript mode

javascript processing processing.js

I downloaded the just released Unfolding Maps for Processing 2.1 and the examples work fine in Java mode but fail to run in the JavaScript mode. Is there anything which can be done to make them