Unittest2
Unittest2 is a backport of the enhanced features from Python 2.7's `unittest` module to earlier Python versions (primarily Python 2.4-2.6, but later extending to 2.x and early 3.x versions). It provided modern `unittest` capabilities like improved assertion methods, test discovery, class/module-level fixtures, and `assertRaises` as a context manager for users on older Python environments. The project's last release was in 2015, making it largely obsolete for modern Python development.
Warnings
- breaking Unittest2 is primarily a backport for Python 2.x and early Python 3.x versions. For Python 3.2+ users, all features provided by unittest2 are integrated directly into the standard library's `unittest` module, rendering unittest2 largely unnecessary and potentially conflicting.
- gotcha Command-line test discovery (`python -m unittest`) is a Python 2.7+ feature. For Python versions older than 2.7, unittest2 provides a `unit2` script (or `unit2.py` on Windows) for command-line test execution and discovery. Direct `python -m unittest2` will not work.
- gotcha The default value of `TestCase.longMessage` in unittest2 is `True`, which differs from `unittest` in Python 2.7 (where it defaults to `False` for backward compatibility). This can affect the verbosity of failure messages.
- deprecated There was a separate `unittest2py3k` distribution for Python 3 on PyPI, which used the package name `unittest2`. This specific distribution is obsolete. If you are developing for Python 3, you should use the standard library's `unittest` module.
Install
-
pip install unittest2
Imports
- TestCase
from unittest2 import TestCase
- main
import unittest2; unittest2.main()
Quickstart
import unittest2 as unittest
class MyTests(unittest.TestCase):
def setUp(self):
# Setup resources before each test method
self.data = [1, 2, 3]
def test_addition(self):
self.assertEqual(sum(self.data), 6)
def test_empty_list(self):
with self.assertRaises(TypeError):
sum(None)
def tearDown(self):
# Clean up resources after each test method
del self.data
if __name__ == '__main__':
unittest.main()