Skip to content

unittest may incorrectly return exit code 5 when setUpClass raises an exception #136442

Closed

Description

@ueshin

Bug report

Bug description:

In Python 3.12+, unittest returns exit code 5 when no tests are run and none are skipped. However, if a test class’s setUpClass() method raises any exception (except unittest.SkipTest; related to #106584), no tests are executed, and unittest may incorrectly return exit code 5.

This is misleading: the failure occurred due to an error in class-level setup, not because all tests were skipped.

import unittest

class BugTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        raise ValueError("Simulated setup failure")

    def test_example(self):
        self.assertTrue(True)
python -m unittest bug_test.py
echo $?

Actual result:

  • Exit code is 5.

Expected result:

  • Exit code should be 1, because an error occurred during test setup.

I think we should report the error first, then check whether no tests are run and none are skipped or not.

https://github.com/python/cpython/blob/3.12/Lib/unittest/main.py#L282-L288

Suggested:

        if self.exit:
            if not self.result.wasSuccessful():
                sys.exit(1)
            elif self.result.testsRun == 0 and len(self.result.skipped) == 0:
                sys.exit(_NO_TESTS_EXITCODE)
            else:
                sys.exit(0)

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Jul 9, 2025
  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Jul 9, 2025
  3. ZeroIntensity commented on Jul 9, 2025

    @ZeroIntensity
    Member

    Sounds like a reasonable fix. Would you like to submit a PR?

  4. ueshin commented on Jul 9, 2025

    @ueshin
    ContributorAuthor

    @ZeroIntensity Sure, I will submit a PR. Thanks!

  5. added
    3.13only security fixes
    3.14bugs and security fixes
    3.15bugs and security fixes
    on Jul 9, 2025
  6. added a commit that references this issue on Jul 10, 2025
  7. added a commit that references this issue on Nov 15, 2025
  8. added 2 commits that reference this issue on Nov 15, 2025
  9. added 2 commits that reference this issue on Nov 15, 2025
  10. added a commit that references this issue on Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13only security fixes3.14bugs and security fixes3.15bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions