4

为了简化我的问题,请考虑以下代码:
How do you write test for function foo1with patching\mocking the S3Downloader.read_filepart?

我更喜欢你会向我展示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"
4

1 回答 1

7

Note: Assuming that the snippet you mentioned is in fooer.py file

Please find the following sample test case to test 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"

In the snippet I have patched fooer.Session class. To patch an class, we need to provide module & the property of that module. The mock object is passed to the test case using an argument. You can use that object to modify the behaviour. In this case, I have updated the return value of the S3Downloader.

autospec=True in patch verifies that all the specifications of the patched class are properly followed. Basically it checks that the patch object was provided with the correct arguments.

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

A very good blog about testing with mock: https://www.toptal.com/python/an-introduction-to-mocking-in-python

于 2020-03-21T06:01:38.777 回答