gpt4 book ai didi

python - 带有命令行参数的 Nose 测试脚本

转载 作者:太空狗 更新时间:2023-10-29 17:00:24 25 4
gpt4 key购买 nike

我希望能够运行一个接受命令行参数的 Nose 测试脚本。例如,沿线的东西:

测试.py

import nose, sys

def test():
# do something with the command line arguments
print sys.argv

if __name__ == '__main__':
nose.runmodule()

但是,每当我使用命令行参数运行它时,我都会收到一个错误:

$ python test.py arg
E
======================================================================
ERROR: Failure: ImportError (No module named arg)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 368, in loadTestsFromName
module = resolve_name(addr.module)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/util.py", line 334, in resolve_name
module = __import__('.'.join(parts_copy))
ImportError: No module named arg

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

显然,nose 试图对 sys.argv 中传递的参数做一些事情。有没有办法让 nose 忽略这些参数?

最佳答案

好吧,我讨厌“你为什么要那样做?”答案和任何人一样多,但我将不得不在这里做一个。希望您不要介意。

我认为,做您想做的任何事情都不在框架 Nose 的范围内。 Nose 用于自动化 测试。如果您必须传递命令行参数才能使测试通过,那么它不是自动的。现在,您可以做的是这样的事情:

import sys

class test_something(object):
def setUp(self):
sys.argv[1] = 'arg'
del sys.argv[2] # remember that -s is in sys.argv[2], see below
def test_method(self):
print sys.argv

如果你运行它,你会得到这个输出:

[~] nosetests test_something.py -s
['/usr/local/bin/nosetests', 'arg']
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

(如果您想查看标准输出上发生了什么,请记住传递 -s 标志)

但是,我可能仍然反对这样做,因为如果可以避免的话,在自动化测试中扰乱全局状态通常不是一个好主意。我可能会做的是调整我想要测试的任何代码以获取 argv 列表。然后,您可以在测试期间传入任何您想要的内容,并在生产中传入 sys.argv

更新:

The reason why I need to do it is because I am testing multiple implementations of the same library. To test those implementations are correct I use a single nose script, that accepts as a command line argument the library that it should import for testing.

听起来您可能想尝试编写一个 Nose 插件。这很容易做到。 Here are the latest docs.

关于python - 带有命令行参数的 Nose 测试脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1660520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com