使用Unittest测试Docopt命令行应用?
有没有人能告诉我怎么测试一个用Docopt(Python)写的命令行应用?在GitHub上有人发了这个,
import unittest
from docopt import docopt
import your.entry.point.of.sum as sum
# you can import the doc string from the sum module
doc = sum.__doc__
# suppose now the doc is:
# Sum two numbers.
# Usage: summation.py <x> <y>
# then write your test cases
class TestCLIParser(unittest.TestCase):
def test_sum(self):
args = docopt(doc, ["1", "3"])
self.assertEqual(args["<x>"], "1")
self.assertEqual(args["<y>"], "3")
def and_so_on(self):
...
我得到了这个,但有人能教我怎么测试程序的输出吗?这个例子只是测试了参数。
1 个回答
0
class TestCLI(unittest.TestCase):
def test_sum(self):
cmd = shlex.split("sum 1 3")
output = subprocess.check_output(cmd)
self.assertEqual(output, "4")
虽然你可以使用 unittest
模块来进行这类测试,但这并不算严格的单元测试。比如,一个简单的加法程序,它的输出也很简单,像这样的代码很容易捕捉到结果。但是,随着你的程序变得越来越复杂,保持代码中的预期结果就变得更加困难了。对于这种测试,我推荐使用 ApprovalTests。