Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add context manager support to client #540

Merged
merged 1 commit into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions google/cloud/bigquery/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down