Skip to content

Commit 4062f07

Browse files
bpo-45162: Remove many old deprecated unittest features
* "fail*" and "assert*" aliases of TestCase methods. * Broken from start TestCase method assertDictContainsSubset(). * Ignored TestLoader.loadTestsFromModule() parameter use_load_tests. * Old alias _TextTestResult of TextTestResult.
1 parent 62fa613 commit 4062f07

File tree

13 files changed

+60
-371
lines changed

13 files changed

+60
-371
lines changed

Doc/library/unittest.rst

Lines changed: 7 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,9 +1237,6 @@ Test cases
12371237
:meth:`.assertRegex`.
12381238
.. versionadded:: 3.2
12391239
:meth:`.assertNotRegex`.
1240-
.. versionadded:: 3.5
1241-
The name ``assertNotRegexpMatches`` is a deprecated alias
1242-
for :meth:`.assertNotRegex`.
12431240

12441241

12451242
.. method:: assertCountEqual(first, second, msg=None)
@@ -1605,40 +1602,6 @@ Test cases
16051602
:mod:`unittest`-based test framework.
16061603

16071604

1608-
.. _deprecated-aliases:
1609-
1610-
Deprecated aliases
1611-
##################
1612-
1613-
For historical reasons, some of the :class:`TestCase` methods had one or more
1614-
aliases that are now deprecated. The following table lists the correct names
1615-
along with their deprecated aliases:
1616-
1617-
============================== ====================== =======================
1618-
Method Name Deprecated alias Deprecated alias
1619-
============================== ====================== =======================
1620-
:meth:`.assertEqual` failUnlessEqual assertEquals
1621-
:meth:`.assertNotEqual` failIfEqual assertNotEquals
1622-
:meth:`.assertTrue` failUnless assert\_
1623-
:meth:`.assertFalse` failIf
1624-
:meth:`.assertRaises` failUnlessRaises
1625-
:meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1626-
:meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
1627-
:meth:`.assertRegex` assertRegexpMatches
1628-
:meth:`.assertNotRegex` assertNotRegexpMatches
1629-
:meth:`.assertRaisesRegex` assertRaisesRegexp
1630-
============================== ====================== =======================
1631-
1632-
.. deprecated:: 3.1
1633-
The fail* aliases listed in the second column have been deprecated.
1634-
.. deprecated:: 3.2
1635-
The assert* aliases listed in the third column have been deprecated.
1636-
.. deprecated:: 3.2
1637-
``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1638-
:meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1639-
.. deprecated:: 3.5
1640-
The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`.
1641-
16421605
.. _testsuite-objects:
16431606

16441607
Grouping tests
@@ -1764,7 +1727,7 @@ Loading and running tests
17641727
case is created for that method instead.
17651728

17661729

1767-
.. method:: loadTestsFromModule(module, pattern=None)
1730+
.. method:: loadTestsFromModule(module, *, pattern=None)
17681731

17691732
Return a suite of all test cases contained in the given module. This
17701733
method searches *module* for classes derived from :class:`TestCase` and
@@ -1788,10 +1751,11 @@ Loading and running tests
17881751
Support for ``load_tests`` added.
17891752

17901753
.. versionchanged:: 3.5
1791-
The undocumented and unofficial *use_load_tests* default argument is
1792-
deprecated and ignored, although it is still accepted for backward
1793-
compatibility. The method also now accepts a keyword-only argument
1794-
*pattern* which is passed to ``load_tests`` as the third argument.
1754+
Support for a keyword-only argument *pattern* has been added.
1755+
1756+
.. versionchanged:: 3.11
1757+
The undocumented and unofficial *use_load_tests* parameter has been
1758+
removed.
17951759

17961760

17971761
.. method:: loadTestsFromName(name, module=None)
@@ -2144,8 +2108,6 @@ Loading and running tests
21442108
:class:`TextTestRunner`.
21452109

21462110
.. versionadded:: 3.2
2147-
This class was previously named ``_TextTestResult``. The old name still
2148-
exists as an alias but is deprecated.
21492111

21502112

21512113
.. data:: defaultTestLoader
@@ -2168,10 +2130,7 @@ Loading and running tests
21682130
By default this runner shows :exc:`DeprecationWarning`,
21692131
:exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
21702132
:exc:`ImportWarning` even if they are :ref:`ignored by default
2171-
<warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
2172-
methods <deprecated-aliases>` are also special-cased and, when the warning
2173-
filters are ``'default'`` or ``'always'``, they will appear only once
2174-
per-module, in order to avoid too many warning messages. This behavior can
2133+
<warning-ignored>`. This behavior can
21752134
be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
21762135
(see :ref:`Warning control <using-on-warnings>`) and leaving
21772136
*warnings* to ``None``.

