Author xtreak
Recipients jaraco, xtreak
Date 2019-02-22.12:32:29
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1550838749.82.0.249885366116.issue35512@roundup.psfhosted.org>
In-reply-to
Content
If I understand the issue correctly it's as below is a simple reproducer where target is resolved with {'a': 1} during the construction of the decorator [0] though it's redefined later in the program as target = dict(a=2). Also here due to this since target is reassigned the decorator just stores a reference to {'a': 1} and updates it with {'b': 2} leaving the reference to dict object {'a': 2} unpatched in test_with_decorator. Meanwhile in case of the context manager (test_with_context_manager) it's created and resolved at the time it's executed hence updating the object {'a': 2} correctly. A possible fix would be to store the reference to the string path of the patch '__main__.target' and try it again with importer function. I will take a further look into this. It would be helpful if you can confirm this reproducer is good enough and resembles the original report.


from unittest import mock

target = dict(a=1)

@mock.patch.dict('__main__.target', dict(b=2))
def test_with_decorator():
    print(f"target inside decorator : {target}")

def test_with_context_manager():
    with mock.patch.dict('__main__.target', dict(b=2)):
        print(f"target inside context : {target}")

target = dict(a=2)
test_with_decorator()
test_with_context_manager()

$ python3 test_foo.py
target inside decorator : {'a': 2}
target inside context : {'a': 2, 'b': 2}

[0] https://github.com/python/cpython/blob/3208880f1c72800bacf94a2045fcb0436702c7a1/Lib/unittest/mock.py#L1624
History
Date User Action Args
2019-02-22 12:32:29xtreaksetrecipients: + xtreak, jaraco
2019-02-22 12:32:29xtreaksetmessageid: <1550838749.82.0.249885366116.issue35512@roundup.psfhosted.org>
2019-02-22 12:32:29xtreaklinkissue35512 messages
2019-02-22 12:32:29xtreakcreate