Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > testing command line scripts that use optparse

Thread Tools

testing command line scripts that use optparse

Posts: n/a
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/", line 1578, in error
self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
File "/usr/local/python2.6/lib/python2.6/", line 1568, in exit
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.


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
problem in running a basic code in python 3.3.0 that includes HTML file Satabdi Mukherjee Python 1 04-04-2013 07:48 PM
How to use optparse without the command line? markolopa Python 2 04-13-2011 01:18 PM
Running python scripts from the command line. Nanderson Python 2 02-01-2011 03:08 AM
How to send command line options into test scripts? yusuf Perl Misc 22 08-11-2006 06:57 PM
use one line Perl command to add a line at the begin of a file Ting Wang Perl Misc 3 12-13-2005 06:07 PM