Doc/whatsnew/3.11.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,28 @@ Removed
265265
and :class:`fileinput.FileInput`, deprecated since Python 3.9.
266266
(Contributed by Hugo van Kemenade in :issue:`45132`.)
267267

268+
* Removed many old deprecated :mod:`unittest` features:
269+
270+
- :class:`~unittest.TestCase` method aliases ``failUnlessEqual``,
271+
``failIfEqual``, ``failUnless``, ``failIf``, ``failUnlessRaises``,
272+
``failUnlessAlmostEqual``, ``failIfAlmostEqual`` (deprecated in Python 3.1),
273+
``assertEquals``, ``assertNotEquals``, ``assert_``, ``assertAlmostEquals``,
274+
``assertNotAlmostEquals``, ``assertRegexpMatches``, ``assertRaisesRegexp``
275+
(deprecated in Python 3.2), and ``assertNotRegexpMatches`` (deprecated in
276+
Python 3.5).
277+
278+
- Undocumented and broken :class:`~unittest.TestCase` method
279+
``assertDictContainsSubset`` (deprecated in Python 3.2).
280+
281+
- Undocumented :meth:`<unittest.TestLoader.loadTestsFromModule>
282+
TestLoader.loadTestsFromModule` parameter *use_load_tests* (deprecated
283+
and ignored since Python 3.2).
284+
285+
- An alias of the :class:`~unittest.TextTestResult` class:
286+
``_TextTestResult`` (deprecated in Python 3.2).
287+
288+
(Contributed by Serhiy Storchaka in :issue:`45162`.)
289+
268290

269291
Optimizations
270292
=============

Lib/unittest/__init__.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,6 @@ def testMultiply(self):
6767
from .signals import installHandler, registerResult, removeResult, removeHandler
6868
# IsolatedAsyncioTestCase will be imported lazily.
6969

70-
# deprecated
71-
_TextTestResult = TextTestResult
72-
7370
# There are no tests here, so don't try to run anything discovered from
7471
# introspecting the symbols (e.g. FunctionTestCase). Instead, all our
7572
# tests come from within unittest.test.

Lib/unittest/case.py

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,35 +1137,6 @@ def assertDictEqual(self, d1, d2, msg=None):
11371137
standardMsg = self._truncateMessage(standardMsg, diff)
11381138
self.fail(self._formatMessage(msg, standardMsg))
11391139

1140-
def assertDictContainsSubset(self, subset, dictionary, msg=None):
1141-
"""Checks whether dictionary is a superset of subset."""
1142-
warnings.warn('assertDictContainsSubset is deprecated',
1143-
DeprecationWarning)
1144-
missing = []
1145-
mismatched = []
1146-
for key, value in subset.items():
1147-
if key not in dictionary:
1148-
missing.append(key)
1149-
elif value != dictionary[key]:
1150-
mismatched.append('%s, expected: %s, actual: %s' %
1151-
(safe_repr(key), safe_repr(value),
1152-
safe_repr(dictionary[key])))
1153-
1154-
if not (missing or mismatched):
1155-
return
1156-
1157-
standardMsg = ''
1158-
if missing:
1159-
standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
1160-
missing)
1161-
if mismatched:
1162-
if standardMsg:
1163-
standardMsg += '; '
1164-
standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
1165-
1166-
self.fail(self._formatMessage(msg, standardMsg))
1167-
1168-
11691140
def assertCountEqual(self, first, second, msg=None):
11701141
"""Asserts that two iterables have the same elements, the same number of
11711142
times, without regard to order.
@@ -1329,27 +1300,6 @@ def assertNotRegex(self, text, unexpected_regex, msg=None):
13291300
raise self.failureException(msg)
13301301

13311302

1332-
def _deprecate(original_func):
1333-
def deprecated_func(*args, **kwargs):
1334-
warnings.warn(
1335-
'Please use {0} instead.'.format(original_func.__name__),
1336-
DeprecationWarning, 2)
1337-
return original_func(*args, **kwargs)
1338-
return deprecated_func
1339-
1340-
# see #9424
1341-
failUnlessEqual = assertEquals = _deprecate(assertEqual)
1342-
failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
1343-
failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
1344-
failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
1345-
failUnless = assert_ = _deprecate(assertTrue)
1346-
failUnlessRaises = _deprecate(assertRaises)
1347-
failIf = _deprecate(assertFalse)
1348-
assertRaisesRegexp = _deprecate(assertRaisesRegex)
1349-
assertRegexpMatches = _deprecate(assertRegex)
1350-
assertNotRegexpMatches = _deprecate(assertNotRegex)
1351-
1352-
13531303

13541304
class FunctionTestCase(TestCase):
13551305
"""A test case that wraps a test function.

