-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
Closed as not planned
Closed as not planned
Copy link
Labels
invalidstdlibPython modules in the Lib dirPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Description
Bug report
Bug description:
When I unittest some code I need to patch the init to prevent DB calls etc, I ran into a problem where data was leaking between tests as a result. This doesn't occur when I don't patch the init function.
import unittest
from unittest.mock import patch
class Something(object):
data: dict = {}
def __init__(self, data = None):
if data is None:
self.data = {}
else:
self.data = data
class UnitTest(unittest.TestCase):
def test_something(self):
thing = Something()
thing.data["First"] = 1
self.assertEqual(thing.data, {"First": 1})
def test_something_else(self):
thing_else = Something()
thing_else.data["Second"] = 2
self.assertEqual(thing_else.data, {"Second": 2})
def test_something_patch_init(self):
with patch('main.Something.__init__', return_value=None):
thing = Something()
thing.data["First"] = 1
self.assertEqual(thing.data, {"First": 1})
def test_something_else_patch_init(self):
with patch('main.Something.__init__', return_value=None):
thing_else = Something()
thing_else.data["Second"] = 2
self.assertEqual(thing_else.data, {"Second": 2})
Running pytest results in the following error:
========================================================================== FAILURES ===========================================================================
_____________________________________________________________ UnitTest.test_something_patch_init ______________________________________________________________
self = <main.UnitTest testMethod=test_something_patch_init>
def test_something_patch_init(self):
with patch('main.Something.__init__', return_value=None):
thing = Something()
thing.data["First"] = 1
> self.assertEqual(thing.data, {"First": 1})
E AssertionError: {'Second': 2, 'First': 1} != {'First': 1}
E - {'First': 1, 'Second': 2}
E + {'First': 1}
main.py:30: AssertionError
=================================================================== short test summary info ===================================================================
FAILED main.py::UnitTest::test_something_patch_init - AssertionError: {'Second': 2, 'First': 1} != {'First': 1}
================================================================= 1 failed, 3 passed in 0.05s =================================================================
CPython versions tested on:
3.9, 3.10, 3.11, 3.12, 3.13
Operating systems tested on:
macOS
Metadata
Metadata
Assignees
Labels
invalidstdlibPython modules in the Lib dirPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Projects
Status
Done