9

I know Python unittest. I have some experience using it for testing Python subprograms.

Now I need to add testing my command line application (not just a Python function) written in Python. I want to call it with certain arguments and certain input in stdin and test output in stdout.

How to integrate testing a command line tool with other unittest test cases?

Or what to use instead of unittest?

2
  • 1
    sounds like a validation or integration tests, could be implemented with any languages, python unittest should be fine with it. Commented Aug 7, 2018 at 23:51
  • > "Or what to use instead of unittest?" see this answer: stackoverflow.com/q/13493288/a#70888702 . Also noticed the use of self.assertEqual, self.assertIn, ... in accepted answer? that's why pytest's doc says under features : "no need to remember self.assert* names" Commented Feb 29, 2024 at 18:06

1 Answer 1

16

You can still use the standard unittest format and test the whole application as a standard function. Make a wrapper that makes the script entry point a simple wrapper, like:

if __name__ == "__main__":
    sys.exit(main(sys.argv))

As long as you don't abuse global variables for keeping the state, you only need to test the main() function.

If you want to test scripts which you don't have control over, you can still use unittest and subprocess by writing a test like:

def test_process(self):
    result = subprocess.run(['your_script', 'your_args', ...], capture_output=True)
    self.assertIn('expected out', result.stdout)

def test_process_failure(self):
    result = subprocess.run(['your_script', 'your_args', ...], capture_output=True)
    self.assertEqual(result.returncode, 1)
Sign up to request clarification or add additional context in comments.

3 Comments

I thought about this. But are there other ways? (I want it to work with all kinds of Python scripts, not only scripts done with the guidelines which you gave in your answer.) Just to make sure.
@porton added an example for testing scripts from outside
ahw right, self.assertEqual, self.assertIn, ... - that's why pytest's doc says under features : "no need to remember self.assert* names"

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.