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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

where were you 4 days ago... Thanks!
sorry ^_^ but glad to hear it helped you!
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
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 for the mocking possibilities for the imported stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.