Django Unit Testing in Visual Studio 2017 or 2019:

别说谁变了你拦得住时间么 提交于 2021-01-27 07:10:46

问题


Django needs setup code so unit tests on models that need a database will work. Standard Django unit test do that silently in the background but not with Visual Studio. I have not found a good way to provide setup code that will work for starting test runs from both the Visual Studio Test Explorer and with django manage.py test. Visual Studio Test Explorer does not call setUpModule/tearDownModule nor tearDownClass. The following code works from within VS, but I find it ugly, AND it doesn't work with nose/django-nose:

import os
import django
import unittest
from django.test.utils import setup_test_environment, teardown_test_environment
from django.test.utils import setup_databases, teardown_databases

try:
    os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test"
    setup_test_environment()
    print("Called setup_test_environment()")
    django.setup()
    old_config=setup_databases(1,False)
except:
    old_config=None

def tearDownModule():
    try:
        global old_config
        if old_config:
            teardown_test_environment()
            print("Called teardown_test_environment()")
            teardown_databases(old_config,1,False)
    except:
        pass

from unittest import TestCase # This needs to be called after django.setup 
from konsenser.models import Poll   

class PollTest(TestCase):

    @classmethod
    def setUpClass(cls):
        print("Setting up class")
        return super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        print("Tearing down class")
        return super().setUpClass()


    def setUp(self):
        Poll.objects.create(name='Test Poll', description='for testing')

    def test_content(self):
        poll=Poll.objects.get(id=1)
        name=f'{poll.name}'
        description=f'{poll.description}'
        self.assertDictEqual({'name':name,'description':description },
                             {'name':'Test Poll','description':'for testing'})


if __name__ == '__main__':
    unittest.main()

When run by VS Test Explorer, the output is

Called setup_test_environment()
Creating test database for alias 'default'...
Setting up class

So it doesn't tear down via my functions/methods. I cannot stick django.setup() into setUpClass because the model import needs django setup already. I wouldn't want to either because I want to create the test database just once and not repeatedly for all test classes.

Anbody any insight? I can't help but thinking I am doing this completely wrong...

来源:https://stackoverflow.com/questions/53678954/django-unit-testing-in-visual-studio-2017-or-2019

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!