Skip to content
Advertisement

How do I mock google cloud storage functions for my unittest ? (Python)

The following is my function that I want to unit test:

    def scraper(bucket_name,bucket_prefix):

        client = storage.Client()
        prefix_files = list(client.list_blobs(bucket_name,max_results = 700,page_token=None,prefix=bucket_prefix,delimiter='/'))
        return prefix_files

Since I want to unit test in isolation without any dependencies or internet, I would like to mock the google cloud client object and its functionality of list_blobs. Is that the correct way of going about unittesting this function? If so, how do I mock the above mentioned ? If not, what other suggestions would you guys have ? I know how to create a mock object but I’m not sure how to implement one in my context. Thank you.

Advertisement

Answer

I have managed to find an answer to my own question, it basically uses patching (pseudo code below):

@patch("yourfile.storage.Client")
def testingfunc(self,mockClient):
    call your original functions
    use assert statement with your mockClient
Advertisement