Visual Studio Code下Django应用程序单元测试的问题

时间:2019-04-29 21:39:48

标签: django unit-testing django-models visual-studio-code vscode-settings

我有一个Django项目的草稿,其中添加了一个应用程序(例如my_app)。在这个应用程序中,我放置了带有一个测试的tests.py文件:

import unittest

class Test_MyModel(unittest.TestCase):
  def test_dummy(self):
    self.assertEqual(1,1)

在这种情况下,该虚拟测试可以通过Visual Studio代码发现并可以在其中执行,也可以从命令行启动该测试:

python manage.py test

当我使用单元测试修改文件时,请从my_app中导入一些模型(放置在文件models.py中):

import unittest

from .models import MyModel # new added line

class Test_MyModel(unittest.TestCase):
  def test_dummy(self):
    self.assertEqual(1,1)

在这种情况下,我仍然可以从命令行运行测试而没有任何问题,但是VSC找不到我的测试,并且在VSC中的Python测试日志中我得到了错误:

======================================================================
ERROR: tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/myuser/Projects/backend/my_app/tests.py", line 3, in <module>
from my_app.models import MyModel
File "/Users/myuser/Projects/backend/my_app/models.py", line 4, in <module>
class MyModel(models.Model):
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

任何提示或建议如何解决此问题并完全在VSC下使用单元测试进行模型测试?

1 个答案:

答案 0 :(得分:0)

我已经找到解决问题的方法。我需要在my_app文件夹的init.py文件中添加以下几行。

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app_project.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()