Skip to content

test_datetime does not respect custom setUpClass and tearDownClass #120242

Description

@sobolevn

Bug report

Example test case that can be possibly added to test_datetime.py:

classTestExample(unittest.TestCase):
@classmethoddefsetUpClass(cls) ->None:
cls.value_to_test=1returnsuper().setUpClass()
deftest_example_bug(self):
self.assertEqual(self.value_to_test, 1)

./python.exe -m test test_datetime -v -m test_example_bug outputs:

test_example_bug (test.datetimetester.TestExample_Pure.test_example_bug) ... ERROR
test_example_bug (test.datetimetester.TestExample_Fast.test_example_bug) ... ERROR
======================================================================
ERROR: test_example_bug (test.datetimetester.TestExample_Pure.test_example_bug)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/sobolev/Desktop/cpython2/Lib/test/datetimetester.py", line 77, in test_example_bug
self.assertEqual(self.value_to_test, 1)
^^^^^^^^^^^^^^^^^^
AttributeError: 'TestExample_Pure' object has no attribute 'value_to_test'
======================================================================
ERROR: test_example_bug (test.datetimetester.TestExample_Fast.test_example_bug)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/sobolev/Desktop/cpython2/Lib/test/datetimetester.py", line 77, in test_example_bug
self.assertEqual(self.value_to_test, 1)
^^^^^^^^^^^^^^^^^^
AttributeError: 'TestExample_Fast' object has no attribute 'value_to_test'
----------------------------------------------------------------------
Ran 2 tests in 0.003s
FAILED (errors=2)
test test_datetime failed
test_datetime failed (2 errors)
== Tests result: FAILURE ==
1 test failed:
test_datetime
Total duration: 208 ms
Total tests: run=2 (filtered)
Total test files: run=1/1 (filtered) failed=1
Result: FAILURE

This happens because of these lines:

forclsintest_classes:
cls.__name__+=suffix
cls.__qualname__+=suffix
@classmethod
defsetUpClass(cls_, module=module):
cls_._save_sys_modules=sys.modules.copy()
sys.modules[TESTS] =module
sys.modules['datetime'] =module.datetime_module
ifhasattr(module, '_pydatetime'):
sys.modules['_pydatetime'] =module._pydatetime
sys.modules['_strptime'] =module._strptime
@classmethod
deftearDownClass(cls_):
sys.modules.clear()
sys.modules.update(cls_._save_sys_modules)
cls.setUpClass=setUpClass
cls.tearDownClass=tearDownClass

I proposed this fix: https://github.com/python/cpython/pull/119675/files#diff-d4ea73ff6f3d1428ce4536793404e64ce7dbc1f6d0afe22f707ee0a24777afea but it was not merged.

Refs #119675
Refs #119659

Linked PRs

Metadata

Metadata

Assignees

Labels

testsTests in the Lib/test dirtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions