Skip to content

Instantly share code, notes, and snippets.

@8enmann
Created June 24, 2019 20:46
Show Gist options
  • Save 8enmann/3e3c868c1520b13dfafda6787e272f1f to your computer and use it in GitHub Desktop.
Save 8enmann/3e3c868c1520b13dfafda6787e272f1f to your computer and use it in GitHub Desktop.
Partly broken example trying to test Process as a single thread.
# mock_process.py
"""Make a process single threaded for testing."""
import multiprocessing
def f(x):
return x
def target():
"""Run a process by specifying a target function."""
p = multiprocessing.Process(target=f, args=(1,))
p.start()
p.join()
class Worker(multiprocessing.Process):
def __init__(self, x):
super(Worker, self).__init__()
self.x = x
def run(self):
return self.x
def subclass():
"""Run a process by subclassing Process."""
p = Worker(1)
p.start()
p.join()
import pytest
import mock
@mock.patch('multiprocessing.Process')
def test_target(MockProcess):
target()
kwargs = MockProcess.call_args.kwargs
assert kwargs['target'](*kwargs['args']) == 1
mp = MockProcess.return_value
assert mp.start.called
assert mp.join.called
class DummyWorker(Worker):
def __init__(self, x):
super(DummyWorker, self).__init__()
def start():
self.ret = self.run()
def join():
pass
def mock_start(self):
return self.run()
@mock.patch.object(Worker, 'join')
@mock.patch.object(Worker, 'start')
def test_subclass(mock_start, mock_join):
subclass()
import pdb; pdb.set_trace()
assert 1 == subclass()
pytest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment