0

I am fairly new to Python and I would like to make a test where I read some values from a test json file rather than making an expensive http call.

In my test.py, I created a method with the same arguments and name as the method to be replaced. The method to be replaced is a top level method in task.py :

#In task.py
def foo(arg1: str, arg2: str, arg3 = None, arg4 = None):
   # do expensive stuff
   response = {"error": "For the sake of example", "result": ""}

def do_something():
   return foo("", "")


#In test.py
import task

def foo(arg1: str, arg2: str, arg3 = None, arg4 = None):
        config_path = os.path.join(test_files_dir, "test.json")
        with open(config_path, "rt") as f:
            result_dict = json.loads(f.read())
        response = {"error": "", "result": result_dict}
        return response

def test_method():
        task.foo = foo
        response = task.do_something()
        assert not response['error']

However step by step debug still enters the original method rather than the replaced one. What I am missing here ? If it worked, how can I make that change lasts for the duration of the test method only ?

FooBar
  • 132
  • 1
  • 9
  • Does this answer your question? [Override module method where from...import is used](https://stackoverflow.com/questions/10829200/override-module-method-where-from-import-is-used) – PM 77-1 Dec 01 '20 at 16:52
  • Why use `foo` at all? Why not just call your second foo `mock_foo` and use that in your test? – JeffUK Dec 01 '20 at 17:09
  • @PM77-1 Is a 3rd module really mandatory to achieve this ? – FooBar Dec 01 '20 at 17:22
  • @JeffUK I am not sure I understood what you meant. I want to change the method called inside `do_something()` when I am running tests. The behaviour I want to test is `do_something`, not `foo`. `foo` is just the access to external data (http call, and I want to replace it by local file read in tests). – FooBar Dec 01 '20 at 17:22
  • Does this answer your question? [Mocking out methods on any instance of a python class](https://stackoverflow.com/questions/5036920/mocking-out-methods-on-any-instance-of-a-python-class) – JeffUK Dec 01 '20 at 18:53
  • I think your question is possibly 'What is monkey patching' .. (for 100 points) but it's not recommended because it breaks your class for any further tests, which is explained in the link I posted above. – JeffUK Dec 01 '20 at 19:00

0 Answers0