Can't pickle MagicMock or Mock

See original GitHub issue
This is because a MagicMock instance has a custom MagicMock subclass.

{{{
>>> from pickle import dumps
>>> from mock import MagicMock
>>> dumps(MagicMock())
Traceback (most recent call last):
  ...
pickle.PicklingError: Can't pickle <class 'mock.MagicMock'>: it's not the same 
object as mock.MagicMock
}}}

Original issue reported on code.google.com by fuzzyman on 8 Mar 2012 at 6:17

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

33reactions
sprtcommented, Jul 16, 2015

This works for my use case:

class PickableMock(Mock):
    def __reduce__(self):
        return (Mock, ())
0reactions
rbtcollinscommented, Jul 31, 2015

Upstreamed as http://bugs.python.org/issue14577 and http://bugs.python.org/issue20804

If there are more issues needed, please file them as bugs on bugs.python.org. {This tracker is focusing on bugs unique to the backport}

Read more comments on GitHub >

github_iconTop Results From Across the Web

PicklingError when using mock to check function is called
PicklingError: Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock . How can I test that os.
Read more >
31173 (Testing with PickleSerializer and Mock objects breaks.)
When trying to mock a session object when the session serializer is set to Pickle throws an error. _pickle.PicklingError: Can't pickle <class 'mock.mock....
Read more >
mock - issue #139 - Google Code
It's probably enough to make them pickleable though and if you're not using the magic methods then maybe the breakage won't affect you....
Read more >
Issue 14577: pickling uses __class__ so you can't pickle ...
msg158254 ‑ (view) Author: Michael Foord (michael.foord) * Date: 2012‑04‑14 11:16 msg158255 ‑ (view) Author: Antoine Pitrou (pitrou) * Date: 2012‑04‑14 11:20 msg158257 ‑ (view)...
Read more >
Multiprocessing and Pickle, How to Easily fix that?
Pickling is not secure, which means don't arbitrarily open untrusted pickle files. It is a good practice to initialize the class with the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found