3

can anyone show me how can I test a cli app written in Docopt (Python)? Someone on GitHub posted this,

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):
        ...

I have got this but can someone show me how can I test the output of the program? This example only tests the arguments

Delete Me
  • 111
  • 1
  • 4
  • 12
  • so you want to capture stdout like in this question http://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python ? – J. P. Petersen Jun 25 '14 at 07:08

1 Answers1

0
class TestCLI(unittest.TestCase):
    def test_sum(self):
        cmd = shlex.split("sum 1 3")
        output = subprocess.check_output(cmd)
        self.assertEqual(output, "4")

Although you can use the unittest module to drive this kind of testing, it's not strictly unit testing. A simple sum program has simple output, which is easy to capture in code like this. But, as your program evolves to something more complex, it becomes more difficult to maintain the expectations in source code. For this kind of testing, I'd recommend ApprovalTests.

ian.buchanan
  • 314
  • 1
  • 10