1

I'm a beginner programmer, I've been stuck for the past week trying to write unit tests. I read through the unit test docs and watched two long tutorials on implementing unit testing with Mock. The docs refer to mocking classes extensively, but for functions, I'm not sure if I should be using @patch/with patch, patch.dict{}, side_effect, or some other option to mock a function, specifically the argument to a function.

mymodule.py

def regex():
    '''Runs a regex, creates a dict 'data' and then calls scraper(data)'''

def scraper(data):
    '''scrapes a website and then calls a function which submits data to a db'''

I would like to create a test that passes in test data to the function scraper . Thank you in advance.

2 Answers 2

1

Yes, you can also do unit test using mock for non-object_oriented code.

See example below:

from unittest.mock import MagicMock
def a():
    return 10
def b():
    print(a())  
b()
a = MagicMock(return_value=3)
b()

And the output is:

10
3

In the previous example mock is used to fake/mock the function a(), so you can test function b() in isolation, b() is your SUT, without calling a() real implementation. This can be useful for more complex code, specially when function a() relies on data that might not be available in the unit test level.

Sign up to request clarification or add additional context in comments.

Comments

0

You haven't given enough examples to really help, but a couple of observations:

  • Generally, it's better to structure your code to avoid the need for mocking in tests; to the extent possible, each function should be a self-contained piece of code, which can be called separately.

  • There's no need to mock arguments; simply pass the test value in.

  • I'm not sure what's intended with this code:

    bar = {'key': 'value'}     
    
    def foo(bar):
        pass
    

    The bar defined at the outer level is a completely separate variable to the bar used as an argument in the function definition. It is confusing to give them the same name...

  • A function can be mocked using patch or patch.object with the return_value=... option; often, though, it suggests that the code needs to be refactored to reduce the dependency between the two functions.

3 Comments

I appreciate your response, I'm going to clarify the question, versus elaborating here.
Right, so in the test you call: scraper(test_data) No need to mock.
Ok, I must have another bug somewhere, but I'll troubleshoot and leave it for another post as needed. Thank you.

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.