Lib/unittest/loader.py

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -93,30 +93,8 @@ def loadTestsFromTestCase(self, testCaseClass):
9393
loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
9494
return loaded_suite
9595

96-
# XXX After Python 3.5, remove backward compatibility hacks for
97-
# use_load_tests deprecation via *args and **kws. See issue 16662.
98-
def loadTestsFromModule(self, module, *args, pattern=None, **kws):
96+
def loadTestsFromModule(self, module, *, pattern=None):
9997
"""Return a suite of all test cases contained in the given module"""
100-
# This method used to take an undocumented and unofficial
101-
# use_load_tests argument. For backward compatibility, we still
102-
# accept the argument (which can also be the first position) but we
103-
# ignore it and issue a deprecation warning if it's present.
104-
if len(args) > 0 or 'use_load_tests' in kws:
105-
warnings.warn('use_load_tests is deprecated and ignored',
106-
DeprecationWarning)
107-
kws.pop('use_load_tests', None)
108-
if len(args) > 1:
109-
# Complain about the number of arguments, but don't forget the
110-
# required `module` argument.
111-
complaint = len(args) + 1
112-
raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint))
113-
if len(kws) != 0:
114-
# Since the keyword arguments are unsorted (see PEP 468), just
115-
# pick the alphabetically sorted first argument to complain about,
116-
# if multiple were given. At least the error message will be
117-
# predictable.
118-
complaint = sorted(kws)[0]
119-
raise TypeError("loadTestsFromModule() got an unexpected keyword argument '{}'".format(complaint))
12098
tests = []
12199
for name in dir(module):
122100
obj = getattr(module, name)

Lib/unittest/runner.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -159,15 +159,6 @@ def run(self, test):
159159
if self.warnings:
160160
# if self.warnings is set, use it to filter all the warnings
161161
warnings.simplefilter(self.warnings)
162-
# if the filter is 'default' or 'always', special-case the
163-
# warnings from the deprecated unittest methods to show them
164-
# no more than once per module, because they can be fairly
165-
# noisy. The -Wd and -Wa flags can be used to bypass this
166-
# only when self.warnings is None.
167-
if self.warnings in ['default', 'always']:
168-
warnings.filterwarnings('module',
169-
category=DeprecationWarning,
170-
message=r'Please use assert\w+ instead.')
171162
startTime = time.perf_counter()
172163
startTestRun = getattr(result, 'startTestRun', None)
173164
if startTestRun is not None:

Lib/unittest/test/_test_warnings.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,6 @@ def warnfun():
1818
warnings.warn('rw', RuntimeWarning)
1919

2020
class TestWarnings(unittest.TestCase):
21-
# unittest warnings will be printed at most once per type (max one message
22-
# for the fail* methods, and one for the assert* methods)
23-
def test_assert(self):
24-
self.assertEquals(2+2, 4)
25-
self.assertEquals(2*2, 4)
26-
self.assertEquals(2**2, 4)
27-
28-
def test_fail(self):
29-
self.failUnless(1)
30-
self.failUnless(True)
31-
3221
def test_other_unittest(self):
3322
self.assertAlmostEqual(2+2, 4)
3423
self.assertNotAlmostEqual(4+4, 2)

Lib/unittest/test/test_assertions.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -271,15 +271,6 @@ def testAssertDictEqual(self):
271271
r"\+ \{'key': 'value'\}$",
272272
r"\+ \{'key': 'value'\} : oops$"])
273273

