Search code examples
python-3.xpython-mock

How to patch google.cloud.storage in python


I have a class that import google cloud:

StorageUtils:

from google.cloud import storage

I have a app that uses StorageUtils:

App:

import StorageUtils

Then I have a test, that I want to test my app

Test:

from app import App

I want to test my app without using google cloud. The easiest way I found is to use sys.modules:

import sys
from unittest.mock import MagicMock
sys.modules["google.cloud.storage"] = MagicMock()

I found this solution quite a work around. Are there any other way using python mock?


Solution

  • In this case, if the file that contains the class StorageUtils is called storage_utils.py:

    #test_storage.py
    @patch("storage_utils.storage")
    def test_storage(st):
        storage = StorageUtils()