[TIP] Mock and multiprocessing on Windows
akira
4kir4.1i at gmail.com
Tue Sep 25 04:59:53 PDT 2012
On 09/25/2012 12:23 PM, Stefan Scherfke wrote:
> Hi,
>
> [tl;dr] Below is a snippet that works on Linux/Mac but fails on Windows. Is there a way to fix it?
>
> The example below fails on Windows, because it uses spawn() to start subprocesses. The python
> state is being pickled and sent to the new process. However, pickling mock objects doesn’t
> work, so the example fails.
>
> Is there another way to mock something in a subprocess on Windows?
>
>
> Below is a minimal example that prints
>
> <class 'mock.MagicMock'>
> eggs
>
> on Mac/Linux and:
>
> <class 'function'>
> spam
>
> on Windows:
>
>
> # sub.py
> def spam():
> return 'spam'
>
>
> def main():
> print(type(spam))
> print(spam())
>
> # EOF
>
> # main.py
> import multiprocessing
> import mock
>
> import sub
>
>
> def main():
> with mock.patch('sub.spam') as spam_mock:
> spam_mock.return_value = 'eggs'
> p = multiprocessing.Process(target=sub.main)
> p.start()
> p.join()
>
>
> if __name__ == '__main__':
> main()
>
> # EOF
the fork semantics allows the child process to see changes to globals
introduced in the parent on Mac,Linux. mock.patch should be executed in
each process on Windows.
More information about the testing-in-python
mailing list