I am having trouble in unit testing the following code block:
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
I am new to mocking and I have tried the following test:
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
Can anybody mock the google stuff and write a unit test please?
Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.
Query data in a notebook using the BigQuery client library directly. In this section, you use the BigQuery client library for Python directly to read data into the Python notebook. The client library gives you more control over your queries and lets you use more complex configurations for queries and jobs.
Unit tests in BigQuery (standard) SQL Create BigQuery object (dataset, table, UDF) to meet some business requirement. Create a SQL unit test to check the object. Run SQL unit test to check the object does the job or not. If the test is passed then move on to the next SQL unit test.
This is how you mock google.cloud.bigquery with pytest, pytest-mock
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With