Skip to content

Commit f32a5b1

Browse files
authored
Update unittest partially (#6051)
* Update `test_unittest` from 3.13.5 * Remove old `test_unittest.py`
1 parent 1c55f9e commit f32a5b1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1612
-680
lines changed

Lib/test/test_unittest.py

Lines changed: 0 additions & 16 deletions
This file was deleted.

Lib/test/test_unittest/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import os.path
2+
from test.support import load_package_tests
3+
4+
5+
def load_tests(*args):
6+
return load_package_tests(os.path.dirname(__file__), *args)

Lib/test/test_unittest/__main__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from . import load_tests
2+
import unittest
3+
4+
unittest.main()

Lib/unittest/test/_test_warnings.py renamed to Lib/test/test_unittest/_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)
File renamed without changes.

Lib/unittest/test/support.py renamed to Lib/test/test_unittest/support.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,19 @@ def addSuccess(self, test):
136136

137137
def wasSuccessful(self):
138138
return True
139+
140+
141+
class BufferedWriter:
142+
def __init__(self):
143+
self.result = ''
144+
self.buffer = ''
145+
146+
def write(self, arg):
147+
self.buffer += arg
148+
149+
def flush(self):
150+
self.result += self.buffer
151+
self.buffer = ''
152+
153+
def getvalue(self):
154+
return self.result

Lib/unittest/test/test_assertions.py renamed to Lib/test/test_unittest/test_assertions.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -271,20 +271,11 @@ 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"),
285-
[r"\+ foo$", "^oops$",
286-
r"\+ foo$",
287-
r"\+ foo : oops$"])
276+
[r"\+ foo\n$", "^oops$",
277+
r"\+ foo\n$",
278+
r"\+ foo\n : oops$"])
288279

289280
def testAssertLess(self):
290281
self.assertMessages('assertLess', (2, 1),
@@ -395,6 +386,16 @@ def testAssertWarns(self):
395386
'^UserWarning not triggered$',
396387
'^UserWarning not triggered : oops$'])
397388

389+
def test_assertNotWarns(self):
390+
def warn_future():
391+
warnings.warn('xyz', FutureWarning, stacklevel=2)
392+
self.assertMessagesCM('_assertNotWarns', (FutureWarning,),
393+
warn_future,
394+
['^FutureWarning triggered$',
395+
'^oops$',
396+
'^FutureWarning triggered$',
397+
'^FutureWarning triggered : oops$'])
398+
398399
def testAssertWarnsRegex(self):
399400
# test error not raised
400401
self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'unused regex'),

Lib/unittest/test/test_async_case.py renamed to Lib/test/test_unittest/test_async_case.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,9 @@ async def __aenter__(self):
3737
pass
3838

3939

40-
# TODO: RUSTPYTHON; used by following test suite
41-
# VAR = contextvars.ContextVar('VAR', default=())
40+
VAR = contextvars.ContextVar('VAR', default=())
4241

4342

44-
@unittest.skip("TODO: RUSTPYTHON; requires sys.get_coroutine_origin_tracking_depth()")
4543
class TestAsyncCase(unittest.TestCase):
4644
maxDiff = None
4745

@@ -50,6 +48,8 @@ def setUp(self):
5048
# starting a new event loop
5149
self.addCleanup(support.gc_collect)
5250

51+
# TODO: RUSTPYTHON
52+
@unittest.expectedFailure
5353
def test_full_cycle(self):
5454
expected = ['setUp',
5555
'asyncSetUp',
@@ -296,6 +296,8 @@ async def on_cleanup2(self):
296296
test.doCleanups()
297297
self.assertEqual(events, ['asyncSetUp', 'test', 'asyncTearDown', 'cleanup2', 'cleanup1'])
298298

299+
# TODO: RUSTPYTHON
300+
@unittest.expectedFailure
299301
def test_deprecation_of_return_val_from_test(self):
300302
# Issue 41322 - deprecate return of value that is not None from a test
301303
class Nothing:
@@ -486,5 +488,21 @@ async def test_demo1(self):
486488
result = test.run()
487489
self.assertTrue(result.wasSuccessful())
488490

491+
# TODO: RUSTPYTHON
492+
@unittest.expectedFailure
493+
def test_loop_factory(self):
494+
asyncio.set_event_loop_policy(None)
495+
496+
class TestCase1(unittest.IsolatedAsyncioTestCase):
497+
loop_factory = asyncio.EventLoop
498+
499+
async def test_demo1(self):
500+
pass
501+
502+
test = TestCase1('test_demo1')
503+
result = test.run()
504+
self.assertTrue(result.wasSuccessful())
505+
self.assertIsNone(support.maybe_get_event_loop_policy())
506+
489507
if __name__ == "__main__":
490508
unittest.main()

Lib/unittest/test/test_break.py renamed to Lib/test/test_unittest/test_break.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ def __init__(self, catchbreak):
236236
self.testRunner = FakeRunner
237237
self.test = test
238238
self.result = None
239+
self.durations = None
239240

240241
p = Program(False)
241242
p.runTests()
@@ -244,7 +245,8 @@ def __init__(self, catchbreak):
244245
'verbosity': verbosity,
245246
'failfast': failfast,
246247
'tb_locals': False,
247-
'warnings': None})])
248+
'warnings': None,
249+
'durations': None})])
248250
self.assertEqual(FakeRunner.runArgs, [test])
249251
self.assertEqual(p.result, result)
250252

