grasshopper
grasshopper

Reputation: 4068

Monkey patching a class in a function that is called from a child method (Python)

Let's say I have this situation:

module2.py

class Bar:

    def bar():
        a = 5
        # do stuff
         Messages.show("Done")

module1.py

import module2

class Foo:

    def __init__(self):
         self.bar = module2.Bar()
    def foo(self):
        self.bar.bar()

I want to test the method Foo.foo(), but I want to ignore Messages.show("Done), ie I want calls to the Messages.show function to be done on a mock object. If foo was calling Messages.show directly, I could use monkeypatch on foo to mock the Messages class. But now, I'm calling a class from another module and I don't know how to specify that Messages.show calls should not be done ( the reason being that they access the Gui and that doesn't work in a test environment). Let's assume I cannot modify module2.py.

Upvotes: 0

Views: 137

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Just override what module2 thinks Messages is:

import module2

module2.Messages = ...

Upvotes: 2

Related Questions