模拟另一个函数使用的python函数 [英] Mock a python function that is used by another function

查看:115
本文介绍了模拟另一个函数使用的python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对于问这样一个简单的问题感到很不高兴,但对于为什么这个示例无法按预期工作,我确实感到困惑.我希望以下断言的值为70会失败,但是测试的值为30.

I feel bad for asking such a simple question but I'm really confused as to why this example does not work as expected. I expect that the following assert would fail with a value of 70 but the test passes with a value of 30.

以下内容位于称为calc的pip包中:

The following is in a pip package called calc:

calc/__init__.py
from .calculator import *


calc/calculator.py
def get_value_1():
    return 10


def get_value_2():
    return 20


def addition():
    return get_value_1() + get_value_2()


test/simple.test
import calc
@mock.patch('calc.get_value_1', return_value=50)
def test1(mock_data):
    value = calc.addition()
    assert value == 30

Test output:
plugins: cov-2.6.0, nbval-0.9.1
collected 1 item                                                                                                                                             

test/simple_test.py::test6 PASSED

================= 1 passed in 0.21 seconds ===================

推荐答案

@JulienChein的答案非常好,我将根据您的代码片段添加一些示例.

The answer of @JulienChein is pretty good, and I will just add some example based on you snippet.

我创建了一个与您相似的环境.

I create a similar environment to your.

.
├── calculator.py
├── __init__.py
└── test
    ├── __init__.py
    └── test_calc.py

calculator.py

def get_value_1():
    return 10

def get_value_2():
    return 20

def addition():
    return get_value_1() + get_value_2()

__ init __.py

from .calculator import *

test/test_calc.py

from unittest.mock import patch
from .. import addition

# Here get_value_1, is mocked from calc.__inti__.py
@patch('calc.get_value_1', return_value=50)
def test1(mock_data):
    value = addition()
    assert value == 30  # This assert is False

# Here get_value_1, is mocked from calc.calculator.py
@patch('calc.calculator.get_value_1', return_value=50)
def test2(mock_data):
    value = addition()
    assert value == 70  # This assert is True

重点是addition使用 calc.calculator.py 中的方法,这就是为什么您需要从此文件中模拟该方法的原因.

The point is that addition uses methods from calc.calculator.py, that's why you need to mock the method from this file.

这篇关于模拟另一个函数使用的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