Python 3.x 在python中模拟BigQuery连接
我在python文件中有以下代码。我必须对这个文件进行单元测试。但为了做到这一点,我需要实例化类的对象Python 3.x 在python中模拟BigQuery连接,python-3.x,google-bigquery,mocking,python-unittest,python-unittest.mock,Python 3.x,Google Bigquery,Mocking,Python Unittest,Python Unittest.mock,我在python文件中有以下代码。我必须对这个文件进行单元测试。但为了做到这一点,我需要实例化类的对象 class BigQuery(metaclass=singleton.Singleton): """ Big Query Class for operations on big query Will standardize in future versions. """ def __init__(self): """ U
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.")
上面的类还包含其他需要测试的方法。如何在不调用BigQueryAPI的情况下模拟每个方法的对象???我让它工作起来了。基本上,您需要模拟对bigquery客户端初始化的函数调用。在
mock.patch
的帮助下,我们可以从\u service\u account\u json模拟客户端对象或函数。下面是代码
with patch.object(bigquery.Client, "from_service_account_json") as srv_acc_mock:
srv_acc_mock.return_value = Mock()
# do something here....
对于GCS客户端,我们也需要遵循相同的模式,但通过导入正确的模块,将bigquery.client
更改为storage.client
。您是否尝试过: