简体   繁体   English

Python 单元测试被测函数导入的函数

[英]Python Unit test a function imported by the function under test

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: lambda_函数:

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:竞争.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.虽然我能够修补被测函数,例如 patch.object,但上面的修补程序调用似乎不起作用,我无法弄清楚。

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. from.db import get_from_db创建一个使用db.calls.get_from_db get_prizes使用的就是这个新全局名称。

So that's the name you need to patch, not the original source from which get_from_db is initialized.所以这是您需要修补的名称,而不是初始化get_from_db的原始来源。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM