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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With