Skip to content

gh-127221: Add colour to unittest output - #127223

Merged
hugovk merged 7 commits into
python:mainfrom
hugovk:3.14-unittest-colour
Dec 5, 2024
Merged

hugovk merged 7 commits into
python:mainfrom
hugovk:3.14-unittest-colour

Conversation

@hugovk

@hugovk hugovk commented Nov 24, 2024 •

Copy link
Copy Markdown
Member

Use the existing _colorize module already used for tracebacks and doctest so output can be controlled with the PYTHON_COLORS, NO_COLOR and FORCE_COLOR environment variables.

This PR does a couple of things to add colour:

  • Enable colour for tracebacks by passing in colorize to msgLines = list(tb_e.format(colorize=can_colorize()))
  • Add colour for pass/fail/errors, using pytest as a guide
  • Plus some unrelated tidy-up (use more specific test methods, new-style objects, underscore variables)

Tested with some small demo scripts:

No tests ran

run-unittests-none.py
import unittest

if __name__ == "__main__":
    unittest.main()
Before After pytest
image image image

Passed

run-unittests-pass.py
Mode Before After pytest
Regular image image image
Verbose image image image

Failing

run-unittests.py
import unittest


class TestThings(unittest.TestCase):
    def test_pass(self):
        self.assertTrue(True)

    def test_fail(self):
        self.assertTrue(False)

    def test_error(self):
        raise Exception("Manually raised exception")

    def test_pass2(self):
        self.assertEqual(1, 1)

    @unittest.skip("demonstrating skipping")
    def test_skip(self):
        self.fail("shouldn't happen")


class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

    @unittest.expectedFailure
    def test_pass(self):
        self.assertEqual(1, 1, "not broken")


if __name__ == "__main__":
    unittest.main()
Mode Before After pytest
Regular image image image
Verbose image image image

Subtests

run-unittests-subtests.py
import unittest


class DoSubTest(unittest.TestCase):
    def test_subtest(self):
        """Test with subtest"""
        for i in range(0, 4):
            with self.subTest(i=i):
                if i == 2:
                    raise Exception("Manually raised exception")
                self.assertEqual(i % 2, 0)


if __name__ == "__main__":
    unittest.main()
Mode Before After pytest
Regular image image image
Verbose image image image

📚 Documentation preview 📚: https://cpython-previews--127223.org.readthedocs.build/

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stdlib Standard Library Python modules in the Lib/ directory type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants