Python 单元测试 Google Bigquery

标签 python unit-testing google-bigquery

我在对以下代码块进行单元测试时遇到问题:

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/

相关文章:

python - 如何将字符串列表中的反向字符串与python中的原始字符串列表进行比较?

python - 如何将图像蒙版叠加到原始图像上但仅显示蒙版边界框?

c# - 使用 NUnit Console Runner 运行一个文件夹下的所有测试

google-bigquery - bq mk -f --view(强制替换现有 View 不起作用)

python - Python3 hashlib 和 Google BigQuery 的 MD5 哈希输出的差异

python - 是否可以在 setup.py 中表达特定于平台的依赖项,而无需构建我的 egg 的特定于平台的版本?

python - 谷歌应用引擎上的二郎?

java - JUnit 测试通过但 PIT 说套件不是绿色的

scala - 如何在 ScalaTest 中使用具有异步规范的夹具上下文对象?

javascript - BIgQuery UDF Javascript可在Web UI中使用,但不能嵌入