How to mock a function called in a class attribute in python

60 Views Asked by At

I need to mock a function that is called in a class attribute in a python class. I'm able to do it patching the function when the object is initialised, but it does not work when I access it without creating an instance. See the code below:

# methods.py

def bar():
    return "bar"
# foo.py
from methods import bar

class Foo:
    class_attribute = bar()
    
    def __init__(self):
        self.class_attribute = bar()

#test_foo.py
from foo import Foo
import unittest
from unittest.mock import patch

class FooTestCase(unittest.TestCase):
    @patch("foo.bar")
    def test_mock_foo(self, mock):
        mock.return_value = "patched foo"
        print(Foo.class_attribute) # it prints "bar"
        print(Foo().class_attribute) # it prints "patched foo"

unittest.main(argv=[''], verbosity=0,exit=False)

How is it possible to mock the function without mocking the class attribute?

0

There are 0 best solutions below