[TIP] argv with unitest

Ben Finney ben+python at benfinney.id.au
Tue Aug 18 06:55:38 PDT 2009

Mag Gam <magawake at gmail.com> writes:

> How do I simulate argv with unittest? Is it better to place it in
> setUp() or somewhere else?

This is a classic instance where the practice of unit testing encourages
you to design your code to be more easily tested, and hence think about
how your code will be more easily used from outside, and hence
indirectly encourages good design: narrow, well-defined interfaces.

You should structure your program so that the “mainline code” function
receives the commandline arguments as its (preferably only) explicit
function call parameter, so that it can more easily become a component
in some larger system — such as your unit test suite.

Guido van Rossum made a weblog entry on one good recipe for this
<URL:http://www.artima.com/weblogs/viewpost.jsp?thread=4829>, and I do
something similar with all my Python programs.

 \            “Do not enter the lift backwards, and only when lit up.” |
  `\                                                —elevator, Leipzig |
_o__)                                                                  |
Ben Finney

More information about the testing-in-python mailing list