Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 574
user3071643 Avatar asked Feb 27 '26 09:02

user3071643


1 Answers

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.g(2) == 4
like image 87
yedpodtrzitko Avatar answered Feb 28 '26 23:02

yedpodtrzitko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!