riser101
riser101

Reputation: 650

How to test Python command line apps

I've built a python command line application, which operates in two modes:

  1. in an interactive mode, where it opens up an interactive shell using python CMDModule.

    Example:

    running plcli in command line, opens up its interactive mode

    (cmd)> do_x

  2. reads commands from an input file and executes them one-by-one.

    Example:

    running plcli input_file.txt in command line, it executes commands line-by-line and outputs result to stdout.

How do I write unit and integration test for this cli app. I've explored pytest-console-scripts and script-test but they doesn't seem to be optimum or best practice.

Please suggest accepted/best practise libraries or usage to test python command line applications.

Note : I'm not using any python cli frameworks like clint or click

Upvotes: 0

Views: 1697

Answers (1)

FMc
FMc

Reputation: 42411

The most important principle is to organize your code so that the complexity resides in functions (or methods) that are amenable to straightforward unit testing -- in other words, in functions that don't deal with the command-line or interactive nature of the larger program. Then glue those functions to a thin outer layer that provides the command-line or interactive functionality. That glue will tend to be very simple and might not be worth the trouble of testing. If it does need any testing, you can often do it with a small number of basic end-to-end executions (e.g. for the command-line scenario a test that uses Python's subprocess module to run your program exactly the way a user would).

More details can be found in Gary Bernhardt's excellent Boundaries talk.

Upvotes: 1

Related Questions