Django models unittest\loader.py raise配置不正确

Django models unittest\loader.py raise配置不正确,django-models,loader,testcase,discovery,django-unittest,Django Models,Loader,Testcase,Discovery,Django Unittest,如果我在Django中添加单元测试文件,以下代码会导致问题: from myApp.models import anyModel 无法导入测试模块:测试应用程序。测试模型 回溯(最近一次呼叫最后一次): 提高配置不当( django.core.exceptions.impropertlyconfigured:请求的设置已安装\u应用程序,但未配置设置。您必须定义环境变量django\u settings\u模块或调用设置。configure()在访问设置之前。经过一段时间的努力,我找到了原因并

如果我在Django中添加单元测试文件,以下代码会导致问题:

from myApp.models import anyModel
无法导入测试模块:测试应用程序。测试模型 回溯(最近一次呼叫最后一次):

提高配置不当(


django.core.exceptions.impropertlyconfigured:请求的设置已安装\u应用程序,但未配置设置。您必须定义环境变量django\u settings\u模块或调用设置。configure()在访问设置之前。

经过一段时间的努力,我找到了原因并修复了它。让我们首先解释一下问题:

1-错误情况是什么:

I found the fix like thius:

1- using pytest framework instead of unit test framework

2- pip install pytest-django

3- create pytest.ini and put it in the root of your project

4- add the following content in pytest.ini:

-- FILE: pytest.ini (or tox.ini)

[pytest]

DJANGO_SETTINGS_MODULE = mysite.settings (mysite shoul be change to your web project name)

# -- recommended but optional:

python_files = tests.py test_*.py *_tests.py
您已在web项目中使用Django+VSCode,并希望通过使用VSCode测试面板来发现您的测试,并可能通过使用测试资源管理器单独调试您的测试。这是处理此作业的web参考:

如果按照以下步骤操作,则一切正常,但只要从models.py导入模型,如下所示:

  • 从myApp.models导入anyModel
您的测试发现将面临以下错误:

提高配置不当( django.core.exceptions.ImpropertlyConfigured:请求的设置已安装\u应用程序,但未配置设置。在访问设置之前,必须定义环境变量django\u settings\u MODULE或调用settings.configure()

2-错误的原因是什么:

I found the fix like thius:

1- using pytest framework instead of unit test framework

2- pip install pytest-django

3- create pytest.ini and put it in the root of your project

4- add the following content in pytest.ini:

-- FILE: pytest.ini (or tox.ini)

[pytest]

DJANGO_SETTINGS_MODULE = mysite.settings (mysite shoul be change to your web project name)

# -- recommended but optional:

python_files = tests.py test_*.py *_tests.py
如果遇到此错误,可以看到此命令行命令工作正常:

  • python manage.py测试
该问题与设置DJANGO_设置_模块有关

3-解决方案是什么:

I found the fix like thius:

1- using pytest framework instead of unit test framework

2- pip install pytest-django

3- create pytest.ini and put it in the root of your project

4- add the following content in pytest.ini:

-- FILE: pytest.ini (or tox.ini)

[pytest]

DJANGO_SETTINGS_MODULE = mysite.settings (mysite shoul be change to your web project name)

# -- recommended but optional:

python_files = tests.py test_*.py *_tests.py
最后一行将解决此问题

我使用了以下参考资料: