pythonpytestmonkeypatching

How does one use pytest monkeypatch to patch a class


I would like to use pytest monkeypatch to mock a class which is imported into a separate module. Is this actually possible, and if so how does one do it? It seems like I have not seen an example for this exact situation. Suppose you have app with and imported class A in something.py

from something import A #Class is imported

class B :
  def __init__(self) :
   self.instance = A() #class instance is created

  def f(self, value) :
    return self.instance.g(value)

inside my test.py I want to mock A inside B

from something import B

#this is where I would mock A such that
def mock_A :
  def g(self, value) :
    return 2*value

#Then I would call B
c = B()
print(c.g(2)) #would be 4

I see how monkeypatch can be used to patch instances of classes, but how is it done for classes that have not yet been instantiated? Is it possible? Thanks!


Solution

  • tested this, works for me:

    def test_thing(monkeypatch):
        def patched_g(self, value):
            return value * 2
    
        monkeypatch.setattr(A, 'g', patched_g)
        b = B()
        assert b.f(2) == 4