![](/img/trans.png)
[英]Running a single test from unittest.TestCase via the command line
[英]Python, unit test - Pass command line arguments to setUp of unittest.TestCase
我有一个脚本,它充当使用 Python unittest
模块编写的某些单元测试的包装器。 除了清理一些文件、创建输出流和生成一些代码之外,它还使用以下命令将测试用例加载到套件中
unittest.TestLoader().loadTestsFromTestCase()
我已经在使用optparse
来提取几个用于确定输出位置、是否重新生成代码以及是否进行一些清理的命令行参数。 我还想传递一个配置变量,即端点 URI,以在测试用例中使用。
我意识到我可以将OptionParser
添加到 TestCase 的 setUp 方法中,但我想改为将选项传递给setUp
。 这可以使用loadTestsFromTestCase()
吗? 我可以遍历返回的TestSuite
的TestCases
,但是我可以手动调用TestCases
上的 setUp 吗?
**编辑**我想指出的是,我能够将参数传递给setUp
如果我遍历测试和呼叫setUp
手动像:
(options, args) = op.parse_args()
suite = unittest.TestLoader().loadTestsFromTestCase(MyTests.TestSOAPFunctions)
for test in suite:
test.setUp(options.soap_uri)
但是,我为此使用了xmlrunner
,它的 run 方法将TestSuite
作为参数。 我假设它将运行 setUp 方法本身,所以我需要XMLTestRunner
可用的参数。
好吧,我想做同样的事情,并且要自己问这个问题。 我想改进以下代码,因为它有重复。 但是,它确实让我发送参数来测试 TestCase:
import unittest
import helpspot
class TestHelpSpot(unittest.TestCase):
"A few simple tests for HelpSpot"
def __init__(self, testname, path, user, pword):
super(TestHelpSpot, self).__init__(testname)
self.hs = helpspot.HelpSpot(path, user, pword)
def test_version(self):
a = self.hs.version()
b = self.hs.private_version()
self.assertEqual(a, b)
def test_get_with_param(self):
a = self.hs.filter_get(xFilter=1)
def test_unknown_method(self):
self.assertRaises(helpspot.HelpSpotError, self.hs.private_wuggienorple)
if __name__ == '__main__':
import sys
user = sys.argv[1]
pword = sys.argv[2]
path = sys.argv[3]
test_loader = unittest.TestLoader()
test_names = test_loader.getTestCaseNames(TestHelpSpot)
suite = unittest.TestSuite()
for test_name in test_names:
suite.addTest(TestHelpSpot(test_name, path, user, pword))
result = unittest.TextTestRunner().run(suite)
sys.exit(not result.wasSuccessful())
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-z", "--zebra",
action="store_true", dest="zebra", default=False,
help="run like a zebra")
(options, args) = parser.parse_args()
if options.zebra:
zebrafy()
# remove our args because we don't want to send them to unittest
for x in sum([h._long_opts+h._short_opts for h in parser.option_list],[]):
if x in sys.argv:
sys.argv.remove(x)
unittest.main()
我绝对会建议不要像这样将参数传递给 setUp; setUp 旨在在运行测试时隐式调用,因此您不应像这样显式调用它。
解决此问题的一种方法是将需要设置的值设置为环境变量或全局可访问“上下文”模块中的值,这将允许测试用例根据需要访问它们。 我会去使用环境变量,因为它在运行测试方面更灵活(然后你不再依赖命令行参数)。
如果您在 init 方法中定义属性,那么您可以像这样简单地将它们全部传递到构造函数中。
import unittest
import helpspot
class TestHelpSpot(unittest.TestCase):
"A few simple tests for HelpSpot"
def __init__(self, testname, path, user, pword):
super(TestHelpSpot, self).__init__(testname)
self.path = path
self.user = user
self.pword = pword
....
....
....
if __name__ == '__main__':
True
suite = unittest.TestSuite()
suite.addTest(TestHelpSpot("test_version", path, user, pword))
unittest.TextTestRunner().run(suite)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.