简体   繁体   English

在 python 中模拟 BigQuery 连接

[英]Mocking BigQuery Connection in python

I have the following code in a python file.我在 python 文件中有以下代码。 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??如何在不调用 bigquery API 的情况下为每个方法模拟对象?

I got it working.我让它工作了。 Basically you need to mock the function call to the bigquery client initialization.基本上,您需要模拟对 bigquery 客户端初始化的函数调用。 With the help of mock.patch we can mock the client object or the function from_service_account_json .mock.patch的帮助下,我们可以模拟客户端对象或函数from_service_account_json The following is the code以下是代码

with patch.object(bigquery.Client, "from_service_account_json") as srv_acc_mock:
            srv_acc_mock.return_value = Mock()

            # do something here....

We need to follow the same pattern for GCS client also but change the bigquery.Client to storage.Client by importing the right modules.我们也需要对 GCS 客户端遵循相同的模式,但通过导入正确的模块将bigquery.Client更改为storage.Client

While your accepted solution could work, it'll be more complete and robust to mock all of bigquery.Client .虽然您接受的解决方案可以工作,但模拟所有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 = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM