如何模拟第三方静态方法

Jav*_*aSa 3 pytest python-3.x python-unittest pytest-mock

为了简化我的问题,请考虑以下代码:
如何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"
Run Code Online (Sandbox Code Playgroud)

Jay*_*shi 6

注意:假设您提到的代码段在 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"

Run Code Online (Sandbox Code Playgroud)

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

autospec=Truein patch 验证是否正确遵循了修补类的所有规范。基本上它会检查补丁对象是否提供了正确的参数。

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

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