如何使用Python 3.7模拟Google API库以进行单元测试 [英] How to Mock a Google API Library with Python 3.7 for Unit Testing
问题描述
我正在尝试创建一组单元测试来测试Bigquery的Google客户端库.我正在努力制作一个Unittest文件,它将模拟客户端,并让我测试我的输入.我提供了带有一些设置功能的简单脚本,以返回属于DataSet的表的列表.
I'm trying to create a set of Unit Tests to test the Google Client Library for Bigquery. I'm struggling to make a Unittest file which will mock the client and will let me test my inputs. I've provided a simple script with some set functionality to return a list of Tables that belong to the DataSet.
Would somebody show me a sample example of mocking the Google Client Library as the documentation I have found @ https://github.com/googleapis/google-cloud-python/blob/master/bigquery/tests/unit/test_client.py is not directly interacting with the methods of the code, so I am unable to apply it to my code.
赞赏实现这一点的任何想法或方法,我似乎在Stack Overflow上找不到记录该问题的任何地方.
Appreciate any ideas or ways to achieve this, I can't seem to find anywhere on Stack Overflow documenting this problem.
谢谢
from google.cloud import bigquery
def get_dataset():
client = bigquery.Client.from_service_account_json('some_client_secret.json')
dataset_id = 'some_project.some_dataset'
dataset = client.get_dataset(dataset_id)
full_dataset_id = "{}.{}".format(dataset.project, dataset.dataset_id)
friendly_name = dataset.friendly_name
print(
"Got dataset '{}' with friendly_name '{}'.".format(
full_dataset_id, friendly_name
)
)
# View dataset properties
print("Description: {}".format(dataset.description))
print("Labels:")
labels = dataset.labels
if labels:
for label, value in labels.items():
print("\t{}: {}".format(label, value))
else:
print("\tDataset has no labels defined.")
# View tables in dataset
print("Tables:")
tables = list(client.list_tables(dataset)) # API request(s)
if tables:
for table in tables:
print("\t{}".format(table.table_id))
else:
print("\tThis dataset does not contain any tables.")
推荐答案
我还发现很难绕过身份验证部分,而且只能模拟与方法的交互,因此我最终只模拟了整个库. :facepalm:
I also find it hard to get around the authentication part and only mock interacting with methods, so I ended up just mocked the whole library. :facepalm:
import sys
from unittest.mock import MagicMock
sys.modules["google.cloud.storage"] = MagicMock()
from your_application import make_app
def test_make_app():
make_app()
这篇关于如何使用Python 3.7模拟Google API库以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!