testing command line scripts that use optparse

Peter vmail at mycircuit.org
Thu Dec 3 18:18:06 EST 2009


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




More information about the Python-list mailing list