0

I have a production code to test (code_to_test) presented which requires me to mock the test of loading of pickle file to do some validations further.

def code_to_test():
  #need to mock the below line
  with open("path/to/file/model.pickle", "rb") as pickle_file:
     model_dictionary = dill.load(pickle_file)
  #some other stuff to validate based on the mock

I mocked as follows

from unittest.mock import patch
with patch("path.of.module.code_to_test.dill.load") as _mock:
     _mock.return_value = some_dictionary_fixture

But it failed to test stating

When I tried to mock as follows, it shows up

ModuleNotFoundError

Update: I also tried to Patch builtins.open and use mock_open (Like so - https://stackoverflow.com/a/34677735/7641555 ). But I am not sure how to use it to mock my case.

jOasis
  • 394
  • 2
  • 10
  • 32
  • `mock` is part of unittest and you aren't showing your imports, so I'm going to assume you didn't import it. https://docs.python.org/3/library/unittest.mock.html – Kevin Welch May 30 '21 at 08:41
  • Why don't you extract the file loading? Either pass the loaded content in, or call a function that returns it. – jonrsharpe May 30 '21 at 08:50

1 Answers1

1

your patch is ~slightly off -- you're including the function but you should not:

from unittest.mock import patch
with patch("path.of.module.dill.load") as _mock:
     _mock.return_value = some_dictionary_fixture

but, you don't even need that -- since dill is imported as a module you can patch that directly:

import dill
from unittest import mock
with mock.patch.object(dill, 'load', return_value=some_dictionary_fixture):
    ...
anthony sottile
  • 61,815
  • 15
  • 148
  • 207