Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to mock a python function return value using patch

I have 2 files and a test file. For some unknown reason, i could not get this to pass. This tests always fail as it still returns 'hello_world' instead of using the mocked value of 'goodbye_world'.

utils.py

def hello_world():
    return "hello_world"

foo.py

from utils import hello_world
class Foo:
    def function_a():
        return hello_world()

test.py

import foo
from unittest.mock import patch
from unittest import TestCase

class TestStuff(TestCase):
  @patch('foo.hello_world')
  def test_hello_world(mock_value):
      mock_value.return_value = 'goodbye_world'
      temp = foo.Foo()
      self.assertEqual(temp.function_a(), 'goodbye_world')
like image 341
Lee Sai Mun Avatar asked Nov 08 '25 00:11

Lee Sai Mun


1 Answers

Oh i figured it out. I should be patching from the src directory. So it should be 'src.foo.hello_world'

like image 183
Lee Sai Mun Avatar answered Nov 10 '25 14:11

Lee Sai Mun



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!