1

So I have these files:

transmitter.py

import multiprocessing as MP
from common import BaseWorker

class TxWorker(BaseWorker):
    ... code ...

common.py

import multiprocessing as MP

class BaseWorker(MP.Process):
    ... code ...

Now I have this test file, written for pytest with pytest-mock plugin:

from transmitter import TxWorker

class MockProcess:
    def __init__(self, name, *args, **kwargs):
        self.name = name

    def canary():
        return "Mocked!"

@pytest.fixture(scope="module")
def mocked_process(module_mocker):
    module_mocker.patch(WHERE_TO_PATCH, MockProcess)
    yield

def test_case(mocked_process):
    tw = TxWorker()
    assert tw.canary() == "Mocked!"

I can't get this test to work.

I've tried setting WHERE_TO_PATCH to:

  • transmitter.MP.Process
  • common.MP.Process
  • multiprocessing.Process

None of them works. I keep having the error AttributeError: 'TxWorker' object has no attribute 'canary'.

Where did I go wrong?

pepoluan
  • 6,132
  • 4
  • 46
  • 76
  • Does this answer your question? [How do a mock a superclass that is part of a library?](https://stackoverflow.com/questions/28181867/how-do-a-mock-a-superclass-that-is-part-of-a-library) – Brian McCutchon Dec 16 '20 at 06:04
  • Because you're using it as a superclass. – Brian McCutchon Dec 16 '20 at 06:04
  • @BrianMcCutchon so in essence: I cannot replace the class, I should hijack its `__init__` instead? – pepoluan Dec 16 '20 at 09:07
  • Or use the mixin approach in mgilson's answer, or do something else. – Brian McCutchon Dec 16 '20 at 20:00
  • Yeah I was originally planning to isolate BaseWorker so it won't actually start in a separate process. The canary() was just to ensure that I've patched the correct `Process`. But thanks anyways for the tip! – pepoluan Dec 17 '20 at 02:59

0 Answers0