testing command line scripts that use optparse

P

Peter

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top