Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock third party static method

In order to simplify my question, consider the following code:
How do you write test for function foo1 with patching\mocking the S3Downloader.read_file part?

I prefer you will show me example usage of pytest-mock or even 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"
like image 868
JavaSa Avatar asked Mar 03 '23 16:03

JavaSa


1 Answers

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

like image 130
Jay Joshi Avatar answered Mar 05 '23 17:03

Jay Joshi