-1

I am writing unit tests for a function, f, which imports other functions/classes which the unit test does not (directly) interact with. Is there any way I can patch those functions from the unit test (maybe in set_up())?

For reference, I am using Python 2.7.

From the unittest, I want to modify/patch the behavior of helper.

In unittest file:

def test_some_function():
    assert(some_function() == True)

In some_function() definition

import helper
def some_function():
    foo = helper.do_something()
    return foo & bar
idjaw
  • 25,487
  • 7
  • 64
  • 83
PK5144
  • 39
  • 5
  • 1
    Please provide a [mcve] of your scenario. i.e. Show your code and test code and explain what issues you are having. – idjaw Oct 01 '16 at 20:15
  • Edited. Hopefully that is enough. I don't think there is much more code I can paste, as this is more of a general question. I know that I can patch, etc. within a single file, but I want to be able to change the behaviour for the unit tests. I tried using a set_up() patch command, but could not get it to work. – PK5144 Oct 01 '16 at 20:21
  • 1
    So, you want to control what `helper.do_something` does? In other words, you are looking to mock that to control its return to write your unit tests for `some_function`? Because that is definitely doable – idjaw Oct 01 '16 at 20:22
  • Exactly! My first question was if that was possible, so thanks for clarifying that. :) How can I go about actually doing it? I've tried MagicMock, @patch, etc. based on different blogs, but nothing seems to change the behavior in the unit tests, only locally. – PK5144 Oct 01 '16 at 20:24

1 Answers1

1

Mocking out a module is fairly standard and documented here. You will see a fairly explicit example of how it is done.

Furthermore, it is important to understand where to patch, to understand how you properly mock out modules in other scripts.

To provide you with a more explicit example with reference to your code, you want to do something like this:

import unittest
from unittest.mock import patch

import module_you_are_testing

class MyTest(unittest.TestCase):

    @patch('module_you_are_testing.helper')
    def test_some_function(self, helper_mock):
        helper_mock.do_something.return_value = "something"
        # do more of your testing things here

So, the important thing to remember here, is that you are referencing helper with respect to where you are testing. Look at the sample code I provided and you will see we are importing module_you_are_testing. So, it is with respect to that you mock.

idjaw
  • 25,487
  • 7
  • 64
  • 83