@@ -259,7 +261,8 @@ def __init__(self, catchbreak):
259261
'verbosity': verbosity,
260262
'failfast': failfast,
261263
'tb_locals': False,
262-
'warnings': None})])
264+
'warnings': None,
265+
'durations': None})])
263266
self.assertEqual(FakeRunner.runArgs, [test])
264267
self.assertEqual(p.result, result)
265268

Lib/unittest/test/test_case.py renamed to Lib/test/test_unittest/test_case.py

Lines changed: 80 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
import unittest
1717

18-
from unittest.test.support import (
18+
from test.test_unittest.support import (
1919
TestEquality, TestHashing, LoggingResult, LegacyLoggingResult,
2020
ResultWithNoStartTestRunStopTestRun
2121
)
@@ -304,7 +304,8 @@ def defaultTestResult(self):
304304
def test(self):
305305
pass
306306

307-
Foo('test').run()
307+
with self.assertWarns(RuntimeWarning):
308+
Foo('test').run()
308309

309310
def test_deprecation_of_return_val_from_test(self):
310311
# Issue 41322 - deprecate return of value that is not None from a test
@@ -709,36 +710,6 @@ def testAssertIn(self):
709710
self.assertRaises(self.failureException, self.assertNotIn, 'cow',
710711
animals)
711712

712-
def testAssertDictContainsSubset(self):
713-
with warnings.catch_warnings():
714-
warnings.simplefilter("ignore", DeprecationWarning)
715-
716-
self.assertDictContainsSubset({}, {})
717-
self.assertDictContainsSubset({}, {'a': 1})
718-
self.assertDictContainsSubset({'a': 1}, {'a': 1})
719-
self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
720-
self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
721-
722-
with self.assertRaises(self.failureException):
723-
self.assertDictContainsSubset({1: "one"}, {})
724-
725-
with self.assertRaises(self.failureException):
726-
self.assertDictContainsSubset({'a': 2}, {'a': 1})
727-
728-
with self.assertRaises(self.failureException):
729-
self.assertDictContainsSubset({'c': 1}, {'a': 1})
730-
731-
with self.assertRaises(self.failureException):
732-
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
733-
734-
with self.assertRaises(self.failureException):
735-
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
736-
737-
one = ''.join(chr(i) for i in range(255))
738-
# this used to cause a UnicodeDecodeError constructing the failure msg
739-
with self.assertRaises(self.failureException):
740-
self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
741-
742713
def testAssertEqual(self):
743714
equal_pairs = [
744715
((), ()),
@@ -1161,6 +1132,8 @@ def testAssertMultiLineEqual(self):
11611132
# need to remove the first line of the error message
11621133
error = str(e).split('\n', 1)[1]
11631134
self.assertEqual(sample_text_error, error)
1135+
else:
1136+
self.fail(f'{self.failureException} not raised')
11641137

11651138
def testAssertEqualSingleLine(self):
11661139
sample_text = "laden swallows fly slowly"
@@ -1177,6 +1150,74 @@ def testAssertEqualSingleLine(self):
11771150
# need to remove the first line of the error message
11781151
error = str(e).split('\n', 1)[1]
11791152
self.assertEqual(sample_text_error, error)
1153+
else:
1154+
self.fail(f'{self.failureException} not raised')
1155+
1156+
def testAssertEqualwithEmptyString(self):
1157+
'''Verify when there is an empty string involved, the diff output
1158+
does not treat the empty string as a single empty line. It should
1159+
instead be handled as a non-line.
1160+
'''
1161+
sample_text = ''
1162+
revised_sample_text = 'unladen swallows fly quickly'
1163+
sample_text_error = '''\
1164+
+ unladen swallows fly quickly
1165+
'''
1166+
try:
1167+
self.assertEqual(sample_text, revised_sample_text)
1168+
except self.failureException as e:
1169+
# need to remove the first line of the error message
1170+
error = str(e).split('\n', 1)[1]
1171+
self.assertEqual(sample_text_error, error)
1172+
else:
1173+
self.fail(f'{self.failureException} not raised')
1174+
1175+
def testAssertEqualMultipleLinesMissingNewlineTerminator(self):
1176+
'''Verifying format of diff output from assertEqual involving strings
1177+
with multiple lines, but missing the terminating newline on both.
1178+
'''
1179+
sample_text = 'laden swallows\nfly sloely'
1180+
revised_sample_text = 'laden swallows\nfly slowly'
1181+
sample_text_error = '''\
1182+
laden swallows
1183+
- fly sloely
1184+
? ^
1185+
+ fly slowly
1186+
? ^
1187+
'''
1188+
try:
1189+
self.assertEqual(sample_text, revised_sample_text)
1190+
except self.failureException as e:
1191+
# need to remove the first line of the error message
1192+
error = str(e).split('\n', 1)[1]
1193+
self.assertEqual(sample_text_error, error)
1194+
else:
1195+
self.fail(f'{self.failureException} not raised')
1196+
1197+
def testAssertEqualMultipleLinesMismatchedNewlinesTerminators(self):
1198+
'''Verifying format of diff output from assertEqual involving strings
1199+
with multiple lines and mismatched newlines. The output should
1200+
include a - on it's own line to indicate the newline difference
1201+
between the two strings
1202+
'''
1203+
sample_text = 'laden swallows\nfly sloely\n'
1204+
revised_sample_text = 'laden swallows\nfly slowly'
1205+
sample_text_error = '''\
1206+
laden swallows
1207+
- fly sloely
1208+
? ^
1209+
+ fly slowly
1210+
? ^
1211+
-\x20
1212+
'''
1213+
try:
1214+
self.assertEqual(sample_text, revised_sample_text)
1215+
except self.failureException as e:
1216+
# need to remove the first line of the error message
1217+
error = str(e).split('\n', 1)[1]
1218+
self.assertEqual(sample_text_error, error)
1219+
else:
1220+
self.fail(f'{self.failureException} not raised')
11801221

11811222
def testEqualityBytesWarning(self):
11821223
if sys.flags.bytes_warning:
@@ -1801,45 +1842,18 @@ def testAssertNoLogsYieldsNone(self):
18011842
pass
18021843
self.assertIsNone(value)
18031844

1804-
def testDeprecatedMethodNames(self):
1805-
"""
1806-
Test that the deprecated methods raise a DeprecationWarning. See #9424.
1807-
"""
1808-
old = (
1809-
(self.failIfEqual, (3, 5)),
1810-
(self.assertNotEquals, (3, 5)),
1811-
(self.failUnlessEqual, (3, 3)),
1812-
(self.assertEquals, (3, 3)),
1813-
(self.failUnlessAlmostEqual, (2.0, 2.0)),
1814-
(self.assertAlmostEquals, (2.0, 2.0)),
1815-
(self.failIfAlmostEqual, (3.0, 5.0)),
1816-
(self.assertNotAlmostEquals, (3.0, 5.0)),
1817-
(self.failUnless, (True,)),
1818-
(self.assert_, (True,)),
1819-
(self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
1820-
(self.failIf, (False,)),
1821-
(self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))),
1822-
(self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
1823-
(self.assertRegexpMatches, ('bar', 'bar')),
1824-
)
1825-
for meth, args in old:
1826-
with self.assertWarns(DeprecationWarning):
1827-
meth(*args)
1828-
1829-
# disable this test for now. When the version where the fail* methods will
1830-
# be removed is decided, re-enable it and update the version
1831-
def _testDeprecatedFailMethods(self):
1832-
"""Test that the deprecated fail* methods get removed in 3.x"""
1833-
if sys.version_info[:2] < (3, 3):
1834-
return
1845+
def testDeprecatedFailMethods(self):
1846+
"""Test that the deprecated fail* methods get removed in 3.12"""
18351847
deprecated_names = [
18361848
'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual',
18371849
'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf',
1838-
'assertDictContainsSubset',
1850+
'assertNotEquals', 'assertEquals', 'assertAlmostEquals',
1851+
'assertNotAlmostEquals', 'assert_', 'assertDictContainsSubset',
1852+
'assertRaisesRegexp', 'assertRegexpMatches'
18391853
]
18401854
for deprecated_name in deprecated_names:
18411855
with self.assertRaises(AttributeError):
1842-
getattr(self, deprecated_name) # remove these in 3.x
1856+
getattr(self, deprecated_name)
18431857

18441858
def testDeepcopy(self):
18451859
# Issue: 5660
@@ -1956,7 +1970,7 @@ def testNoCycles(self):
19561970
del case
19571971
self.assertFalse(wr())
19581972

1959-
# TODO: RUSTPYTHON; destructors
1973+
# TODO: RUSTPYTHON
19601974
@unittest.expectedFailure
19611975
def test_no_exception_leak(self):
19621976
# Issue #19880: TestCase.run() should not keep a reference

0 commit comments

Comments
 (0)