【发布时间】:2019-07-19 20:45:15
【问题描述】:
如何在运行测试时输出我的__main__ 文件打印?我的意思是从该文件打印,而不是 unittests 文件打印。
我有这个示例结构(所有文件都在同一个目录中):
main.py:
import argparse
print('print me?') # no output
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('name')
args = parser.parse_args()
print(args.name) # no output
other.py:
def print_me():
print('ran print_me')
test.py:
import unittest
import sh
import other
class TestMain(unittest.TestCase):
def test_main(self):
print('test_main') # prints it.
sh.python3('main.py', 'test123')
def test_other(self):
print('test_other') # prints it.
other.print_me()
我使用python3 -m nose -s 或python3 -m unittest 运行它,但这没有区别,打印不是从main.py 输出的,只有直接在测试文件中定义的输出。这是我得到的:
user@user:~/python-programs/test_main$ python3 -m nose -s
test_main
.test_other
ran print_me
.
----------------------------------------------------------------------
Ran 2 tests in 0.040s
OK
附:当然,如果我在不使用测试的情况下运行main.py,那么它会正常打印(例如使用python shell/interpreter 并使用sh 调用main.py,就像在单元测试中一样)
【问题讨论】:
-
这很奇怪。为什么要在该块中定义函数?为什么要通过 shell 调用运行主文件?
-
@DanielRoseman 为什么你觉得奇怪?这是实际 main.py 使用的测试用例(好像它会被正常调用,而不是通过导入和使用参数)。有了功能,是的,它可以避免。但是里面有没有功能,我猜这里不相关。如果它分散了你对实际问题的注意力,我可以删除该功能:)
标签: python python-3.x unit-testing stdout main