测试 Python 脚本 [英] Testing Python Scripts

查看:22
本文介绍了测试 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 doctest、unittest、nose 等测试框架测试 Python 脚本的 STDOUT 输出?例如,运行我的脚本todo.py --list"应该返回取出垃圾".

How do I test the STDOUT output of a Python script with a testing framework like doctest, unittest, nose, etc? For example, say running my script "todo.py --list" should return "take out the garbage".

我读过有人将脚本的 STDOUT 打印部分与生成要打印的输出的部分分开.我习惯于在我的 shell 脚本周围散布打印语句.这仅仅是我应该打破的 TDD 不友好习惯还是有一种方法可以轻松测试正确的打印输出?

I've read someone who separates out the STDOUT printing part of the script from the part that generates the output to be printed. I'm used to sprinkling print statements all around my shell scripts. Is this simply a TDD unfriendly habit I should break or is there a way to easily test for correct print output?

推荐答案

我看到两种方式:

  1. 在单元测试期间重定向标准输出:

  1. Redirect stdout during the unittest:

class YourTest(TestCase):
    def setUp(self):
        self.output = StringIO()
        self.saved_stdout = sys.stdout
        sys.stdout = self.output

    def tearDown(self):
        self.output.close()
        sys.stdout = self.saved_stdout

    def testYourScript(self):
        yourscriptmodule.main()
        assert self.output.getvalue() == "My expected ouput"

  • 使用记录器记录输出并在测试中收听.

  • Use a logger for your outputs and listen to it in your test.

    这篇关于测试 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