Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 128615
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T05:39:49+00:00 2026-05-11T05:39:49+00:00

I’m trying to unit test some code that looks like this: def main(): parser

  • 0

I’m trying to unit test some code that looks like this:

def main():     parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')     parser.add_option('--foo', action='store', help='The foo option is self-explanatory')     options, arguments = parser.parse_args()     if not options.foo:         parser.error('--foo option is required')     print 'Your foo is %s.' % options.foo     return 0  if __name__ == '__main__':    sys.exit(main()) 

With code that looks like this:

@patch('optparse.OptionParser') def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):     #     # setup     #     optionparser_mock = Mock()     mock_optionparser.return_value = optionparser_mock     options_stub = Mock()     options_stub.foo = None     optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)     def parser_error_mock(message):         self.assertEquals(message, '--foo option is required')         sys.exit(2)     optionparser_mock.error = parser_error_mock      #     # exercise & verify     #     self.assertEquals(sut.main(), 2) 

I’m using Michael Foord’s Mock, and nose to run the tests.

When I run the test, I get:

  File '/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py', line 27, in parser_error_mock     sys.exit(2) SystemExit: 2  ---------------------------------------------------------------------- Ran 1 test in 0.012s  FAILED (errors=1) 

The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.

I can make the test pass by adding ‘return 2’ under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?

Update: df‘s answer works, although the correct call is ‘self.assertRaises(SystemExit, sut.main)’.

Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?

BTW, the test is more robust if I add:

self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})]) 

at the end.

Update 2: I can test for the exit code by replacing ‘self.assertRaises(SystemExit, sut.main)’ with:

try:     sut.main() except SystemExit, e:     self.assertEquals(type(e), type(SystemExit()))     self.assertEquals(e.code, 2) except Exception, e:     self.fail('unexpected exception: %s' % e) else:     self.fail('SystemExit exception expected') 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T05:39:50+00:00Added an answer on May 11, 2026 at 5:39 am

    As noted in my updates to my question, I had to modify dF‘s answer to:

    self.assertRaises(SystemExit, sut.main) 

    …and I came up with a few longer snippet to test for the exit code.

    [Note: I accepted my own answer, but I will delete this answer and accept dF‘s if he updates his.]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 200k
  • Answers 200k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Is this acceptable? Yes it is. It seems like it… May 12, 2026 at 7:56 pm
  • Editorial Team
    Editorial Team added an answer Have you tried trying to isolate the area where the… May 12, 2026 at 7:56 pm
  • Editorial Team
    Editorial Team added an answer You can select the type of your setting entry as… May 12, 2026 at 7:56 pm

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
In order to apply a triggered animation to all ToolTip s in my app,
I have a French site that I want to parse, but am running into
I have text I am displaying in SIlverlight that is coming from a CMS

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.