我在对以下代码块进行单元测试时遇到问题:
from google.cloud import bigquery
from google.oauth2 import service_account
def run_query(query, gcp_ser_acc):
credentials =
service_account.Credentials.from_service_account_info(gcp_ser_acc)
client = bigquery.Client(gcp_ser_acc['project_id'], credentials)
query_job = client.query(query)
results = query_job.result()
return results
我是模拟新手,我尝试过以下测试:
def test_run_a_query_with_real_key(self):
gcp_ser_acc = {
'project_id': 'my_project_id',
'private_key': 'my_private_key',
'token_uri': 'my_token_uri',
'client_email': 'my_client_email'
}
with mock.patch('service_account.Credentials', call_args=gcp_ser_acc, return_value={}):
with mock.patch('bigquery.Client', call_args=(gcp_ser_acc['project_id'], {}), return_value={}):
run_query('SELECT 1+1 as col', gcp_ser_acc)
assert service_account.Credentials.called
assert bigquery.Client.called
任何人都可以模拟谷歌的东西并编写一个单元测试吗?
最佳答案
这就是使用 pytest、pytest-mock 模拟 google.cloud.bigquery 的方式
from google.cloud import bigquery
schema = [
bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
]
def some_query(table_name='blahblahbloo'):
client = bigquery.Client()
table_id = f"project.dataset.{table_name}"
table = bigquery.Table(table_id, schema=schema)
table = client.create_table(table)
def test_some_query(mocker):
mock_table = mocker.patch('google.cloud.bigquery.Table', autospec=True)
mock_client = mocker.patch('google.cloud.bigquery.Client', autospec=True)
some_query() # run with mocked objects
mock_table.assert_called_with('project.dataset.blahblahbloo', schema=schema)
mock_client().create_table.assert_called_with(mock_table.return_value)
关于Python 单元测试 Google Bigquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700181/