Is there a way to make python pickle ignore “it's not the same object ” errors

前端 未结 2 894
轻奢々
轻奢々 2021-01-18 05:29

Is there a way to make python pickle ignore \"it\'s not the same object \" errors?

I\'m writing a test using Mock to have fine grain control over the results that d

相关标签:
2条回答
  • 2021-01-18 06:09

    In case someone wants a generic solution to pickle mocks:

    m = mock.MagicMock()
    m.__reduce__ = lambda self: (mock.MagicMock, ())
    

    Note that this doesn't seem to save internal content of the used mock (e.g calls).

    0 讨论(0)
  • 2021-01-18 06:18

    Looking at the where to patch section in the documentation I see this advice:

    The basic principle is that you patch where an object is used, which is not necessarily the same place as where it is defined.

    Following this recommendation, I've tried to replace:

    @patch('datetime.datetime', MockDatetime)
    

    with:

    @patch('__main__.datetime', MockDatetime)
    

    and I didn't get any error from pickle. Also, I added a print statement to make sure that datetime was really being patched and I got the expected value.

    0 讨论(0)
提交回复
热议问题