Skip to content
Permalink
Browse files
feat: add context manager support to client (#540)
  • Loading branch information
plamut committed Mar 9, 2021
1 parent 816934b commit d5c7e11a1dc2a149d74294bfadbae62d70573e69
Showing with 28 additions and 0 deletions.
  1. +6 −0 google/cloud/bigquery/client.py
  2. +22 −0 tests/unit/test_client.py
@@ -3423,6 +3423,12 @@ def schema_to_json(self, schema_list, destination):
with open(destination, mode="w") as file_obj:
return self._schema_to_json_file_object(json_schema_list, file_obj)

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self.close()


# pylint: disable=unused-argument
def _item_to_project(iterator, resource):
@@ -7218,6 +7218,28 @@ def test_list_rows_error(self):
with self.assertRaises(TypeError):
client.list_rows(1)

def test_context_manager_enter_returns_itself(self):
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)

with mock.patch.object(client, "close"), client as context_var:
pass

self.assertIs(client, context_var)

def test_context_manager_exit_closes_client(self):
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)

fake_close = mock.Mock()
with mock.patch.object(client, "close", fake_close):
with client:
pass

fake_close.assert_called_once()


class Test_make_job_id(unittest.TestCase):
def _call_fut(self, job_id, prefix=None):

0 comments on commit d5c7e11

Please sign in to comment.