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

1

1 Answer 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")

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.