testing command line scripts that use optparse

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Dec 4 10:31:31 EST 2009


Peter wrote:
> Hi
> I have a script like this:
>
> def doit(input, output):
>  parser = OptionParser()
>  parser.add_option("-a", "--accounts", dest="accounts", default="all",
>                    help="list available accounts")
> ...
>
>  (options, args) = parser.parse_args()
>
>
> # main driver
> if __name__ == "__main__":
>  import sys
>  doit(sys.stdin, sys.stdout)
>
> that I would like to test like this:
>
>    def test_accounts(self):
>      input = """-aRoot"""         output = """Results"""
>      self.runtest(input, output)
>        def runtest(self, input, expected):
>      inputStream = cStringIO.StringIO(input)
>      actual = cStringIO.StringIO()
>      doit(inputStream, actual)
>      assert_equal(actual.getvalue(), expected)
>
> But when running test_accounts, I get:
> ...
> File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1578, in 
> error
>    self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
>  File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1568, in 
> exit
>    sys.exit(status)
> SystemExit: 2
> -------------------- >> begin captured stdout << ---------------------
> stdin <cStringIO.StringI object at 0x8bd5b30>
>
> optparse expects a file object and gets a cStringIO.
>
> What is the correct way to set up this ?
> Thanks for your help.
>
> Peter
>
It seems there is something wrong with the type of the paramaters given 
to the doit function. We can't say more cause cause you remove the 
related code of the doit function.

But the error seems pretty clear to me : "optparse expects a file object 
and gets a cStringIO"

JM



More information about the Python-list mailing list