小编典典

应用具有测试目录时,在Django中运行特定的测试用例

django

Django文档(http://docs.djangoproject.com/zh-CN/1.3/topics/testing/#running-tests)指出,你可以通过指定单个测试用例来运行它们:

$ ./manage.py test animals.AnimalTestCase

假设你将测试保存在Django应用程序的tests.py文件中。如果是这样,那么此命令将按预期工作。

我在tests目录中有针对Django应用程序的测试:

my_project/apps/my_app/
├── __init__.py
├── tests
│   ├── __init__.py
│   ├── field_tests.py
│   ├── storage_tests.py
├── urls.py
├── utils.py
└── views.py

tests/__init__.py文件具有suite()函数:

import unittest

from my_project.apps.my_app.tests import field_tests, storage_tests

def suite():
    tests_loader = unittest.TestLoader().loadTestsFromModule
    test_suites = []
    test_suites.append(tests_loader(field_tests))
    test_suites.append(tests_loader(storage_tests))
    return unittest.TestSuite(test_suites)

要运行测试,我要做的是:

$ ./manage.py test my_app

尝试指定单个测试用例会引发异常:

$ ./manage.py test my_app.tests.storage_tests.StorageTestCase
...
ValueError: Test label 'my_app.tests.storage_tests.StorageTestCase' should be of the form app.TestCase or app.TestCase.test_method

我试图做异常消息说:

$ ./manage.py test my_app.StorageTestCase
...
ValueError: Test label 'my_app.StorageTestCase' does not refer to a test

当我的测试位于多个文件中时,如何指定单个测试用例?


阅读 492

收藏
2020-04-02

共2个答案

小编典典

结帐django-nose。它允许你指定测试运行方式:

python manage.py test another.test:TestCase.test_method

或如注释中所述,使用以下语法:

python manage.py test another.test.TestCase.test_method
2020-04-02
小编典典

从Django 1.6开始,你可以对要运行的元素使用完整的点符号来运行完整的测试用例或单个测试。

现在,自动测试发现将在工作目录下以test开头的任何文件中找到测试,因此解决了你必须重命名文件的问题,但是现在你可以将其保留在所需的目录中。如果要使用自定义文件名,则可以使用option标志指定一个模式(默认Django测试运行器)--pattern="my_pattern_*.py"

所以,如果你在你的manage.py目录,要运行的测试test_aTestCase子A在文件中,tests.py应用程序在/模块example,你会怎么做:

python manage.py test example.tests.A.test_a
2020-04-02