Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test command line applications in Python?

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?

like image 280
porton Avatar asked Aug 07 '18 23:08

porton


People also ask

How do you test a Python program?

Python has made testing accessible by building in the commands and libraries you need to validate that your applications work as designed. Getting started with testing in Python needn’t be complicated: you can use unittest and write small, maintainable methods to validate your code.

What is automated testing in Python?

Automated testing is the execution of your test plan (the parts of your application you want to test, the order in which you want to test them, and the expected responses) by a script instead of a human. Python already comes with a set of tools and libraries to help you create automated tests for your application.

How do I run a unittest test from the command line?

This is one of many ways to execute the unittest test runner. When you have a single test file named test.py, calling python test.py is a great way to get started. Another way is using the unittest command line. Try this: This will execute the same test module (called test) via the command line.

Is your Python App runnable on the command line?

You’ve just finished building your first Python command-line app. Or maybe your second or third. You’ve been learning Python for a while, and now you’re ready to build something bigger and more complex, but still runnable on a command-line.


1 Answers

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)
like image 69
viraptor Avatar answered Oct 08 '22 17:10

viraptor