关于单元测试:如何使用nose2测试Python 2代码

How to test Python 2 code using nose2

我之前已经问过这个问题(强制使用Python 2.7而不是Python 3.5)但是没有得到答案,并且我想我可能会再试一次。 我正在尝试使用该命令运行测试

1
nose2

但是我收到的错误结束了

1
SyntaxError: Missing parentheses in call to 'print'

似乎nose2假设代码在Python 3中,而在这种情况下它是在Python 2中。有没有办法让nose2在Python 2代码上工作? (例如,通过更改其配置)?


nose2接受shebang行中配置的任何python。

要测试python2项目使用(您的计算机上的可执行文件和路径可能不同):

1
python2.7 /usr/local/bin/nose2

通过此示例验证:

test.py:

1
2
def test_the_program():
    print"foo"

使用python3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ python3 /usr/local/bin/nose2
======================================================================
ERROR: test (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: test
    (...)
    print"hans"
               ^
SyntaxError: Missing parentheses in call to 'print'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

用python2.7:

1
2
3
4
5
6
7
$ python2.7 /usr/local/bin/nose2
foo
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK