1

I have a module that imports another module like this:

#main-file.py
import src.FetchFunction.video_service.fields.urls as urls

def some_func():
  return urls.fetch()

now I want to test this file like this:

import unittest
import src.FetchFunction.video_service.fields.urls as urls
from unittest.mock import MagicMock

class MainFileTest(unittest.TestCase):

    def test_example(self):
      urls.fetch = MagicMock(return_value='mocked_resp')
      assertSomething()

this part works well and does what I want. BUT this affects other tests file... I mean I have other tests that use the "urls.fetch" and now instead of getting the proper flow they get the above mocked response.

Any idea?

  • quite sure its not related but Im using pytest to run my tests
Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82

1 Answers1

1

Use patch in a context to define the scope where the mocked fetch should be used. In the example below, outside the with block the urls.fetch is reverted to the original value:

import unittest
from unittest.mock import patch

class MainFileTest(unittest.TestCase):

    def test_example(self):
        with patch('urls.fetch', return_value='mocked_resp'):
            # urls.fetch is mocked now
            assertSomething()
        # urls.fetch is not mocked anymore
hoefling
  • 59,418
  • 12
  • 147
  • 194
  • where were you 4 days ago... Thanks! – Tzook Bar Noy Apr 19 '18 at 13:59
  • sorry ^_^ but glad to hear it helped you! – hoefling Apr 19 '18 at 15:00
  • Hey @hoefling any ideas on how to mock this imported module in the tested file. "from .modifiers import Modifiers". Patch does seem to be nice – Tzook Bar Noy Apr 20 '18 at 07:53
  • Do you want to mock the module? Or do you want to mock what you actually import from it (`Modifiers` class)? Check out [my other answer](https://stackoverflow.com/a/48847105/2650249) for the mocking possibilities for the imported stuff. – hoefling Apr 20 '18 at 09:49