Python Unit test a function imported by the function under test

Question:

I’m attempting to implement thorough testing of code that calls to a database at various at points. I’m able to mock the calls that occur in the function under test, but I’m now also needing to stub out functions that are imported by the function under test.

As an example:

lambda_function:

from competiton.prizes import get_prize

def lambda_handler():
    # This has a call to DB and has been stubbed
    get_entries()
    some_functionality()
    get_prizes()

def get_prizes():
    return get_prizes()

competition.prizes.common:

from .db import get_from_db

def get_prizes()
    # This is the call I want to mock a return value
    some_info = get_from_db()

And my test:

class TestLambdaFunction:

    @patch("db.calls.get_from_db", return_value = (200, 100))
    @patch.object(lambda_function, "get_entries")
    def test_level_one_not_reached(self, mock_get_milestones, mock_get_reward):
        x = lambda_function()

While I am able to patch a function under test, such as the patch.object, the patch call above just doesn’t seem to work and I can’t figure it out.

Asked By: FreakShow

||

Answers:

from .db import get_from_db

def get_prizes()
    # This is the call I want to mock a return value
    some_info = get_from_db()

from .db import get_from_db creates a new global name that’s initalized using db.calls.get_from_db, and it’s this new global name that get_prizes uses.

So that’s the name you need to patch, not the original source from which get_from_db is initialized.

class TestLambdaFunction:

    @patch("competition.prizes.common.get_from_db", return_value = (200, 100))
    @patch.object(lambda_function, "get_entries")
    def test_level_one_not_reached(self, mock_get_milestones, mock_get_reward):
        x = lambda_function()
Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.