-1

I am writing python tests for the first time. I am trying to test a basic mock. I want to return some value that I want when I call the function, rather than a mock object.

Here is the code: In views:

def myfunction():
    return "Actual data"

In test:

class TestBasic(unittest.TestCase):
    @patch('trailblazer.views.myfunction')
    def testMyFunction(self, val):
        print(val)
        val.return_value = "Test value"
        print(val)
        op = myfunction()
        print(op)

output:

<MagicMock name='myfunction' id='4520521120'>
<MagicMock name='myfunction' id='4520521120'>
Actual data
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

PS: I don't have my methods in a class and I don't want to change that.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
sinshil
  • 11
  • 4

1 Answers1

1

You have a direct reference to myfunction() in your test module, and that reference is never patched. You only patched the reference in the trailblazer.views module.

Your test would work if you used that reference instead of myfunction:

from trailblazer import views

class TestBasic(unittest.TestCase):
    @patch('trailblazer.views.myfunction')
    def testMyFunction(self, val):
        print(val)
        val.return_value = "Test value"
        print(val)
        op = views.myfunction()
        print(op)

However, a more meaningful test is to test the code that uses myfunction(). You use mocking to be able to focus on the behaviour of a specific unit of code, where mocking lets you precisely control interactions with other units.

In other words, if you have code like:

def some_function_to_test():
    # other things
    result = myfunction()
    # more things working on result
    return final_result

then when testing some_function_to_test() it makes sense to patch myfunction().

I recommend you read up on how Python names work; I highly recommend Facts and myths about Python names and values, together with Where to patch in the unittest.mock documentation.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I believe that this question, even though over simplified can help others who don't initially understand, like me, that the function that is actually being used needs to be mocked and not the one that was being imported. Also since, there was scope for a valid answer, the question seems valid to me. Hence, the significance of down voting the question is not very clear anymore. I would appreciate if you could tell me what can I do to improve the question. Thanks! – sinshil Oct 08 '17 at 19:57
  • @sinshil: I can't read minds, sorry. There is a tooltip on the downvote button that could be a reason, and the only advice I can give you is to read [ask] thoroughly and try to apply the advice. – Martijn Pieters Oct 08 '17 at 20:43
  • Sorry. I was merely trying to understand ,being new to this. – sinshil Oct 09 '17 at 09:46