Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking BigQuery Connection in python

I have the following code in a python file. I have to unit test this file. But in order to do that I need to instantiate the object of the class

class BigQuery(metaclass=singleton.Singleton):
    """
    Big Query Class for operations on big query
    Will standardize in future versions.
    """

    def __init__(self):
        """
        Used for initializing client
        """
        try:
            self.client = bigquery.Client.from_service_account_json(
                SERVICE_ACCOUNT_JSON)
        except:
            logging.error("Cannot instantiate bigquery client", exc_info=True)
            raise Exception("Cannot instantiate bigquery client.")

The above class also contains other methods that needs to be tested. How will I mock the object for every method without calling bigquery API??

like image 250
bigbounty Avatar asked Mar 19 '26 06:03

bigbounty


1 Answers

While your accepted solution could work, it'll be more complete and robust to mock all of bigquery.Client. This will prevent implementation changes from breaking the mock, and it makes it easy to set return values:

from unittest.mock import patch

@patch('google.cloud.bigquery.Client', autospec=True)
def my_test(mock_bigquery): 
  mock_bigquery().query.return_value = ...
like image 87
Ran Halprin Avatar answered Mar 21 '26 23:03

Ran Halprin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!