如何在Pylons中使用Nose运行单个测试

155
我有一个 Pylons 1.0 应用程序,其中包含一堆位于 test/functional 目录下的测试。 我得到了奇怪的测试结果,我只想运行单个测试。 nose 文档说我应该能够在命令行传递一个测试名称,但无论我做什么都会出现 ImportError。
例如:
nosetests -x -s sometestname

给出:

Traceback (most recent call last):
  File "/home/ben/.virtualenvs/tsq/lib/python2.6/site-packages/nose-0.11.4-py2.6.egg/nose/loader.py", line 371, in loadTestsFromName
   module = resolve_name(addr.module)
  File "/home/ben/.virtualenvs/tsq/lib/python2.6/site-packages/nose-0.11.4-py2.6.egg/nose/util.py", line 334, in resolve_name
   module = __import__('.'.join(parts_copy))
ImportError: No module named sometestname

我遇到同样的错误

nosetests -x -s appname.tests.functional.testcontroller

什么是正确的语法?

6个回答

237

nosetests appname.tests.functional.test_controller 应该可以工作,其中文件名是 test_controller.py

要运行特定的测试类和方法,请使用形式为 module.path:ClassNameInFile.method_name 的路径,即用冒号分隔模块/文件路径和文件内的对象。module.path 是该文件的相对路径(例如 tests/my_tests.py:ClassNameInFile.method_name)。


1
啊,这是我没有尝试过的组合。叹气。谢谢! - Ben
2
这将运行测试控制器/模块中的每个测试。那么如何运行单个测试方法呢?类似于 appname.tests.functional.test_controller.name_of_test_method - ryonlife
69
要运行特定的测试类和方法,请使用形式为模块路径:文件中的类名.方法名的路径,即使用冒号分隔模块/文件路径和文件内的对象。 - James Murty
9
对于其他人可能会感到困惑的问题:module.path是文件的相对路径(例如 my_tests.py:ClassNameInFile.method_name),而不是在import语句中使用的路径。 - bcoughlan
1
@bcoughlan 我把这个加到答案里了!这真的很令人困惑。 - schlamar
显示剩余4条评论

47

对我而言,使用 Nosetests 1.3.0 ,这些变体是有效的(但请确保测试文件夹中有 __init__.py 文件):

nosetests [options] tests.ui_tests
nosetests [options] tests/ui_tests.py
nosetests [options] tests.ui_tests:TestUI.test_admin_page

请注意模块名称和类名之间只有一个冒号。


1
感谢第二个选项,借助Bash自动完成功能,绝对是最方便的一个。 - Peter Kilczuk
值得注意的是,对于调用带参数的测试(使用 @parameterized.expand 的测试),您必须使用以下语法:test_file.py:ClassNameInFile.MethodName_TestNumber,其中 TestNumber 可以是 1、2、3 等,每个参数化测试一个。 - luca

2

我必须添加".py"文件扩展名,也就是说,

r'/path_to/my_file.py:' +  r'test_func_xy'

也许这是因为我在文件中没有任何类。去掉.py后,nose会抱怨:

无法在文件/path_to/my_file中找到可调用的test_func_xy:该文件不是Python模块

尽管我在文件夹/path_to/中有一个__init__.py

0
对于 nosetests 1.3.7 版本,您需要执行以下操作:
nosetests --tests=tests.test_something.py,tests.test_something_else.py。

0
我根据之前的答案编写了这个小脚本:
#!/usr/bin/env bash

# 
# Usage:
# 
#     ./noseTest <filename> <method_name>
# 
# e.g.:
# 
#     ./noseTest test/MainTest.py mergeAll
#     
# It is assumed that the file and the test class have the _same name_ 
# (e.g. the test class `MainTest` is defined in the file `MainTest.py`).
# If you don't follow this convention, this script won't work for you.
#

testFile="$1"
testMethod="$2"

testClass="$(basename "$testFile" .py)"

nosetests "$testFile:$testClass.test_$testMethod"

0

以下方法对我非常有效:

nosetests test_file.py:method_name

请注意,我的测试不在类中。测试方法都在一个文件中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接