【问题标题】:How to test Python 2 code using nose2如何使用nose2测试Python 2代码
【发布时间】:2023-03-04 02:13:01
【问题描述】:

我之前问过这个问题 (Force nose2 to use Python 2.7 instead of Python 3.5) 但没有得到答案,我想我可以再试一次。我正在尝试使用命令运行测试

nose2

但我收到一个以

结尾的错误
SyntaxError: Missing parentheses in call to 'print'

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

【问题讨论】:

  • 根据this文档nose2应该支持Python 2.6、2.7、3.2及以上。你确定你使用python2解释器吗? python2和python3之间有很多differences。您提到的语法错误建议您尝试使用 python3 解释器运行 python2 代码。
  • stackoverflow.com/questions/9079036/… 之后,我使用包含print(sys.version_info[0]) 的脚本检查了我的Python 版本,它返回2
  • 顺便说一下,另一个“按原样”工作的测试程序是pytest。它的测试发现方法略有不同(例如,我不得不将测试脚本重命名为以test_ 开头或以_test 结尾),但我发现终端输出比nose2 更加用户友好。

标签: python unit-testing nose2


【解决方案1】:

nose2 采用 shebang 行中配置的任何 python。

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

python2.7 /usr/local/bin/nose2

已通过此示例验证:

test.py

def test_the_program():
    print "foo"

使用 python3

$ 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

$ python2.7 /usr/local/bin/nose2
foo
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2023-03-11
    • 2013-04-24
    • 1970-01-01
    • 2017-09-01
    相关资源
    最近更新 更多