简体   繁体   中英

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

在此处输入图像描述

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM