The code is below. Two tests. The difference in settings: PostgreSQL and SQLite.
Being switched to SQLite, these tests pass. But in case of PostgreSQL this error occurs:
AssertionError: '/documents/1002/' != '/documents/1/'
- /documents/1002/
? ---
+ /documents/1/
I've always been using SQLite for learning purposes and thought that before every test the database is cleaned. But then I tried PostgreSQL and can see that this behaveiour seems to be connected with database management system rather than with TestCase algorithm.
Could you comment on this?
****VARIANT 1****
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'michael',
'PASSWORD': '***',
'HOST': 'localhost',
'PORT': '',
}
}
**VARIANT 2**
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
'USER': 'michael',
'PASSWORD': '***',
'HOST': 'localhost',
}
}
from django.test import TestCase
def create_master_document(title=None,
dated_from=today,
dated_through=today,
created_by=user,
creation_date=today):
title = title or "Some title"
md = MasterDocument.objects.create(title = title,
dated_from = dated_from,
dated_through = dated_through,
created_by = created_by,
creation_date = creation_date)
return md
class MasterDocumentTest(TestCase):
def test_0_create_master_document(self):
create_master_document()
number_of_mds = MasterDocument.objects.all().count()
self.assertEqual(number_of_mds, 1)
def test_1_create_multiple_master_documents(self):
for i in range(0, 1000):
create_master_document()
number_of_mds = MasterDocument.objects.all().count()
self.assertEqual(number_of_mds, 1000)
def test_2_get_absolute_url(self):
md = create_master_document()
url = md.get_absolute_url()
self.assertEqual(url, '/documents/1/')
No. The database is always cleared between test cases. The difference is how the database manages its autoincrement sequences; sqlite seems to reset them, but Postgres does not. You should not rely on either behaviour in your tests, but rather check specifically based on the ID of the relevant document.