274-
def testAssertDictContainsSubset(self):
275-
with warnings.catch_warnings():
276-
warnings.simplefilter("ignore", DeprecationWarning)
277-
278-
self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
279-
["^Missing: 'key'$", "^oops$",
280-
"^Missing: 'key'$",
281-
"^Missing: 'key' : oops$"])
282-
283274
def testAssertMultiLineEqual(self):
284275
self.assertMessages('assertMultiLineEqual', ("", "foo"),
285276
[r"\+ foo$", "^oops$",

Lib/unittest/test/test_case.py

Lines changed: 6 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -696,36 +696,6 @@ def testAssertIn(self):
696696
self.assertRaises(self.failureException, self.assertNotIn, 'cow',
697697
animals)
698698

699-
def testAssertDictContainsSubset(self):
700-
with warnings.catch_warnings():
701-
warnings.simplefilter("ignore", DeprecationWarning)
702-
703-
self.assertDictContainsSubset({}, {})
704-
self.assertDictContainsSubset({}, {'a': 1})
705-
self.assertDictContainsSubset({'a': 1}, {'a': 1})
706-
self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
707-
self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
708-
709-
with self.assertRaises(self.failureException):
710-
self.assertDictContainsSubset({1: "one"}, {})
711-
712-
with self.assertRaises(self.failureException):
713-
self.assertDictContainsSubset({'a': 2}, {'a': 1})
714-
715-
with self.assertRaises(self.failureException):
716-
self.assertDictContainsSubset({'c': 1}, {'a': 1})
717-
718-
with self.assertRaises(self.failureException):
719-
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
720-
721-
with self.assertRaises(self.failureException):
722-
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
723-
724-
one = ''.join(chr(i) for i in range(255))
725-
# this used to cause a UnicodeDecodeError constructing the failure msg
726-
with self.assertRaises(self.failureException):
727-
self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
728-
729699
def testAssertEqual(self):
730700
equal_pairs = [
731701
((), ()),
@@ -1788,45 +1758,18 @@ def testAssertNoLogsYieldsNone(self):
17881758
pass
17891759
self.assertIsNone(value)
17901760

1791-
def testDeprecatedMethodNames(self):
1792-
"""
1793-
Test that the deprecated methods raise a DeprecationWarning. See #9424.
1794-
"""
1795-
old = (
1796-
(self.failIfEqual, (3, 5)),
1797-
(self.assertNotEquals, (3, 5)),
1798-
(self.failUnlessEqual, (3, 3)),
1799-
(self.assertEquals, (3, 3)),
1800-
(self.failUnlessAlmostEqual, (2.0, 2.0)),
1801-
(self.assertAlmostEquals, (2.0, 2.0)),
1802-
(self.failIfAlmostEqual, (3.0, 5.0)),
1803-
(self.assertNotAlmostEquals, (3.0, 5.0)),
1804-
(self.failUnless, (True,)),
1805-
(self.assert_, (True,)),
1806-
(self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
1807-
(self.failIf, (False,)),
1808-
(self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))),
1809-
(self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
1810-
(self.assertRegexpMatches, ('bar', 'bar')),
1811-
)
1812-
for meth, args in old:
1813-
with self.assertWarns(DeprecationWarning):
1814-
meth(*args)
1815-
1816-
# disable this test for now. When the version where the fail* methods will
1817-
# be removed is decided, re-enable it and update the version
1818-
def _testDeprecatedFailMethods(self):
1819-
"""Test that the deprecated fail* methods get removed in 3.x"""
1820-
if sys.version_info[:2] < (3, 3):
1821-
return
1761+
def testDeprecatedFailMethods(self):
1762+
"""Test that the deprecated fail* methods get removed in 3.11"""
18221763
deprecated_names = [
18231764
'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual',
18241765
'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf',
1825-
'assertDictContainsSubset',
1766+
'assertNotEquals', 'assertEquals', 'assertAlmostEquals',
1767+
'assertNotAlmostEquals', 'assert_', 'assertDictContainsSubset',
1768+
'assertRaisesRegexp', 'assertRegexpMatches'
18261769
]
18271770
for deprecated_name in deprecated_names:
18281771
with self.assertRaises(AttributeError):
1829-
getattr(self, deprecated_name) # remove these in 3.x
1772+
getattr(self, deprecated_name)
18301773

18311774
def testDeepcopy(self):
18321775
# Issue: 5660

0 commit comments

Comments
 (0)