【问题标题】:Python3 - output __main__ file prints when running unittests (from actual program, not unittests)Python3 - 运行单元测试时输出 __main__ 文件(来自实际程序,而不是单元测试)
【发布时间】:2019-07-19 20:45:15
【问题描述】:

如何在运行测试时输出我的__main__ 文件打印?我的意思是从该文件打印,而不是 unittests 文件打印。

我有这个示例结构(所有文件都在同一个目录中):

ma​​in.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 -spython3 -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


【解决方案1】:

sh.python3 启动新进程,其输出未被nose 捕获。您可以重定向输出打印结果:

print(sh.python3('main.py', 'test123'))

【讨论】:

  • 我实际上尝试过这个,但在我看来,它似乎只捕获了__main__ 块内的打印。仔细观察,它确实捕获了所有内容。这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2014-06-03
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
相关资源
最近更新 更多