Is there a way to make a Pyrenean pickle to ignore the errors "this is not the same object"

Is there a way to make python pickle ignore the error "this is not the same object"?

I am writing a test using Mock to have fine control over the results obtained by datetime.utcnow (). The code I use is time sensitive, so the layout of the patch makes it easy to test.

The same tests should sort the objects and send the results to the remote server. For testing purposes, if the standard time and time was pickled and received by the remote server, everything will be fine.

Unfortunately, the brine module has the following error:

Unable to sort <type 'datetime.datetime'>: this is not the same object as datetime.datetime

Here is a minimal example to reproduce the error.

from mock import patch from datetime import datetime import pickle class MockDatetime(datetime): frozendt = datetime(2011,05,31) @classmethod def advance(cls, **kw): cls.frozendt = cls.frozendt + timedelta(**kw) @classmethod def utcnow(cls): return cls.frozendt @patch('datetime.datetime', MockDatetime) def test(): pickle.dumps(datetime.utcnow()) if __name__ == '__main__': test() 

Are there any combos of the __reduce__ and __getstate__ methods that could trick the pickle mechanism into thinking MockDatetime - is this the time I'm pickled?

+6
source share
2 answers

Looking at where the fix is in the documentation, I see this tip:

The basic principle is that you correct where the object is used, which does not necessarily coincide with the place where it is defined.

Following this recommendation, I tried replacing:

 @patch('datetime.datetime', MockDatetime) 

from:

 @patch('__main__.datetime', MockDatetime) 

and I did not get any errors from pickle . In addition, I added a print statement to make sure the datetime really fixed, and I got the expected value.

+5
source

In case someone wants a general solution for pickling layouts:

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

Note that this does not seem to preserve the internal content of the mock used (e.g. calls).

+2
source

Source: https://habr.com/ru/post/903075/


All Articles