简体   繁体   English

如何在测试中模拟python函数

[英]How do I mock a python function within a test

I'm trying to mock a function that's imported from a library which is renamed. 我正在尝试模拟从重命名的库中导入的函数。

The example 这个例子

mylibrarywithlongname: mylibrarywithlongname:

def helloworld():
    return "hello world"

def helloworld_helper():
    return helloworld()

Main program: 主程序:

import mylibrarywithlongname as ml
from mock import MagicMock

def test():
    ml.helloworld = MagicMock(return_value="oops")
    print(ml.helloworld_helper())

print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())

This returns 这返回

hello world
oops
oops

I'm trying to find the syntax to only mock within the test without having to copy the function and restore it manually. 我试图找到仅在测试中模拟的语法,而不必复制该函数并手动还原它。

The third line should return the original "hello world" 第三行应返回原始的“ hello world”

For this example, I'm using python 2.7 (because I try to mock an old project) 对于此示例,我使用的是python 2.7(因为我尝试模拟一个旧项目)

My attempt: 我的尝试:

from mock import MagicMock, patch

@patch(ml.helloworld, MagicMock(return_value="oops"))
def test():
    print(ml.helloworld_helper())

fails with the error 失败并显示错误

AttributeError: 'function' object has no attribute 'rsplit'

Answering my own question: I need to patch the original import name for it to work. 回答我自己的问题:我需要打补丁原始的导入名称才能起作用。

import mylibrarywithlongname as ml
from mock import patch

def test():
    with patch('mylibrarywithlongname.helloworld') as mp:
        ml.helloworld.return_value = "oops"
        print(ml.helloworld_helper())

print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())

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

相关问题 单元测试 Python Azure Function:如何构造一个带有 Z0ECD18C1D7A2BB7A28 负载的模拟测试请求消息? - Unit testing Python Azure Function: How do I construct a mock test request message with a JSON payload? 如何在Python单元测试中模拟类? - How do I mock a class in a Python unit test? 我可以模拟在 Python 测试中的另一个 function 调用中调用的 function 返回吗? - Can I mock a function return that is called within another function call in a Python Test? Python如何在另一个函数中模拟一个函数 - Python how to mock a function within another function Python:如何模拟设置类变量的函数调用 - Python: How do I mock a function call that sets a class variable 如何从单元测试中模拟.patch 库函数 - How to mock.patch library function from within unit test 如何在python中测试模拟调用的值是否在可能值的范围内 - How to test the value of a mock call in python is within a range of possible values 如何模拟从我的自定义 function 中调用的“csv.DictWriter.writeheader()”? - How do I mock `csv.DictWriter.writeheader()`, which is called from within my custom function? 如何在 Django 中模拟 function? - How do I mock a function in Django? 如何使用python mock直接模拟超类? - How do I directly mock a superclass with python mock?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM