子类化 python unittest.Testcase,调用相同的 main
我想创建一个名为BasicTest 的python 的unittest.Testcase 子类。我希望 BasicTest 的每个子类在 main 中运行相同的例程。我怎样才能做到这一点?
例子:
in basic_test.py:
class BasicTest(unittest.TestCase):
...
if __name__ == '__main__':
# Do optparse stuff
unittest.main()
in some_basic_test.py:
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
#call the main in basic_test.py
I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this?
Example:
in basic_test.py:
class BasicTest(unittest.TestCase):
...
if __name__ == '__main__':
# Do optparse stuff
unittest.main()
in some_basic_test.py:
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
#call the main in basic_test.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法(重新)导入模块作为新的 main,因此
if __name__=="__main__"
代码是无法访问的。多尔的建议或类似的建议似乎是最合理的。
但是,如果您无法访问相关模块,您可以考虑查看 runpy .run_module() 将模块作为 main 执行。
You cannot (re)import a module as a new main, thus the
if __name__=="__main__"
code is kind of unreachable.Dor’s suggestion or something similar seems most reasonable.
However if you have no access to the module in question, you might consider looking at the runpy.run_module() that executes a module as main.
我想您想要的是在从任何测试用例运行测试之前运行一些设置/初始化代码。在这种情况下,您可能对
setUpClass
类方法。testA.py
testB.py
testA.py 的输出:
testB.py 的输出:
I guess what you want is to run some setup/initialization code before running tests from any test case. In this case you might be interested in
setUpClass
class method.testA.py
testB.py
Output from testA.py:
Output from testB.py: