如何模拟第三方静态方法

问题描述 投票:2回答:1

为了简化我的问题,请考虑以下代码:如何使用补丁\模拟foo1部分编写功能S3Downloader.read_file的测试?

[我希望您向我展示pytest-mock甚至unitest.mock的用法示例

from sagemaker.s3 import S3Downloader

class Fooer(object):
    @staticmethod
    def foo1(s3_location):       
        s3_content = S3Downloader.read_file(s3_location)
        return Fooer.foo2(s3_content)


    @staticmethod
    def foo2(s3_content):
       return s3_content +"_end"
python-3.x pytest python-unittest pytest-mock
1个回答
2
投票

注意:假设您提到的代码段位于fooer.py文件中

请找到以下示例测试用例以测试foo1

import fooer
import mock

class TestFooer(object):

    @mock.patch('fooer.S3Downloader', autospec=True)
    def test_foo1(self, mock_s3_downloader):
        """
        Verify foo1 method that it should return the content downloaded from S3 bucket with _end prefix
        """
        mock_s3_downloader.read_file.return_value = "s3_content"
        foo1_result = fooer.Fooer.foo1("s3_location")
        assert foo1_result == "s3_content_end", "Content was not returned with _end prefix"

在摘要中,我修补了fooer.Session类。要修补一个类,我们需要提供模块和该模块的属性。模拟对象使用一个参数传递给测试用例。您可以使用该对象来修改行为。在这种情况下,我已经更新了S3Downloader的返回值。

autospec=True in patch验证已正确遵循修补类的所有规范。基本上,它将检查是否为修补程序对象提供了正确的参数。

参考:https://medium.com/@yeraydiazdiaz/what-the-mock-cheatsheet-mocking-in-python-6a71db997832

关于模拟测试的非常不错的博客:https://www.toptal.com/python/an-introduction-to-mocking-in-python

© www.soinside.com 2019 - 2024. All rights reserved.