0

I want to write test for Subclass while mocking Base as Base comes from an external library. How can I mock it given that we modify all callables in base class.

class SubClass(Base):
    def __init__(self, *args, **argv):
        super().__init__(*args, **argv)

        for attr_name in Base.__dict__:
            attr = getattr(self, attr_name)
            if callable(attr):
                setattr(self, attr_name, functools.partial(__class__.sanity_check, attr))

    @classmethod
    def sanity_check(func):
        txt = func()
        if 'banned_word' in txt:
            raise Exception('Device has banned word on it!')
        return txt
hasanatkazmi
  • 8,041
  • 2
  • 22
  • 18

1 Answers1

0

You do not need to mock the whole class, and it is enough to mock methods from it. BTW, I had to declare sanity_check as static to make your example code work.

Just look with a trivial base class:

class Base:
    def a(self):
        return "foo"
    def b(self):
        return "bar"

We can easily mock method a before creating a subclass object:

with unittest.mock.patch('module.Base.a', return_value='banned_word') as p:
    x = SubClass()
    x.a()

raises as expected:

Traceback (most recent call last):
  File "###", line #, in <module>
    x.a()
  File "###", line ##, in sanity_check
    raise Exception('Device has banned word on it!')
Exception: Device has banned word on it!

(module is the name of the module where Base is declared, I just used __main__ for testing...)

Allan Lewis
  • 308
  • 3
  • 13
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252