Skip to main content
 首页 » 编程设计

python之使用 python manage.py 测试应用程序的自定义 SimpleTestCase 子项的 ImportError

2024年10月17日8thcjp

我想为当前运行良好的 my_app 使用通用的自定义测试用例。我有以下简化的目录架构:

my_app 
├── tests 
│   ├── __init__.py 
│   └── test_views 
│       ├── __init__.py 
│       ├── custom_test.py 
│       ├── registration 
│       │   ├── __init__.py 
│       │   ├── test_login.py 
└── views 
    |── __init__.py 
    ├── registration 
    │   ├── __init__.py 
    │   ├── login.py 

CustomTest 类如下所示:

from django.test import SimpleTestCase 
from django.test.client import Client 
 
 
class CustomTest(SimpleTestCase): 
 
    def setUp(self): 
        self.client = Client() 

我要启动的测试如下:

from tests.test_views.custom_test import CustomTest 
 
class Test_Login(CustomTest): 
 
    def test_thing(self): 
        self.assertTrue(True) 

'my_app' 目录位于 pythonpath 中,每个模块都有一个 init.py 文件。 Django 可以在 test_login.py 中发现错误(例如,如果我将 CustomTest 更改为不存在的其他内容),因此在我真正的问题发生之前读取 test_login.py 并成功导入和使用 CustomTest。但是当我想启动测试时:

python manage.py test my_app 

我收到以下错误:

ImportError: Failed to import test module: my_app.tests.test_views.registration.test_login 
Traceback (most recent call last): 
  File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests 
    module = self._get_module_from_name(name) 
  File "/usr/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name 
    __import__(name) 
  File "~/workspace/my_app/my_app/tests/test_views/registration/test_login.py", line 7, in <module> 
    from tests.tests_views.my_app_test.custom_test import CustomTest 
ImportError: No module named tests_views.my_app_test.custom_test 

有什么想法吗?

请您参考如下方法:

将应用名称放在import的左边:

from myapp.tests.test_views.custom_test import CustomTest