Home:ALL Converter>How do I mock methods of a decorated class in python?

How do I mock methods of a decorated class in python?

Ask Time:2022-11-24T06:07:51         Author:CodeOcelot

Json Formatter

Having trouble with applying mocks to a class with a decorator. If I write the class without a decorator, patches are applied as expected. However, once the class is decorated, the same patch fails to apply.

What's going on here, and what's the best way to approach testing classes that may be decorated?

Here's a minimal reproduction.

# module.py
import functools


def decorator(func):

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper


@decorator  # comment this out and the test passes
class Something:

    def do_external(self):
        raise Exception("should be mocked")

    def run(self):
        self.do_external()
# test_module.py
from unittest import TestCase
from unittest.mock import Mock, patch

from module import Something


class TestModule(TestCase):
    @patch('module.Something.do_external', Mock())
    def test_module(self):
        s = Something()
        s.run()

If you prefer, here's an online reproducible example of the issue.

Author:CodeOcelot,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74553493/how-do-i-mock-methods-of-a-decorated-class-in-python
yy