testing command line scripts that use optparse

Discussion in 'Python' started by Peter, Dec 3, 2009.

  1. Peter

    Peter Guest

    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
    Peter, Dec 3, 2009
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. markolopa
    Replies:
    2
    Views:
    229
    markolopa
    Apr 13, 2011
  2. Ganesh Pal
    Replies:
    0
    Views:
    100
    Ganesh Pal
    Feb 25, 2014
  3. Peter Otten
    Replies:
    0
    Views:
    64
    Peter Otten
    Feb 25, 2014
  4. Mark Lawrence
    Replies:
    0
    Views:
    61
    Mark Lawrence
    Feb 25, 2014
  5. Ganesh Pal
    Replies:
    1
    Views:
    74
Loading...

Share This Page