hek*_*ran 148 python django unit-testing
Django文档(http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests)表示您可以通过指定它们来运行单个测试用例:
$ ./manage.py test animals.AnimalTestCase
Run Code Online (Sandbox Code Playgroud)
这假设您在Django应用程序的tests.py文件中进行了测试.如果这是真的,那么这个命令就像预期的那样工作.
我在测试目录中测试了Django应用程序:
my_project/apps/my_app/
??? __init__.py
??? tests
? ??? __init__.py
? ??? field_tests.py
? ??? storage_tests.py
??? urls.py
??? utils.py
??? views.py
Run Code Online (Sandbox Code Playgroud)
该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)
Run Code Online (Sandbox Code Playgroud)
要运行测试我做:
$ ./manage.py test my_app
Run Code Online (Sandbox Code Playgroud)
尝试指定单个测试用例会引发异常:
$ ./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
Run Code Online (Sandbox Code Playgroud)
我试着做异常消息说的话:
$ ./manage.py test my_app.StorageTestCase
...
ValueError: Test label 'my_app.StorageTestCase' does not refer to a test
Run Code Online (Sandbox Code Playgroud)
当我的测试在多个文件中时,如何指定单个测试用例?
cri*_*pes 155
从Django 1.6开始,您可以运行完整的测试用例或单个测试,使用完整的点符号表示您要运行的元素.
现在,自动测试发现将在工作目录下以test开头的任何文件中找到测试,因此解决了您必须重命名文件的问题,但现在可以将它们保存在所需的目录中.如果要使用自定义文件名,可以使用选项标志指定模式(默认Django测试运行器)--pattern="my_pattern_*.py"
.
因此,如果您在manage.py
目录中并希望在app/module下的文件test_a
内运行TestCase
子类A
内的测试,您将执行以下操作:tests.py
example
python manage.py test example.tests.A.test_a
Run Code Online (Sandbox Code Playgroud)
如果您不想包含依赖项,并且在Django 1.6或更高版本中就是这样做的.
Sam*_*lan 142
结帐django-nose.它允许您指定要运行的测试:
python manage.py test another.test:TestCase.test_method
Run Code Online (Sandbox Code Playgroud)
或者如评论中所述,使用语法:
python manage.py test another.test.TestCase.test_method
Run Code Online (Sandbox Code Playgroud)
cam*_*ous 18
使用该-k
标志按名称运行特定测试,而不指定整个路径:
./manage.py test animals.AnimalTestCase -k my_test_name
Run Code Online (Sandbox Code Playgroud)
要不就
./manage.py test -k my_test_name
Run Code Online (Sandbox Code Playgroud)
(我知道这不是确切的问题,但当我试图弄清楚这一点时,该页面在谷歌搜索中排名很高)
小智 10
我自己遇到了这个问题并发现了这个问题,如果有其他人出现,这就是我挖出来的.DjangoTestSuiteRuner使用一个名为build_test(label)的方法,该方法根据标签确定要运行的测试用例.看看这个方法,事实证明他们在"模型"或"测试"模块上做了一个getattr().这意味着如果您返回套件,测试运行器不会在该套件中查找您的测试用例,它只会查看其中一个模块.
快速解决方法是__init__.py
直接导入测试而不是定义套件.使它们成为"测试"模块的一部分,因此build_test(label)可以找到它们.
对于上面的示例,tests/__init__.py
应该只包含:
from field_tests import *
from storage_tests import *
Run Code Online (Sandbox Code Playgroud)
这不是很优雅,当然如果你试图用你的套件做一些更复杂的事情,那么这将不起作用,但它适用于这种情况.
归档时间: |
|
查看次数: |
69488 次 |
最近记录: |