[Tutor] Unit testing command-line options from argparse or optparse
Dave Angel
davea at ieee.org
Wed May 19 11:46:31 CEST 2010
Serdar Tumgoren wrote:
> Hello all,
>
> Does anyone have advice for writing unit tests against variables set by
> command-line options?
>
> I have a program I'd like to run in either "debug" or "live" mode, with
> various settings associated with each. Below is some pseudo-code that shows
> what I'd like to do:
>
> <<snipped argparse import and options setup >>
> mode = p.parse_args() #always set to either --debug or --live
>
> if mode.live:
> recipients = ['jsmith at email.com', 'janedoe at email.com']
> # set logging to a file
> elif mode.debug:
> recipients = ['admin at admin.com']
> # log to stdout
>
> The "live" and "debug" attributes are set by command-line flags passed to
> the argparse module. What I'd like to do is write tests that check whether
> various settings (recipients, logging, etc.) are configured properly based
> on the command-line options.
>
> But if "mode" is not set until runtime, I clearly can't import it into my
> suite of unit tests, right? Is there some standard testing approach to this
> problem (perhaps mocking?) that you all can recommend?
>
> I'd greatly appreciate it.
> Serdar
>
>
I don't see the problem. If 'mode' is a global in module doit.py, then
just use
import doit
and later,
if doit.mode.debug
The only tricky thing is to make sure that the initialization code has
been run before you actually use the latter code.
And, presuming mode is an object of a special class made for the
purpose, you could go a bit further. You could create the object (with
default attributes) in the top-level code of doit.py. That way it
already exists when the import is finished. And you could then use
from doit import mode
Now, change the semantics of parse_args() so that it takes the mode
object as a parameter, and modifies it according to the arguments. As
long as you don't reassign mode itself, the test code could continue to
use its own "variable". But once again, don't use the mode.debug until
the initialization has been done.
DaveA
More information about the Tutor
mailing list