Skip to content
Advertisement

VSCode not using test database for Django tests

I’ve got an issue where VSCode’s test feature uses the production database instead of creating a test database. tests.py

from django.test import TestCase
# For VSCode test discovery
from django import setup
import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testing.settings")
setup()

class MyTestCase(TestCase):

    def test_some_test(self):
       SomeModel.objects.create()
       my_model = SomeModel.objects.all()
       assert len(SomeModel.objects.all()) == 1

I have previously created 1 instance of SomeModel, so if you do SomeModel.objects.all() in the shell, it returns a queryset with that one instance.

If I run this test from vscode’s tester it will fail. And when I debug it, I can see my_model have two instances of SomeModel in the queryset. It does not use a test database, and uses the production database

enter image description here

When I run this from python manage.py test my_app.tests it passes. And it outputs ‘Creating test database’ and ‘Destroying test database’ at the start and end of the test respectively. I assume this uses a test database.

How can I make VSCode use a test database for the tests and am I missing something?

Advertisement

Answer

Switch to pytest. Pytest does automatically create a test database for you

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement