Python中的模拟方法调用 [英] Mocking Method Calls In Python

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

问题描述

我一直在和网络上搜索堆栈交换,以了解如何执行此操作,但是我无法理解如何模拟方法的行为.我正在尝试模拟openpyxl行为和自定义类的行为.这是我的尝试:

I have been searching stack exchange and around the web for how to do this, but I cannot understand how to mock behaviors for methods. I am trying to mock openpyxl behaviors and behaviors for my custom class. Here is my attempt:

import unittest
from unittest.mock import MagicMock
import openpyxl 
from MyPythonFile import MyClass

class TestMyClass(unittest.TestCase):
  def test_myclass(self):
    myclass = MyClass()
    wb = openpyxl.workbook()
    ws = openpyxl.worksheet()
    wbPath = 'wbPath'

    openpyxl.load_workbook(wbPath, data_only = True) = MagicMock(return_value=wb)

当我尝试最后一行时,出现错误无法分配给函数调用".我需要使用patch.object('openpyxl','load_workbook')吗?我习惯使用Groovy在Java中进行模拟,而且非常简单.

When I try the final line I get the error "can't assign to function call". Do I need to use patch.object('openpyxl','load_workbook')? I am used to mocking in Java with Groovy and it's pretty straightforward.

*想根据@alxwrd的响应添加测试的最终版本

* wanted to add the finalized version of the test based on the response from @alxwrd

import unittest
from unittest.mock import MagicMock
import openpyxl 
import configparser
from MyPythonFile import MyClass

class TestMyClass(unittest.TestCase):
  def test_myclass(self):
    myclass = MyClass()
    wb = openpyxl.workbook()
    ws = openpyxl.worksheet()
    config = configparser.ConfigParser()

    openpyxl.load_workbook = MagicMock(return_value=wb)
    wb.get_sheet_by_name = MagicMock(return_value=ws)

    config.sections() = MagicMock(return_value=['Section1'])
    config.get = MagicMock(side_effect=['Value1','Value2']) 

请注意,config.get使用side_effect参数给出了多次返回,因此,如果在代码中一次调用config.get(),它将返回'Value1',而当第二次调用config.get()时,它将返回'Value2'.

Notice that config.get gives multiple returns with the side_effect parameter, so if config.get() is called once in the code it returns 'Value1' and when config.get() is called a second time it returns 'Value2'.

推荐答案

您不能覆盖函数调用,但是可以覆盖函数本身.

You can't override a function call, but you can override the function itself.

文档:

>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')

所以在您的情况下:

openpyxl.load_workbook = MagicMock(return_value=wb)

这篇关于Python中的模拟方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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