Unittest causing sys.exit()

No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.

IDLE 1.2.2      ==== No Subprocess ====
>>> import unittest
>>> class Test(unittest.TestCase):
        def testA(self):
            a = 1

>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]

  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output

   idle.pyw                               - run default set of tests
   idle.pyw MyTestSuite                   - run suite 'MyTestSuite'
   idle.pyw MyTestCase.testSomething      - run MyTestCase.testSomething
   idle.pyw MyTestCase                    - run all 'test*' test methods
                                           in MyTestCase

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
  File "E:\Python25\lib\unittest.py", line 767, in __init__
  File "E:\Python25\lib\unittest.py", line 796, in parseArgs
  File "E:\Python25\lib\unittest.py", line 773, in usageExit
SystemExit: 2

Asked by: John859 | Posted: 05-10-2021

Answer 1

In new Python 2.7 release, unittest.main() has a new argument.

If 'exit' is set to False, sys.exit() is not called during the execution of unittest.main().

Answered by: Michelle116 | Posted: 06-11-2021

Answer 2

Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing




More information is available here in the Python Library Reference.

Answered by: Kelsey871 | Posted: 06-11-2021

Answer 3

Don't try to run unittest.main() from IDLE. It's trying to access sys.argv, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call unittest.main() in its own Python process.

Answered by: Marcus170 | Posted: 06-11-2021

Answer 4

Pop open the source code to unittest.py. unittest.main() is hard-coded to call sys.exit() after running all tests. Use TextTestRunner to run test suites from the prompt.

Answered by: Connie257 | Posted: 06-11-2021

Answer 5

It's nice to be able to demonstrate that your tests work when first trying out the unittest module, and to know that you won't exit your Python shell. However, these solutions are version dependent.

Python 2.6

I'm using Python 2.6 at work, importing unittest2 as unittest (which is the unittest module supposedly found in Python 2.7).

The unittest.main(exit=False) doesn't work in Python 2.6's unittest2, while JoeSkora's solution does, and to reiterate it:


To break this down into its components and default arguments, with correct semantic names for the various composed objects:

import sys # sys.stderr is used in below default args

test_loader = unittest.TestLoader()
loaded_test_suite = test_loader.loadTestsFromTestCase(Test)
                                           # Default args:
text_test_runner = unittest.TextTestRunner(stream=sys.stderr,

Python 2.7 and 3

In Python 2.7 and higher, the following should work.


Answered by: First Name282 | Posted: 06-11-2021

Answer 6

except SystemExit:
    print('Simple as that, but you should really use a TestRunner instead')

Answered by: Paul590 | Posted: 06-11-2021

Similar questions

python - Handle sys.exit() in cherrypy service

When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a sys.exit() call (from my error handler), cherrypy quits, but the service remains hanging. Code: import cherrypy import win32serviceutil import win32service import sys SERVICE = None class HelloWorld: """ Sample request handler class. """ def __init__(self): self.iVal = ...

linux - How to bypass the 0-255 range limit for sys.exit() in python?

In python (on a Linux system), I'm launching a command using os.system() and retrieving the return code. If that return code is different from 0, I would like to make the program exit with that same return code. So I wrote: ret = os.system(cmd) if ret != 0: print "exit with status %s" % ret sys.exit(ret) When the return code is lower than 256, it works fine, but when it'...

Python sys.exit() help?

I am working in Python and am trying to have a line of code execute and after it executes I am calling sys.exit() to have the script itself "exit." However, it seems that sys.exit() is executing before the line of code above it executes. Below is the code I am trying to implement: if something == True: self.redirect('http://www.google.com/') sys.exit() The...

mocking - How to get around "sys.exit()" in python nosetest?

It seems that python nosetest will quit when encountered sys.exit(), and mocking of this builtin doesn't work.

import - python: Importing scipy.io seems to prevent sys.exit() to work properly

Under Windows, executing the following Python script I get an ERRORLEVEL of 0 instead of the expected 2. import sys import scipy.io sys.exit(2) If I remove the import scipy.io, I got the correct ERRORLEVEL of 2... Any idea why importing scipy.io cause such an issue? PS: windows 7, python 2.72, scipy 0.10.1 Calling help(sys.exit) just before the sys.exit call return...

python - Issue with sys.exit() in pygame

I am learning to use Pygame, and when I use sys.exit(), I run into a problem. Here is the code: import pygame, sys,os from pygame.locals import * pygame.init() window = pygame.display.set_mode((468, 60)) pygame.display.set_caption('Game') screen = pygame.display.get_surface() file_name = os.path.join("data","image.bmp") surface = pygame.image.load(file_name) screen.blit(surface, (0,0)...

python - Why are the methods sys.exit(), exit(), raise SystemExit not working?

I need an alternative to kill the python script while inside a thread function. My intention is killing the server when the client enters a 0... Is this not working because the threads haven't been terminated? Here is my code: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); print 'Socket created' try: socket.bind((HOST, PORT)) except socket.error, message: print 'Bind statement failed. ...

How to use sys.exit() in Python

player_input = '' # This has to be initialized for the loop while player_input != 0: player_input = str(input('Roll or quit (r or q)')) if player_input == q: # This will break the loop if the player decides to quit print("Now let's see if I can beat your score of", player) break if player_input != r: print('invalid choice, try again') if player_input ==r: roll...

python - Is it possible for a unit test to assert that a method calls sys.exit()?

I have a Python 2.7 method that sometimes calls sys.exit(1) Is it possible to make a unit test that verifies this line of code is called when the right conditions are met?

python - how to continue execution after sys.exit() command

Here i'm reading and comparing values from the two logs using 'for' loop.Problem is i'm not able to continue to next TC after sys.exit command. Let me know if required more clarification f = open('/tmp/ftplog', 'r') for line in f: m = re.findall("5\d+", line) #print m fd = open('/tmp/tellog', 'r') for line in fd: n = re.findall(r"5\d+", line) #prin...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python