I'm trying to write a test using the django testing framework, the test spawns a new background process that has access the test datebase. The test looks like this,
temp_project/temp_app/tests.py
import subprocess
from django.test import TestCase
from temp_app.models import TempModel
# Create your tests here.
class TempTest(TestCase):
def setUp(self):
TempModel.objects.create()
def test_main(self):
self.assertEqual(str(TempModel.objects.all()) + '\n',
subprocess.check_output(['python', 'manage.py', 'temp_command']))
The subprocess simply prints out the contents of the database, temp_project/temp_app/management/commands/temp_command.py
from temp_app.models import TempModel
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **kwargs):
print TempModel.objects.all()
The model is an empty placeholder, temp_project/temp_app/models.py
from django.db import models
# Create your models here.
class TempModel(models.Model):
pass
However the output from the test looks like,
> python manage.py test
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_main (temp_app.tests.TempTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/dvoong/projects/opentrv/ors/source/temp/temp_project/temp_app/tests.py", line 15, in test_main
subprocess.check_output(['python', 'manage.py', 'temp_command']))
AssertionError: '[<TempModel: TempModel object>]\n' != '[]\n'
----------------------------------------------------------------------
Ran 1 test in 0.285s
FAILED (failures=1)
Destroying test database for alias 'default'...
So it seems the subprocess is accessing the production database instead of the test one. Any ideas? The database settings are, the default values,
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
The subprocess not using the test database is to be expected since you the subprocess isn't running a test command anyway. The solution would be to create a new settings file and pass it as a parameter to your subprocess using the --settings
parameter. Naturally this new settings file should point to the test database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With