diff --git a/bigquery/unit_tests/test__helpers.py b/bigquery/unit_tests/test__helpers.py index ec84ccbf6950..e42d8207b471 100644 --- a/bigquery/unit_tests/test__helpers.py +++ b/bigquery/unit_tests/test__helpers.py @@ -19,6 +19,7 @@ class Test_not_null(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _not_null + return _not_null(value, field) def test_w_none_nullable(self): @@ -35,6 +36,7 @@ class Test_int_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _int_from_json + return _int_from_json(value, field) def test_w_none_nullable(self): @@ -57,6 +59,7 @@ class Test_float_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _float_from_json + return _float_from_json(value, field) def test_w_none_nullable(self): @@ -79,6 +82,7 @@ class Test_bool_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _bool_from_json + return _bool_from_json(value, field) def test_w_none_nullable(self): @@ -109,6 +113,7 @@ class Test_string_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _string_from_json + return _string_from_json(value, field) def test_w_none_nullable(self): @@ -126,6 +131,7 @@ class Test_bytes_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _bytes_from_json + return _bytes_from_json(value, field) def test_w_none_nullable(self): @@ -137,6 +143,7 @@ def test_w_none_required(self): def test_w_base64_encoded_bytes(self): import base64 + expected = b'Wonderful!' encoded = base64.encodestring(expected) coerced = self._call_fut(encoded, object()) @@ -144,6 +151,7 @@ def test_w_base64_encoded_bytes(self): def test_w_base64_encoded_text(self): import base64 + expected = b'Wonderful!' encoded = base64.encodestring(expected).decode('ascii') coerced = self._call_fut(encoded, object()) @@ -154,6 +162,7 @@ class Test_timestamp_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _timestamp_from_json + return _timestamp_from_json(value, field) def test_w_none_nullable(self): @@ -166,6 +175,7 @@ def test_w_none_required(self): def test_w_string_value(self): import datetime from google.cloud._helpers import _EPOCH + coerced = self._call_fut('1.234567', object()) self.assertEqual( coerced, @@ -174,6 +184,7 @@ def test_w_string_value(self): def test_w_float_value(self): import datetime from google.cloud._helpers import _EPOCH + coerced = self._call_fut(1.234567, object()) self.assertEqual( coerced, @@ -184,6 +195,7 @@ class Test_datetime_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _datetime_from_json + return _datetime_from_json(value, field) def test_w_none_nullable(self): @@ -195,6 +207,7 @@ def test_w_none_required(self): def test_w_string_value(self): import datetime + coerced = self._call_fut('2016-12-02T18:51:33', object()) self.assertEqual( coerced, @@ -205,6 +218,7 @@ class Test_date_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _date_from_json + return _date_from_json(value, field) def test_w_none_nullable(self): @@ -216,6 +230,7 @@ def test_w_none_required(self): def test_w_string_value(self): import datetime + coerced = self._call_fut('1987-09-22', object()) self.assertEqual( coerced, @@ -226,6 +241,7 @@ class Test_time_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _time_from_json + return _time_from_json(value, field) def test_w_none_nullable(self): @@ -237,6 +253,7 @@ def test_w_none_required(self): def test_w_string_value(self): import datetime + coerced = self._call_fut('12:12:27', object()) self.assertEqual( coerced, @@ -247,6 +264,7 @@ class Test_record_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _record_from_json + return _record_from_json(value, field) def test_w_none_nullable(self): @@ -308,6 +326,7 @@ class Test_row_from_json(unittest.TestCase): def _call_fut(self, row, schema): from google.cloud.bigquery._helpers import _row_from_json + return _row_from_json(row, schema) def test_w_single_scalar_column(self): @@ -399,6 +418,7 @@ class Test_rows_from_json(unittest.TestCase): def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _rows_from_json + return _rows_from_json(value, field) def test_w_record_subfield(self): @@ -485,6 +505,7 @@ class Test_int_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _int_to_json + return _int_to_json(value) def test_w_int(self): @@ -498,6 +519,7 @@ class Test_float_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _float_to_json + return _float_to_json(value) def test_w_float(self): @@ -508,6 +530,7 @@ class Test_bool_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _bool_to_json + return _bool_to_json(value) def test_w_true(self): @@ -524,6 +547,7 @@ class Test_bytes_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _bytes_to_json + return _bytes_to_json(value) def test_w_non_bytes(self): @@ -541,6 +565,7 @@ class Test_timestamp_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _timestamp_to_json + return _timestamp_to_json(value) def test_w_float(self): @@ -552,6 +577,7 @@ def test_w_string(self): def test_w_datetime_wo_zone(self): import datetime + ZULU = '2016-12-20 15:58:27.339328+00:00' when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328) self.assertEqual(self._call_fut(when), ZULU) @@ -572,6 +598,7 @@ def utcoffset(self, _): def test_w_datetime_w_utc_zone(self): import datetime from google.cloud._helpers import UTC + ZULU = '2016-12-20 15:58:27.339328+00:00' when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC) self.assertEqual(self._call_fut(when), ZULU) @@ -581,6 +608,7 @@ class Test_datetime_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _datetime_to_json + return _datetime_to_json(value) def test_w_string(self): @@ -590,6 +618,7 @@ def test_w_string(self): def test_w_datetime(self): import datetime from google.cloud._helpers import UTC + when = datetime.datetime(2016, 12, 3, 14, 11, 27, 123456, tzinfo=UTC) self.assertEqual(self._call_fut(when), '2016-12-03T14:11:27.123456Z') @@ -598,6 +627,7 @@ class Test_date_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _date_to_json + return _date_to_json(value) def test_w_string(self): @@ -606,6 +636,7 @@ def test_w_string(self): def test_w_datetime(self): import datetime + when = datetime.date(2016, 12, 3) self.assertEqual(self._call_fut(when), '2016-12-03') @@ -614,6 +645,7 @@ class Test_time_to_json(unittest.TestCase): def _call_fut(self, value): from google.cloud.bigquery._helpers import _time_to_json + return _time_to_json(value) def test_w_string(self): @@ -622,6 +654,7 @@ def test_w_string(self): def test_w_datetime(self): import datetime + when = datetime.time(12, 13, 41) self.assertEqual(self._call_fut(when), '12:13:41') @@ -631,6 +664,7 @@ class Test_ConfigurationProperty(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import _ConfigurationProperty + return _ConfigurationProperty def _make_one(self, *args, **kw): @@ -667,6 +701,7 @@ class Test_TypedProperty(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import _TypedProperty + return _TypedProperty def _make_one(self, *args, **kw): @@ -701,6 +736,7 @@ class Test_EnumProperty(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import _EnumProperty + return _EnumProperty def test_it(self): @@ -735,6 +771,7 @@ class Test_UDFResourcesProperty(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import UDFResourcesProperty + return UDFResourcesProperty def _make_one(self, *args, **kw): @@ -760,6 +797,7 @@ def test_instance_getter_empty(self): def test_instance_getter_w_non_empty_list(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] _, klass = self._descriptor_and_klass() @@ -770,6 +808,7 @@ def test_instance_getter_w_non_empty_list(self): def test_instance_setter_w_empty_list(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] _, klass = self._descriptor_and_klass() @@ -782,6 +821,7 @@ def test_instance_setter_w_empty_list(self): def test_instance_setter_w_valid_udf(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] _, klass = self._descriptor_and_klass() @@ -806,6 +846,7 @@ class Test_AbstractQueryParameter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import AbstractQueryParameter + return AbstractQueryParameter def _make_one(self, *args, **kw): @@ -827,6 +868,7 @@ class Test_ScalarQueryParameter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import ScalarQueryParameter + return ScalarQueryParameter def _make_one(self, *args, **kw): @@ -931,6 +973,7 @@ def test_to_api_repr_w_bool(self): def test_to_api_repr_w_timestamp_datetime(self): from google.cloud._helpers import UTC import datetime + STAMP = '2016-12-20 15:58:27.339328+00:00' when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC) EXPECTED = { @@ -948,6 +991,7 @@ def test_to_api_repr_w_timestamp_datetime(self): def test_to_api_repr_w_timestamp_micros(self): import datetime from google.cloud._helpers import _microseconds_from_datetime + now = datetime.datetime.utcnow() seconds = _microseconds_from_datetime(now) / 1.0e6 EXPECTED = { @@ -965,6 +1009,7 @@ def test_to_api_repr_w_timestamp_micros(self): def test_to_api_repr_w_datetime_datetime(self): import datetime from google.cloud._helpers import _datetime_to_rfc3339 + now = datetime.datetime.utcnow() EXPECTED = { 'parameterType': { @@ -981,6 +1026,7 @@ def test_to_api_repr_w_datetime_datetime(self): def test_to_api_repr_w_datetime_string(self): import datetime from google.cloud._helpers import _datetime_to_rfc3339 + now = datetime.datetime.utcnow() now_str = _datetime_to_rfc3339(now) EXPECTED = { @@ -997,6 +1043,7 @@ def test_to_api_repr_w_datetime_string(self): def test_to_api_repr_w_date_date(self): import datetime + today = datetime.date.today() EXPECTED = { 'parameterType': { @@ -1012,6 +1059,7 @@ def test_to_api_repr_w_date_date(self): def test_to_api_repr_w_date_string(self): import datetime + today = datetime.date.today() today_str = today.isoformat(), EXPECTED = { @@ -1045,6 +1093,7 @@ class Test_ArrayQueryParameter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import ArrayQueryParameter + return ArrayQueryParameter def _make_one(self, *args, **kw): @@ -1186,6 +1235,7 @@ class Test_StructQueryParameter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import StructQueryParameter + return StructQueryParameter def _make_one(self, *args, **kw): @@ -1194,6 +1244,7 @@ def _make_one(self, *args, **kw): @staticmethod def _make_subparam(name, type_, value): from google.cloud.bigquery._helpers import ScalarQueryParameter + return ScalarQueryParameter(name, type_, value) def test_ctor(self): @@ -1308,6 +1359,7 @@ class Test_QueryParametersProperty(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._helpers import QueryParametersProperty + return QueryParametersProperty def _make_one(self, *args, **kw): @@ -1333,6 +1385,7 @@ def test_instance_getter_empty(self): def test_instance_getter_w_non_empty_list(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter("foo", 'INT64', 123)] _, klass = self._descriptor_and_klass() instance = klass() @@ -1342,6 +1395,7 @@ def test_instance_getter_w_non_empty_list(self): def test_instance_setter_w_empty_list(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter("foo", 'INT64', 123)] _, klass = self._descriptor_and_klass() instance = klass() @@ -1353,6 +1407,7 @@ def test_instance_setter_w_empty_list(self): def test_instance_setter_w_valid_udf(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter("foo", 'INT64', 123)] _, klass = self._descriptor_and_klass() instance = klass() diff --git a/bigquery/unit_tests/test__http.py b/bigquery/unit_tests/test__http.py index 0592b98178cd..6beaa3a8cc4d 100644 --- a/bigquery/unit_tests/test__http.py +++ b/bigquery/unit_tests/test__http.py @@ -20,6 +20,7 @@ class TestConnection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery._http import Connection + return Connection def _make_one(self, *args, **kw): @@ -38,6 +39,7 @@ def test_build_api_url_no_extra_query_params(self): def test_build_api_url_w_extra_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) diff --git a/bigquery/unit_tests/test_client.py b/bigquery/unit_tests/test_client.py index 7442d7ad8b5d..3056c1e2f39d 100644 --- a/bigquery/unit_tests/test_client.py +++ b/bigquery/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -27,6 +28,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery.client import Client + return Client def _make_one(self, *args, **kw): @@ -34,6 +36,7 @@ def _make_one(self, *args, **kw): def test_ctor(self): from google.cloud.bigquery._http import Connection + PROJECT = 'PROJECT' creds = _make_credentials() http = object() @@ -45,6 +48,7 @@ def test_ctor(self): def test_list_projects_defaults(self): import six from google.cloud.bigquery.client import Project + PROJECT_1 = 'PROJECT_ONE' PROJECT_2 = 'PROJECT_TWO' PATH = 'projects' @@ -115,6 +119,7 @@ def test_list_projects_explicit_response_missing_projects_key(self): def test_list_datasets_defaults(self): import six from google.cloud.bigquery.dataset import Dataset + PROJECT = 'PROJECT' DATASET_1 = 'dataset_one' DATASET_2 = 'dataset_two' @@ -185,6 +190,7 @@ def test_list_datasets_explicit_response_missing_datasets_key(self): def test_dataset(self): from google.cloud.bigquery.dataset import Dataset + PROJECT = 'PROJECT' DATASET = 'dataset_name' creds = _make_credentials() @@ -208,6 +214,7 @@ def test_list_jobs_defaults(self): from google.cloud.bigquery.job import CopyJob from google.cloud.bigquery.job import ExtractTableToStorageJob from google.cloud.bigquery.job import QueryJob + PROJECT = 'PROJECT' DATASET = 'test_dataset' SOURCE_TABLE = 'source_table' @@ -336,6 +343,7 @@ def test_list_jobs_defaults(self): def test_list_jobs_load_job_wo_sourceUris(self): import six from google.cloud.bigquery.job import LoadTableFromStorageJob + PROJECT = 'PROJECT' DATASET = 'test_dataset' SOURCE_TABLE = 'source_table' @@ -391,6 +399,7 @@ def test_list_jobs_load_job_wo_sourceUris(self): def test_list_jobs_explicit_missing(self): import six + PROJECT = 'PROJECT' PATH = 'projects/%s/jobs' % PROJECT DATA = {} @@ -421,6 +430,7 @@ def test_list_jobs_explicit_missing(self): def test_load_table_from_storage(self): from google.cloud.bigquery.job import LoadTableFromStorageJob + PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' @@ -440,6 +450,7 @@ def test_load_table_from_storage(self): def test_copy_table(self): from google.cloud.bigquery.job import CopyJob + PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' @@ -460,6 +471,7 @@ def test_copy_table(self): def test_extract_table_to_storage(self): from google.cloud.bigquery.job import ExtractTableToStorageJob + PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' @@ -479,6 +491,7 @@ def test_extract_table_to_storage(self): def test_run_async_query_defaults(self): from google.cloud.bigquery.job import QueryJob + PROJECT = 'PROJECT' JOB = 'job_name' QUERY = 'select count(*) from persons' @@ -496,6 +509,7 @@ def test_run_async_query_defaults(self): def test_run_async_w_udf_resources(self): from google.cloud.bigquery._helpers import UDFResource from google.cloud.bigquery.job import QueryJob + RESOURCE_URI = 'gs://some-bucket/js/lib.js' PROJECT = 'PROJECT' JOB = 'job_name' @@ -515,6 +529,7 @@ def test_run_async_w_udf_resources(self): def test_run_async_w_query_parameters(self): from google.cloud.bigquery._helpers import ScalarQueryParameter from google.cloud.bigquery.job import QueryJob + PROJECT = 'PROJECT' JOB = 'job_name' QUERY = 'select count(*) from persons' @@ -533,6 +548,7 @@ def test_run_async_w_query_parameters(self): def test_run_sync_query_defaults(self): from google.cloud.bigquery.query import QueryResults + PROJECT = 'PROJECT' QUERY = 'select count(*) from persons' creds = _make_credentials() @@ -549,6 +565,7 @@ def test_run_sync_query_defaults(self): def test_run_sync_query_w_udf_resources(self): from google.cloud.bigquery._helpers import UDFResource from google.cloud.bigquery.query import QueryResults + RESOURCE_URI = 'gs://some-bucket/js/lib.js' PROJECT = 'PROJECT' QUERY = 'select count(*) from persons' @@ -567,6 +584,7 @@ def test_run_sync_query_w_udf_resources(self): def test_run_sync_query_w_query_parameters(self): from google.cloud.bigquery._helpers import ScalarQueryParameter from google.cloud.bigquery.query import QueryResults + PROJECT = 'PROJECT' QUERY = 'select count(*) from persons' creds = _make_credentials() diff --git a/bigquery/unit_tests/test_dataset.py b/bigquery/unit_tests/test_dataset.py index 015b160687d9..ad510dded5ea 100644 --- a/bigquery/unit_tests/test_dataset.py +++ b/bigquery/unit_tests/test_dataset.py @@ -20,6 +20,7 @@ class TestAccessGrant(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery.dataset import AccessGrant + return AccessGrant def _make_one(self, *args, **kw): @@ -84,6 +85,7 @@ class TestDataset(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery.dataset import Dataset + return Dataset def _make_one(self, *args, **kw): @@ -198,6 +200,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): from google.cloud.bigquery.dataset import AccessGrant + phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com') bharney = AccessGrant('OWNER', 'userByEmail', 'bharney@example.com') grants = [phred, bharney] @@ -233,6 +236,7 @@ def test_access_grants_setter_non_list(self): def test_access_grants_setter_invalid_field(self): from google.cloud.bigquery.dataset import AccessGrant + client = _Client(self.PROJECT) dataset = self._make_one(self.DS_NAME, client) phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com') @@ -241,6 +245,7 @@ def test_access_grants_setter_invalid_field(self): def test_access_grants_setter(self): from google.cloud.bigquery.dataset import AccessGrant + client = _Client(self.PROJECT) dataset = self._make_one(self.DS_NAME, client) phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com') @@ -372,6 +377,7 @@ def test_create_w_bound_client(self): def test_create_w_alternate_client(self): from google.cloud.bigquery.dataset import AccessGrant + PATH = 'projects/%s/datasets' % self.PROJECT USER_EMAIL = 'phred@example.com' GROUP_EMAIL = 'group-name@lists.example.com' @@ -786,6 +792,7 @@ def test_list_tables_explicit(self): def test_table_wo_schema(self): from google.cloud.bigquery.table import Table + conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) dataset = self._make_one(self.DS_NAME, client=client) @@ -798,6 +805,7 @@ def test_table_wo_schema(self): def test_table_w_schema(self): from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Table + conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) dataset = self._make_one(self.DS_NAME, client=client) @@ -825,6 +833,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: diff --git a/bigquery/unit_tests/test_job.py b/bigquery/unit_tests/test_job.py index 57b588a5801c..e0176d6a456b 100644 --- a/bigquery/unit_tests/test_job.py +++ b/bigquery/unit_tests/test_job.py @@ -125,6 +125,7 @@ class TestLoadTableFromStorageJob(unittest.TestCase, _Base): @staticmethod def _get_target_class(): from google.cloud.bigquery.job import LoadTableFromStorageJob + return LoadTableFromStorageJob def _setUpConstants(self): @@ -264,6 +265,7 @@ def test_ctor(self): def test_ctor_w_schema(self): from google.cloud.bigquery.schema import SchemaField + client = _Client(self.PROJECT) table = _Table() full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') @@ -281,6 +283,7 @@ def test_schema_setter_non_list(self): def test_schema_setter_invalid_field(self): from google.cloud.bigquery.schema import SchemaField + client = _Client(self.PROJECT) table = _Table() job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) @@ -290,6 +293,7 @@ def test_schema_setter_invalid_field(self): def test_schema_setter(self): from google.cloud.bigquery.schema import SchemaField + client = _Client(self.PROJECT) table = _Table() job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) @@ -465,6 +469,7 @@ def test_begin_w_bound_client(self): def test_begin_w_alternate_client(self): from google.cloud.bigquery.schema import SchemaField + PATH = '/projects/%s/jobs' % (self.PROJECT,) RESOURCE = self._makeResource(ended=True) LOAD_CONFIGURATION = { @@ -646,6 +651,7 @@ class TestCopyJob(unittest.TestCase, _Base): @staticmethod def _get_target_class(): from google.cloud.bigquery.job import CopyJob + return CopyJob def _makeResource(self, started=False, ended=False): @@ -998,6 +1004,7 @@ class TestExtractTableToStorageJob(unittest.TestCase, _Base): @staticmethod def _get_target_class(): from google.cloud.bigquery.job import ExtractTableToStorageJob + return ExtractTableToStorageJob def _makeResource(self, started=False, ended=False): @@ -1292,6 +1299,7 @@ class TestQueryJob(unittest.TestCase, _Base): @staticmethod def _get_target_class(): from google.cloud.bigquery.job import QueryJob + return QueryJob def _makeResource(self, started=False, ended=False): @@ -1431,6 +1439,7 @@ def test_ctor_defaults(self): def test_ctor_w_udf_resources(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] client = _Client(self.PROJECT) @@ -1440,6 +1449,7 @@ def test_ctor_w_udf_resources(self): def test_ctor_w_query_parameters(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter("foo", 'INT64', 123)] client = _Client(self.PROJECT) job = self._make_one(self.JOB_NAME, self.QUERY, client, @@ -1501,6 +1511,7 @@ def test_from_api_repr_w_properties(self): def test_results(self): from google.cloud.bigquery.query import QueryResults + client = _Client(self.PROJECT) job = self._make_one(self.JOB_NAME, self.QUERY, client) results = job.results() @@ -1542,6 +1553,7 @@ def test_begin_w_bound_client(self): def test_begin_w_alternate_client(self): from google.cloud.bigquery.dataset import Dataset from google.cloud.bigquery.dataset import Table + PATH = '/projects/%s/jobs' % (self.PROJECT,) TABLE = 'TABLE' DS_NAME = 'DATASET' @@ -1612,6 +1624,7 @@ def test_begin_w_alternate_client(self): def test_begin_w_udf(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' INLINE_UDF_CODE = 'var someCode = "here";' PATH = '/projects/%s/jobs' % (self.PROJECT,) @@ -1661,6 +1674,7 @@ def test_begin_w_udf(self): def test_begin_w_named_query_parameter(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter('foo', 'INT64', 123)] PATH = '/projects/%s/jobs' % (self.PROJECT,) RESOURCE = self._makeResource() @@ -1712,6 +1726,7 @@ def test_begin_w_named_query_parameter(self): def test_begin_w_positional_query_parameter(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter.positional('INT64', 123)] PATH = '/projects/%s/jobs' % (self.PROJECT,) RESOURCE = self._makeResource() @@ -1794,6 +1809,7 @@ def test_exists_hit_w_alternate_client(self): def test_reload_w_bound_client(self): from google.cloud.bigquery.dataset import Dataset from google.cloud.bigquery.dataset import Table + PATH = '/projects/%s/jobs/%s' % (self.PROJECT, self.JOB_NAME) DS_NAME = 'DATASET' DEST_TABLE = 'dest_table' @@ -1851,6 +1867,7 @@ def __init__(self, project='project', connection=None): def dataset(self, name): from google.cloud.bigquery.dataset import Dataset + return Dataset(name, client=self) @@ -1882,6 +1899,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: diff --git a/bigquery/unit_tests/test_query.py b/bigquery/unit_tests/test_query.py index fa8dd401e435..0e388c3cd0d9 100644 --- a/bigquery/unit_tests/test_query.py +++ b/bigquery/unit_tests/test_query.py @@ -26,6 +26,7 @@ class TestQueryResults(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery.query import QueryResults + return QueryResults def _make_one(self, *args, **kw): @@ -75,6 +76,7 @@ def _makeResource(self, complete=False): def _verifySchema(self, query, resource): from google.cloud.bigquery.schema import SchemaField + if 'schema' in resource: fields = resource['schema']['fields'] self.assertEqual(len(query.schema), len(fields)) @@ -162,6 +164,7 @@ def test_ctor_defaults(self): def test_ctor_w_udf_resources(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] client = _Client(self.PROJECT) @@ -170,6 +173,7 @@ def test_ctor_w_udf_resources(self): def test_ctor_w_query_parameters(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + query_parameters = [ScalarQueryParameter("foo", 'INT64', 123)] client = _Client(self.PROJECT) query = self._make_one(self.QUERY, client, @@ -180,6 +184,7 @@ def test_from_query_job(self): from google.cloud.bigquery.dataset import Dataset from google.cloud.bigquery.job import QueryJob from google.cloud.bigquery._helpers import UDFResource + DS_NAME = 'DATASET' RESOURCE_URI = 'gs://some-bucket/js/lib.js' client = _Client(self.PROJECT) @@ -205,6 +210,7 @@ def test_from_query_job(self): def test_from_query_job_wo_default_dataset(self): from google.cloud.bigquery.job import QueryJob from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' client = _Client(self.PROJECT) job = QueryJob( @@ -229,6 +235,7 @@ def test_job_wo_jobid(self): def test_job_w_jobid(self): from google.cloud.bigquery.job import QueryJob + SERVER_GENERATED = 'SERVER_GENERATED' client = _Client(self.PROJECT) query = self._make_one(self.QUERY, client) @@ -327,6 +334,7 @@ def test_run_w_alternate_client(self): def test_run_w_inline_udf(self): from google.cloud.bigquery._helpers import UDFResource + INLINE_UDF_CODE = 'var someCode = "here";' PATH = 'projects/%s/queries' % self.PROJECT RESOURCE = self._makeResource(complete=False) @@ -352,6 +360,7 @@ def test_run_w_inline_udf(self): def test_run_w_udf_resource_uri(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' PATH = 'projects/%s/queries' % self.PROJECT RESOURCE = self._makeResource(complete=False) @@ -377,6 +386,7 @@ def test_run_w_udf_resource_uri(self): def test_run_w_mixed_udfs(self): from google.cloud.bigquery._helpers import UDFResource + RESOURCE_URI = 'gs://some-bucket/js/lib.js' INLINE_UDF_CODE = 'var someCode = "here";' PATH = 'projects/%s/queries' % self.PROJECT @@ -409,6 +419,7 @@ def test_run_w_mixed_udfs(self): def test_run_w_named_query_paramter(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + PATH = 'projects/%s/queries' % self.PROJECT RESOURCE = self._makeResource(complete=False) RESOURCE['parameterMode'] = 'NAMED' @@ -444,6 +455,7 @@ def test_run_w_named_query_paramter(self): def test_run_w_positional_query_paramter(self): from google.cloud.bigquery._helpers import ScalarQueryParameter + PATH = 'projects/%s/queries' % self.PROJECT RESOURCE = self._makeResource(complete=False) RESOURCE['parameterMode'] = 'POSITIONAL' @@ -560,6 +572,7 @@ def __init__(self, project='project', connection=None): def dataset(self, name): from google.cloud.bigquery.dataset import Dataset + return Dataset(name, client=self) diff --git a/bigquery/unit_tests/test_schema.py b/bigquery/unit_tests/test_schema.py index 8b49bff5b29a..8081fcd6f4e0 100644 --- a/bigquery/unit_tests/test_schema.py +++ b/bigquery/unit_tests/test_schema.py @@ -20,6 +20,7 @@ class TestSchemaField(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigquery.schema import SchemaField + return SchemaField def _make_one(self, *args, **kw): diff --git a/bigquery/unit_tests/test_table.py b/bigquery/unit_tests/test_table.py index 0b8453103082..57fcb4a4800c 100644 --- a/bigquery/unit_tests/test_table.py +++ b/bigquery/unit_tests/test_table.py @@ -38,6 +38,7 @@ class TestTable(unittest.TestCase, _SchemaBase): @staticmethod def _get_target_class(): from google.cloud.bigquery.table import Table + return Table def _make_one(self, *args, **kw): @@ -162,6 +163,7 @@ def test_ctor(self): def test_ctor_w_schema(self): from google.cloud.bigquery.table import SchemaField + client = _Client(self.PROJECT) dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') @@ -223,6 +225,7 @@ def test_schema_setter_non_list(self): def test_schema_setter_invalid_field(self): from google.cloud.bigquery.table import SchemaField + client = _Client(self.PROJECT) dataset = _Dataset(client) table = self._make_one(self.TABLE_NAME, dataset) @@ -232,6 +235,7 @@ def test_schema_setter_invalid_field(self): def test_schema_setter(self): from google.cloud.bigquery.table import SchemaField + client = _Client(self.PROJECT) dataset = _Dataset(client) table = self._make_one(self.TABLE_NAME, dataset) @@ -402,6 +406,7 @@ def test_create_no_view_query_no_schema(self): def test_create_w_bound_client(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME) RESOURCE = self._makeResource() conn = _Connection(RESOURCE) @@ -432,6 +437,7 @@ def test_create_w_bound_client(self): def test_create_w_partition_no_expire(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME) RESOURCE = self._makeResource() conn = _Connection(RESOURCE) @@ -466,6 +472,7 @@ def test_create_w_partition_no_expire(self): def test_create_w_partition_and_expire(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME) RESOURCE = self._makeResource() conn = _Connection(RESOURCE) @@ -500,6 +507,7 @@ def test_create_w_partition_and_expire(self): def test_partition_type_setter_bad_type(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -513,6 +521,7 @@ def test_partition_type_setter_bad_type(self): def test_partition_type_setter_unknown_value(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -526,6 +535,7 @@ def test_partition_type_setter_unknown_value(self): def test_partition_type_setter_w_known_value(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -540,6 +550,7 @@ def test_partition_type_setter_w_known_value(self): def test_partition_type_setter_w_none(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -555,6 +566,7 @@ def test_partition_type_setter_w_none(self): def test_partition_experation_bad_type(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -568,6 +580,7 @@ def test_partition_experation_bad_type(self): def test_partition_expiration_w_integer(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -583,6 +596,7 @@ def test_partition_expiration_w_integer(self): def test_partition_expiration_w_none(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -602,6 +616,7 @@ def test_partition_expiration_w_none(self): def test_partition_expiration_w_none_no_partition_set(self): from google.cloud.bigquery.table import SchemaField + RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) @@ -617,6 +632,7 @@ def test_partition_expiration_w_none_no_partition_set(self): def test_list_partitions(self): from google.cloud.bigquery.table import SchemaField + conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) client._query_results = [(20160804, None), (20160805, None)] @@ -682,6 +698,7 @@ def test_create_w_missing_output_properties(self): # In the wild, the resource returned from 'dataset.create' sometimes # lacks 'creationTime' / 'lastModifiedTime' from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME) RESOURCE = self._makeResource() del RESOURCE['creationTime'] @@ -896,6 +913,7 @@ def test_patch_w_schema_None(self): def test_update_w_bound_client(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables/%s' % ( self.PROJECT, self.DS_NAME, self.TABLE_NAME) DESCRIPTION = 'DESCRIPTION' @@ -1278,6 +1296,7 @@ def test_fetch_data_w_record_schema(self): def test_insert_data_wo_schema(self): from google.cloud.bigquery.table import _TABLE_HAS_NO_SCHEMA + client = _Client(project=self.PROJECT) dataset = _Dataset(client) table = self._make_one(self.TABLE_NAME, dataset=dataset) @@ -1343,6 +1362,7 @@ def _row_data(row): def test_insert_data_w_alternate_client(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % ( self.PROJECT, self.DS_NAME, self.TABLE_NAME) RESPONSE = { @@ -1407,6 +1427,7 @@ def _row_data(row): def test_insert_data_w_repeated_fields(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % ( self.PROJECT, self.DS_NAME, self.TABLE_NAME) conn = _Connection({}) @@ -1442,6 +1463,7 @@ def _row_data(row): def test_insert_data_w_record_schema(self): from google.cloud.bigquery.table import SchemaField + PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % ( self.PROJECT, self.DS_NAME, self.TABLE_NAME) conn = _Connection({}) @@ -1651,6 +1673,7 @@ def test_upload_from_file_resumable_with_400(self): from google.cloud.exceptions import BadRequest from google.cloud._helpers import UTC from google.cloud._testing import _NamedTemporaryFile + WHEN_TS = 1437767599.006 WHEN = datetime.datetime.utcfromtimestamp(WHEN_TS).replace( tzinfo=UTC) @@ -1776,6 +1799,7 @@ class Test_parse_schema_resource(unittest.TestCase, _SchemaBase): def _call_fut(self, resource): from google.cloud.bigquery.table import _parse_schema_resource + return _parse_schema_resource(resource) def _makeResource(self): @@ -1820,10 +1844,12 @@ class Test_build_schema_resource(unittest.TestCase, _SchemaBase): def _call_fut(self, resource): from google.cloud.bigquery.table import _build_schema_resource + return _build_schema_resource(resource) def test_defaults(self): from google.cloud.bigquery.table import SchemaField + full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') resource = self._call_fut([full_name, age]) @@ -1839,6 +1865,7 @@ def test_defaults(self): def test_w_description(self): from google.cloud.bigquery.table import SchemaField + DESCRIPTION = 'DESCRIPTION' full_name = SchemaField('full_name', 'STRING', mode='REQUIRED', description=DESCRIPTION) @@ -1857,6 +1884,7 @@ def test_w_description(self): def test_w_subfields(self): from google.cloud.bigquery.table import SchemaField + full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') ph_type = SchemaField('type', 'STRING', 'REQUIRED') ph_num = SchemaField('number', 'STRING', 'REQUIRED') @@ -1956,6 +1984,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: @@ -1970,6 +1999,7 @@ def build_api_url(self, path, query_params=None, from six.moves.urllib.parse import urlencode from six.moves.urllib.parse import urlsplit from six.moves.urllib.parse import urlunsplit + # Mimic the build_api_url interface. qs = urlencode(query_params or {}) scheme, netloc, _, _, _ = urlsplit(api_base_url) @@ -1978,11 +2008,14 @@ def build_api_url(self, path, query_params=None, def _email_chunk_parser(): import six + if six.PY3: # pragma: NO COVER Python3 from email.parser import BytesParser + parser = BytesParser() return parser.parsebytes else: from email.parser import Parser + parser = Parser() return parser.parsestr diff --git a/bigtable/unit_tests/test_client.py b/bigtable/unit_tests/test_client.py index 24fee441a6c9..b7b666e819df 100644 --- a/bigtable/unit_tests/test_client.py +++ b/bigtable/unit_tests/test_client.py @@ -33,6 +33,7 @@ class Test__make_data_stub(unittest.TestCase): def _call_fut(self, client): from google.cloud.bigtable.client import _make_data_stub + return _make_data_stub(client) def test_without_emulator(self): @@ -99,6 +100,7 @@ class Test__make_instance_stub(unittest.TestCase): def _call_fut(self, client): from google.cloud.bigtable.client import _make_instance_stub + return _make_instance_stub(client) def test_without_emulator(self): @@ -159,6 +161,7 @@ class Test__make_operations_stub(unittest.TestCase): def _call_fut(self, client): from google.cloud.bigtable.client import _make_operations_stub + return _make_operations_stub(client) def test_without_emulator(self): @@ -223,6 +226,7 @@ class Test__make_table_stub(unittest.TestCase): def _call_fut(self, client): from google.cloud.bigtable.client import _make_table_stub + return _make_table_stub(client) def test_without_emulator(self): @@ -289,6 +293,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.client import Client + return Client def _make_one(self, *args, **kwargs): diff --git a/bigtable/unit_tests/test_cluster.py b/bigtable/unit_tests/test_cluster.py index 9730d9b5ab44..9472fde29f59 100644 --- a/bigtable/unit_tests/test_cluster.py +++ b/bigtable/unit_tests/test_cluster.py @@ -28,6 +28,7 @@ class TestCluster(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.cluster import Cluster + return Cluster def _make_one(self, *args, **kwargs): @@ -35,6 +36,7 @@ def _make_one(self, *args, **kwargs): def test_constructor_defaults(self): from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES + client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) @@ -376,6 +378,7 @@ class Test__prepare_create_request(unittest.TestCase): def _call_fut(self, cluster): from google.cloud.bigtable.cluster import _prepare_create_request + return _prepare_create_request(cluster) def test_it(self): @@ -401,18 +404,21 @@ def test_it(self): def _ClusterPB(*args, **kw): from google.cloud.bigtable._generated import ( instance_pb2 as instance_v2_pb2) + return instance_v2_pb2.Cluster(*args, **kw) def _DeleteClusterRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_instance_admin_pb2 as messages_v2_pb2) + return messages_v2_pb2.DeleteClusterRequest(*args, **kw) def _GetClusterRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_instance_admin_pb2 as messages_v2_pb2) + return messages_v2_pb2.GetClusterRequest(*args, **kw) diff --git a/bigtable/unit_tests/test_column_family.py b/bigtable/unit_tests/test_column_family.py index 90baf9193691..36f4c99c0032 100644 --- a/bigtable/unit_tests/test_column_family.py +++ b/bigtable/unit_tests/test_column_family.py @@ -21,6 +21,7 @@ class Test__timedelta_to_duration_pb(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud.bigtable.column_family import ( _timedelta_to_duration_pb) + return _timedelta_to_duration_pb(*args, **kwargs) def test_it(self): @@ -67,6 +68,7 @@ class Test__duration_pb_to_timedelta(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud.bigtable.column_family import ( _duration_pb_to_timedelta) + return _duration_pb_to_timedelta(*args, **kwargs) def test_it(self): @@ -88,6 +90,7 @@ class TestMaxVersionsGCRule(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.column_family import MaxVersionsGCRule + return MaxVersionsGCRule def _make_one(self, *args, **kwargs): @@ -122,6 +125,7 @@ class TestMaxAgeGCRule(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.column_family import MaxAgeGCRule + return MaxAgeGCRule def _make_one(self, *args, **kwargs): @@ -162,6 +166,7 @@ class TestGCRuleUnion(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.column_family import GCRuleUnion + return GCRuleUnion def _make_one(self, *args, **kwargs): @@ -249,6 +254,7 @@ class TestGCRuleIntersection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.column_family import GCRuleIntersection + return GCRuleIntersection def _make_one(self, *args, **kwargs): @@ -339,6 +345,7 @@ class TestColumnFamily(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.column_family import ColumnFamily + return ColumnFamily def _make_one(self, *args, **kwargs): @@ -466,6 +473,7 @@ def test_create(self): def test_create_with_gc_rule(self): from google.cloud.bigtable.column_family import MaxVersionsGCRule + gc_rule = MaxVersionsGCRule(1337) self._create_test_helper(gc_rule=gc_rule) @@ -524,6 +532,7 @@ def test_update(self): def test_update_with_gc_rule(self): from google.cloud.bigtable.column_family import MaxVersionsGCRule + gc_rule = MaxVersionsGCRule(1337) self._update_test_helper(gc_rule=gc_rule) @@ -577,6 +586,7 @@ class Test__gc_rule_from_pb(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud.bigtable.column_family import _gc_rule_from_pb + return _gc_rule_from_pb(*args, **kwargs) def test_empty(self): @@ -649,24 +659,28 @@ def WhichOneof(cls, name): def _GcRulePB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.GcRule(*args, **kw) def _GcRuleIntersectionPB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.GcRule.Intersection(*args, **kw) def _GcRuleUnionPB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.GcRule.Union(*args, **kw) def _ColumnFamilyPB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.ColumnFamily(*args, **kw) diff --git a/bigtable/unit_tests/test_instance.py b/bigtable/unit_tests/test_instance.py index 84bc0e6346ea..c243ca77a135 100644 --- a/bigtable/unit_tests/test_instance.py +++ b/bigtable/unit_tests/test_instance.py @@ -33,6 +33,7 @@ class TestInstance(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.instance import Instance + return Instance def _make_one(self, *args, **kwargs): @@ -516,6 +517,7 @@ class Test__prepare_create_request(unittest.TestCase): def _call_fut(self, instance, **kw): from google.cloud.bigtable.instance import _prepare_create_request + return _prepare_create_request(instance, **kw) def test_w_defaults(self): @@ -551,6 +553,7 @@ def test_w_explicit_serve_nodes(self): from google.cloud.bigtable._generated import ( bigtable_instance_admin_pb2 as messages_v2_pb) from google.cloud.bigtable.instance import Instance + DISPLAY_NAME = u'DISPLAY_NAME' SERVE_NODES = 5 client = _Client(self.PROJECT) @@ -582,6 +585,7 @@ def __init__(self, project): def copy(self): from copy import deepcopy + return deepcopy(self) def __eq__(self, other): diff --git a/bigtable/unit_tests/test_row.py b/bigtable/unit_tests/test_row.py index c3321a12eec1..60d53d5ccdf6 100644 --- a/bigtable/unit_tests/test_row.py +++ b/bigtable/unit_tests/test_row.py @@ -21,6 +21,7 @@ class Test_SetDeleteRow(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row import _SetDeleteRow + return _SetDeleteRow def _make_one(self, *args, **kwargs): @@ -37,6 +38,7 @@ class TestDirectRow(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row import DirectRow + return DirectRow def _make_one(self, *args, **kwargs): @@ -77,6 +79,7 @@ def _set_cell_helper(self, column=None, column_bytes=None, timestamp_micros=-1): import six import struct + row_key = b'row_key' column_family_id = u'column_family_id' if column is None: @@ -381,6 +384,7 @@ class TestConditionalRow(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row import ConditionalRow + return ConditionalRow def _make_one(self, *args, **kwargs): @@ -523,6 +527,7 @@ class TestAppendRow(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row import AppendRow + return AppendRow def _make_one(self, *args, **kwargs): @@ -667,10 +672,12 @@ class Test__parse_rmw_row_response(unittest.TestCase): def _call_fut(self, row_response): from google.cloud.bigtable.row import _parse_rmw_row_response + return _parse_rmw_row_response(row_response) def test_it(self): from google.cloud._helpers import _datetime_from_microseconds + col_fam1 = u'col-fam-id' col_fam2 = u'col-fam-id2' col_name1 = b'col-name1' @@ -752,10 +759,12 @@ class Test__parse_family_pb(unittest.TestCase): def _call_fut(self, family_pb): from google.cloud.bigtable.row import _parse_family_pb + return _parse_family_pb(family_pb) def test_it(self): from google.cloud._helpers import _datetime_from_microseconds + col_fam1 = u'col-fam-id' col_name1 = b'col-name1' col_name2 = b'col-name2' @@ -808,90 +817,105 @@ def test_it(self): def _CheckAndMutateRowRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.CheckAndMutateRowRequest(*args, **kw) def _CheckAndMutateRowResponsePB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.CheckAndMutateRowResponse(*args, **kw) def _MutateRowRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.MutateRowRequest(*args, **kw) def _ReadModifyWriteRowRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.ReadModifyWriteRowRequest(*args, **kw) def _ReadModifyWriteRowResponsePB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.ReadModifyWriteRowResponse(*args, **kw) def _CellPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Cell(*args, **kw) def _ColumnPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Column(*args, **kw) def _FamilyPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Family(*args, **kw) def _MutationPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Mutation(*args, **kw) def _MutationSetCellPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Mutation.SetCell(*args, **kw) def _MutationDeleteFromColumnPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Mutation.DeleteFromColumn(*args, **kw) def _MutationDeleteFromFamilyPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Mutation.DeleteFromFamily(*args, **kw) def _MutationDeleteFromRowPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Mutation.DeleteFromRow(*args, **kw) def _RowPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.Row(*args, **kw) def _ReadModifyWriteRulePB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.ReadModifyWriteRule(*args, **kw) diff --git a/bigtable/unit_tests/test_row_data.py b/bigtable/unit_tests/test_row_data.py index 8e5d72125f5d..8a2fb6a7e5e6 100644 --- a/bigtable/unit_tests/test_row_data.py +++ b/bigtable/unit_tests/test_row_data.py @@ -21,6 +21,7 @@ class TestCell(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_data import Cell + return Cell def _make_one(self, *args, **kwargs): @@ -97,6 +98,7 @@ class TestPartialRowData(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowData + return PartialRowData def _make_one(self, *args, **kwargs): @@ -189,6 +191,7 @@ class TestPartialRowsData(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowsData + return PartialRowsData def _getDoNothingClass(self): @@ -387,6 +390,7 @@ def test__save_row_no_cell(self): def test_invalid_last_scanned_row_key_on_start(self): from google.cloud.bigtable.row_data import InvalidReadRowsResponse + response = _ReadRowsResponseV2(chunks=(), last_scanned_row_key='ABC') iterator = _MockCancellableIterator(response) prd = self._make_one(iterator) @@ -404,6 +408,7 @@ def test_valid_last_scanned_row_key_on_start(self): def test_invalid_empty_chunk(self): from google.cloud.bigtable.row_data import InvalidChunk + chunks = _generate_cell_chunks(['']) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) @@ -413,6 +418,7 @@ def test_invalid_empty_chunk(self): def test_invalid_empty_second_chunk(self): from google.cloud.bigtable.row_data import InvalidChunk + chunks = _generate_cell_chunks(['', '']) first = chunks[0] first.row_key = b'RK' @@ -432,6 +438,7 @@ class TestPartialRowsData_JSON_acceptance_tests(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowsData + return PartialRowsData def _make_one(self, *args, **kwargs): @@ -439,6 +446,7 @@ def _make_one(self, *args, **kwargs): def _load_json_test(self, test_name): import os + if self.__class__._json_tests is None: dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'read-rows-acceptance-test.json') @@ -452,6 +460,7 @@ def _load_json_test(self, test_name): def _fail_during_consume(self, testcase_name): from google.cloud.bigtable.row_data import InvalidChunk + chunks, results = self._load_json_test(testcase_name) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) @@ -504,6 +513,7 @@ def test_invalid_commit_with_chunk(self): def _sort_flattend_cells(self, flattened): import operator + key_func = operator.itemgetter('rk', 'fm', 'qual') return sorted(flattened, key=key_func) @@ -643,6 +653,7 @@ def _flatten_cells(prd): # Doesn't handle error cases. from google.cloud._helpers import _bytes_to_unicode from google.cloud._helpers import _microseconds_from_datetime + for row_key, row in prd.rows.items(): for family_name, family in row.cells.items(): for qualifier, column in family.items(): diff --git a/bigtable/unit_tests/test_row_filters.py b/bigtable/unit_tests/test_row_filters.py index a49911acc0c3..b3715a1337ad 100644 --- a/bigtable/unit_tests/test_row_filters.py +++ b/bigtable/unit_tests/test_row_filters.py @@ -21,6 +21,7 @@ class Test_BoolFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import _BoolFilter + return _BoolFilter def _make_one(self, *args, **kwargs): @@ -56,6 +57,7 @@ class TestSinkFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import SinkFilter + return SinkFilter def _make_one(self, *args, **kwargs): @@ -74,6 +76,7 @@ class TestPassAllFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import PassAllFilter + return PassAllFilter def _make_one(self, *args, **kwargs): @@ -92,6 +95,7 @@ class TestBlockAllFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import BlockAllFilter + return BlockAllFilter def _make_one(self, *args, **kwargs): @@ -110,6 +114,7 @@ class Test_RegexFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import _RegexFilter + return _RegexFilter def _make_one(self, *args, **kwargs): @@ -150,6 +155,7 @@ class TestRowKeyRegexFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import RowKeyRegexFilter + return RowKeyRegexFilter def _make_one(self, *args, **kwargs): @@ -168,6 +174,7 @@ class TestRowSampleFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import RowSampleFilter + return RowSampleFilter def _make_one(self, *args, **kwargs): @@ -203,6 +210,7 @@ class TestFamilyNameRegexFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import FamilyNameRegexFilter + return FamilyNameRegexFilter def _make_one(self, *args, **kwargs): @@ -222,6 +230,7 @@ class TestColumnQualifierRegexFilter(unittest.TestCase): def _get_target_class(): from google.cloud.bigtable.row_filters import ( ColumnQualifierRegexFilter) + return ColumnQualifierRegexFilter def _make_one(self, *args, **kwargs): @@ -241,6 +250,7 @@ class TestTimestampRange(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import TimestampRange + return TimestampRange def _make_one(self, *args, **kwargs): @@ -278,6 +288,7 @@ def test___ne__same_value(self): def _to_pb_helper(self, start_micros=None, end_micros=None): import datetime from google.cloud._helpers import _EPOCH + pb_kwargs = {} start = None @@ -316,6 +327,7 @@ class TestTimestampRangeFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import TimestampRangeFilter + return TimestampRangeFilter def _make_one(self, *args, **kwargs): @@ -354,6 +366,7 @@ class TestColumnRangeFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import ColumnRangeFilter + return ColumnRangeFilter def _make_one(self, *args, **kwargs): @@ -479,6 +492,7 @@ class TestValueRegexFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import ValueRegexFilter + return ValueRegexFilter def _make_one(self, *args, **kwargs): @@ -497,6 +511,7 @@ class TestValueRangeFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import ValueRangeFilter + return ValueRangeFilter def _make_one(self, *args, **kwargs): @@ -589,6 +604,7 @@ class Test_CellCountFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import _CellCountFilter + return _CellCountFilter def _make_one(self, *args, **kwargs): @@ -624,6 +640,7 @@ class TestCellsRowOffsetFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import CellsRowOffsetFilter + return CellsRowOffsetFilter def _make_one(self, *args, **kwargs): @@ -643,6 +660,7 @@ class TestCellsRowLimitFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import CellsRowLimitFilter + return CellsRowLimitFilter def _make_one(self, *args, **kwargs): @@ -662,6 +680,7 @@ class TestCellsColumnLimitFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import CellsColumnLimitFilter + return CellsColumnLimitFilter def _make_one(self, *args, **kwargs): @@ -682,6 +701,7 @@ class TestStripValueTransformerFilter(unittest.TestCase): def _get_target_class(): from google.cloud.bigtable.row_filters import ( StripValueTransformerFilter) + return StripValueTransformerFilter def _make_one(self, *args, **kwargs): @@ -700,6 +720,7 @@ class TestApplyLabelFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import ApplyLabelFilter + return ApplyLabelFilter def _make_one(self, *args, **kwargs): @@ -735,6 +756,7 @@ class Test_FilterCombination(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import _FilterCombination + return _FilterCombination def _make_one(self, *args, **kwargs): @@ -767,6 +789,7 @@ class TestRowFilterChain(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import RowFilterChain + return RowFilterChain def _make_one(self, *args, **kwargs): @@ -824,6 +847,7 @@ class TestRowFilterUnion(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import RowFilterUnion + return RowFilterUnion def _make_one(self, *args, **kwargs): @@ -881,6 +905,7 @@ class TestConditionalRowFilter(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.row_filters import ConditionalRowFilter + return ConditionalRowFilter def _make_one(self, *args, **kwargs): @@ -995,40 +1020,47 @@ def test_to_pb_false_only(self): def _ColumnRangePB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.ColumnRange(*args, **kw) def _RowFilterPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.RowFilter(*args, **kw) def _RowFilterChainPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.RowFilter.Chain(*args, **kw) def _RowFilterConditionPB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.RowFilter.Condition(*args, **kw) def _RowFilterInterleavePB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.RowFilter.Interleave(*args, **kw) def _TimestampRangePB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.TimestampRange(*args, **kw) def _ValueRangePB(*args, **kw): from google.cloud.bigtable._generated import ( data_pb2 as data_v2_pb2) + return data_v2_pb2.ValueRange(*args, **kw) diff --git a/bigtable/unit_tests/test_table.py b/bigtable/unit_tests/test_table.py index f96ddcc8e704..4ad6afe1596f 100644 --- a/bigtable/unit_tests/test_table.py +++ b/bigtable/unit_tests/test_table.py @@ -32,6 +32,7 @@ class TestTable(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.bigtable.table import Table + return Table def _make_one(self, *args, **kwargs): @@ -432,6 +433,7 @@ class Test__create_row_request(unittest.TestCase): def _call_fut(self, table_name, row_key=None, start_key=None, end_key=None, filter_=None, limit=None): from google.cloud.bigtable.table import _create_row_request + return _create_row_request( table_name, row_key=row_key, start_key=start_key, end_key=end_key, filter_=filter_, limit=limit) @@ -486,6 +488,7 @@ def test_row_range_both_keys(self): def test_with_filter(self): from google.cloud.bigtable.row_filters import RowSampleFilter + table_name = 'table_name' row_filter = RowSampleFilter(0.33) result = self._call_fut(table_name, filter_=row_filter) @@ -509,36 +512,42 @@ def test_with_limit(self): def _CreateTableRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_table_admin_pb2 as table_admin_v2_pb2) + return table_admin_v2_pb2.CreateTableRequest(*args, **kw) def _CreateTableRequestSplitPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_table_admin_pb2 as table_admin_v2_pb2) + return table_admin_v2_pb2.CreateTableRequest.Split(*args, **kw) def _DeleteTableRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_table_admin_pb2 as table_admin_v2_pb2) + return table_admin_v2_pb2.DeleteTableRequest(*args, **kw) def _GetTableRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_table_admin_pb2 as table_admin_v2_pb2) + return table_admin_v2_pb2.GetTableRequest(*args, **kw) def _ReadRowsRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.ReadRowsRequest(*args, **kw) def _ReadRowsResponseCellChunkPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + family_name = kw.pop('family_name') qualifier = kw.pop('qualifier') message = messages_v2_pb2.ReadRowsResponse.CellChunk(*args, **kw) @@ -550,24 +559,28 @@ def _ReadRowsResponseCellChunkPB(*args, **kw): def _ReadRowsResponsePB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.ReadRowsResponse(*args, **kw) def _SampleRowKeysRequestPB(*args, **kw): from google.cloud.bigtable._generated import ( bigtable_pb2 as messages_v2_pb2) + return messages_v2_pb2.SampleRowKeysRequest(*args, **kw) def _TablePB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.Table(*args, **kw) def _ColumnFamilyPB(*args, **kw): from google.cloud.bigtable._generated import ( table_pb2 as table_v2_pb2) + return table_v2_pb2.ColumnFamily(*args, **kw) diff --git a/core/unit_tests/streaming/test_buffered_stream.py b/core/unit_tests/streaming/test_buffered_stream.py index 8a8793b0c49c..797ceea2d280 100644 --- a/core/unit_tests/streaming/test_buffered_stream.py +++ b/core/unit_tests/streaming/test_buffered_stream.py @@ -20,6 +20,7 @@ class Test_BufferedStream(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.buffered_stream import BufferedStream + return BufferedStream def _make_one(self, *args, **kw): @@ -41,6 +42,7 @@ class _Stream(object): def test_ctor_start_zero_longer_than_buffer(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 0 BUFSIZE = 4 @@ -56,6 +58,7 @@ def test_ctor_start_zero_longer_than_buffer(self): def test_ctor_start_nonzero_shorter_than_buffer(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 8 BUFSIZE = 10 @@ -72,6 +75,7 @@ def test_ctor_start_nonzero_shorter_than_buffer(self): def test__bytes_remaining_start_zero_longer_than_buffer(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 0 BUFSIZE = 4 @@ -81,6 +85,7 @@ def test__bytes_remaining_start_zero_longer_than_buffer(self): def test__bytes_remaining_start_zero_shorter_than_buffer(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 8 BUFSIZE = 10 @@ -91,6 +96,7 @@ def test__bytes_remaining_start_zero_shorter_than_buffer(self): def test_read_w_none(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 0 BUFSIZE = 4 @@ -101,6 +107,7 @@ def test_read_w_none(self): def test_read_w_negative_size(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 0 BUFSIZE = 4 @@ -111,6 +118,7 @@ def test_read_w_negative_size(self): def test_read_from_start(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = 0 BUFSIZE = 4 @@ -120,6 +128,7 @@ def test_read_from_start(self): def test_read_exhausted(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' START = len(CONTENT) BUFSIZE = 10 diff --git a/core/unit_tests/streaming/test_exceptions.py b/core/unit_tests/streaming/test_exceptions.py index 0cb1c724bf99..b31c562c8e9d 100644 --- a/core/unit_tests/streaming/test_exceptions.py +++ b/core/unit_tests/streaming/test_exceptions.py @@ -20,6 +20,7 @@ class Test_HttpError(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.exceptions import HttpError + return HttpError def _make_one(self, *args, **kw): @@ -62,6 +63,7 @@ class Test_RetryAfterError(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.exceptions import RetryAfterError + return RetryAfterError def _make_one(self, *args, **kw): diff --git a/core/unit_tests/streaming/test_http_wrapper.py b/core/unit_tests/streaming/test_http_wrapper.py index f05e1b0a6f9f..b0d3156ba42f 100644 --- a/core/unit_tests/streaming/test_http_wrapper.py +++ b/core/unit_tests/streaming/test_http_wrapper.py @@ -20,6 +20,7 @@ class Test__httplib2_debug_level(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.http_wrapper import _httplib2_debug_level + return _httplib2_debug_level def _make_one(self, *args, **kw): @@ -80,6 +81,7 @@ class Test_Request(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.http_wrapper import Request + return Request def _make_one(self, *args, **kw): @@ -95,6 +97,7 @@ def test_ctor_defaults(self): def test_loggable_body_setter_w_body_None(self): from google.cloud.streaming.exceptions import RequestError + request = self._make_one(body=None) with self.assertRaises(RequestError): request.loggable_body = 'abc' @@ -121,6 +124,7 @@ class Test_Response(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.http_wrapper import Response + return Response def _make_one(self, *args, **kw): @@ -217,10 +221,12 @@ class Test__check_response(unittest.TestCase): def _call_fut(self, *args, **kw): from google.cloud.streaming.http_wrapper import _check_response + return _check_response(*args, **kw) def test_w_none(self): from google.cloud.streaming.exceptions import RequestError + with self.assertRaises(RequestError): self._call_fut(None) @@ -254,6 +260,7 @@ class Test__reset_http_connections(unittest.TestCase): def _call_fut(self, *args, **kw): from google.cloud.streaming.http_wrapper import _reset_http_connections + return _reset_http_connections(*args, **kw) def test_wo_connections(self): @@ -289,6 +296,7 @@ def _verify_requested(self, http, request, def test_defaults_wo_connections(self): from google.cloud._testing import _Monkey from google.cloud.streaming import http_wrapper as MUT + INFO = {'status': '200'} CONTENT = 'CONTENT' _http = _Http((INFO, CONTENT)) @@ -309,6 +317,7 @@ def test_defaults_wo_connections(self): def test_w_http_connections_miss(self): from google.cloud._testing import _Monkey from google.cloud.streaming import http_wrapper as MUT + INFO = {'status': '200'} CONTENT = 'CONTENT' CONN_TYPE = object() @@ -331,6 +340,7 @@ def test_w_http_connections_miss(self): def test_w_http_connections_hit(self): from google.cloud._testing import _Monkey from google.cloud.streaming import http_wrapper as MUT + INFO = {'status': '200'} CONTENT = 'CONTENT' CONN_TYPE = object() @@ -354,6 +364,7 @@ def test_w_request_returning_None(self): from google.cloud._testing import _Monkey from google.cloud.streaming import http_wrapper as MUT from google.cloud.streaming.exceptions import RequestError + INFO = None CONTENT = None CONN_TYPE = object() @@ -371,6 +382,7 @@ class Test_make_api_request(unittest.TestCase): def _call_fut(self, *args, **kw): from google.cloud.streaming.http_wrapper import make_api_request + return make_api_request(*args, **kw) def test_wo_exception(self): @@ -424,6 +436,7 @@ def _wo_exception(*args, **kw): def test_w_exceptions_gt_max_retries(self): from google.cloud._testing import _Monkey from google.cloud.streaming import http_wrapper as MUT + HTTP = object() REQUEST = _Request() _created, _checked = [], [] diff --git a/core/unit_tests/streaming/test_stream_slice.py b/core/unit_tests/streaming/test_stream_slice.py index c0c5ff375a96..47820078447d 100644 --- a/core/unit_tests/streaming/test_stream_slice.py +++ b/core/unit_tests/streaming/test_stream_slice.py @@ -20,6 +20,7 @@ class Test_StreamSlice(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.stream_slice import StreamSlice + return StreamSlice def _make_one(self, *args, **kw): @@ -27,6 +28,7 @@ def _make_one(self, *args, **kw): def test_ctor(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) @@ -39,6 +41,7 @@ def test_ctor(self): def test___nonzero___empty(self): from io import BytesIO + CONTENT = b'' MAXSIZE = 0 stream = BytesIO(CONTENT) @@ -47,6 +50,7 @@ def test___nonzero___empty(self): def test___nonzero___nonempty(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) @@ -56,6 +60,7 @@ def test___nonzero___nonempty(self): def test_read_exhausted(self): from io import BytesIO from six.moves import http_client + CONTENT = b'' MAXSIZE = 4 stream = BytesIO(CONTENT) @@ -65,6 +70,7 @@ def test_read_exhausted(self): def test_read_implicit_size(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) @@ -74,6 +80,7 @@ def test_read_implicit_size(self): def test_read_explicit_size(self): from io import BytesIO + CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 SIZE = 3 diff --git a/core/unit_tests/streaming/test_transfer.py b/core/unit_tests/streaming/test_transfer.py index aa4fd2e546ad..8bafd4a1cc47 100644 --- a/core/unit_tests/streaming/test_transfer.py +++ b/core/unit_tests/streaming/test_transfer.py @@ -21,6 +21,7 @@ class Test__Transfer(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.transfer import _Transfer + return _Transfer def _make_one(self, *args, **kw): @@ -28,6 +29,7 @@ def _make_one(self, *args, **kw): def test_ctor_defaults(self): from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE + stream = _Stream() xfer = self._make_one(stream) self.assertIs(xfer.stream, stream) @@ -96,6 +98,7 @@ def test__initialize_not_already_initialized_w_http(self): def test__initialize_not_already_initialized_wo_http(self): from httplib2 import Http + stream = _Stream() xfer = self._make_one(stream) xfer._initialize(None, self.URL) @@ -114,6 +117,7 @@ def test__initialize_w_existing_http(self): def test__initialize_already_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + URL_2 = 'http://example.com/other' HTTP_1, HTTP_2 = object(), object() stream = _Stream() @@ -131,6 +135,7 @@ def test__ensure_initialized_hit(self): def test__ensure_initialized_miss(self): from google.cloud.streaming.exceptions import TransferInvalidError + stream = _Stream() xfer = self._make_one(stream) with self.assertRaises(TransferInvalidError): @@ -143,6 +148,7 @@ def test__ensure_uninitialized_hit(self): def test__ensure_uninitialized_miss(self): from google.cloud.streaming.exceptions import TransferInvalidError + stream = _Stream() HTTP = object() xfer = self._make_one(stream) @@ -166,6 +172,7 @@ class Test_Download(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.transfer import Download + return Download def _make_one(self, *args, **kw): @@ -197,6 +204,7 @@ def test_ctor_w_total_size(self): def test_from_file_w_existing_file_no_override(self): import os from google.cloud._testing import _tempdir + klass = self._get_target_class() with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.out') @@ -208,6 +216,7 @@ def test_from_file_w_existing_file_no_override(self): def test_from_file_w_existing_file_w_override_wo_auto_transfer(self): import os from google.cloud._testing import _tempdir + klass = self._get_target_class() with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.out') @@ -277,6 +286,7 @@ def test__set_total_w_content_range_w_asterisk_total(self): def test_initialize_download_already_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + request = _Request() download = self._make_one(_Stream()) download._initialize(None, self.URL) @@ -296,6 +306,7 @@ def test_initialize_download_w_autotransfer_failing(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.exceptions import HttpError + request = _Request() http = object() download = self._make_one(_Stream(), auto_transfer=True) @@ -314,6 +325,7 @@ def test_initialize_download_w_autotransfer_w_content_location(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + REDIRECT_URL = 'http://example.com/other' request = _Request() http = object() @@ -335,6 +347,7 @@ def test_initialize_download_w_autotransfer_w_content_location(self): def test__normalize_start_end_w_end_w_start_lt_0(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): @@ -342,6 +355,7 @@ def test__normalize_start_end_w_end_w_start_lt_0(self): def test__normalize_start_end_w_end_w_start_gt_total(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) @@ -350,6 +364,7 @@ def test__normalize_start_end_w_end_w_start_gt_total(self): def test__normalize_start_end_w_end_lt_start(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) @@ -422,6 +437,7 @@ def test__compute_end_byte_w_start_ge_0_wo_end_w_total_size(self): def test__get_chunk_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): @@ -431,6 +447,7 @@ def test__get_chunk(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + http = object() download = self._make_one(_Stream()) download._initialize(http, self.URL) @@ -450,6 +467,7 @@ def test__get_chunk(self): def test__process_response_w_FORBIDDEN(self): from google.cloud.streaming.exceptions import HttpError from six.moves import http_client + download = self._make_one(_Stream()) response = _makeResponse(http_client.FORBIDDEN) with self.assertRaises(HttpError): @@ -458,6 +476,7 @@ def test__process_response_w_FORBIDDEN(self): def test__process_response_w_NOT_FOUND(self): from google.cloud.streaming.exceptions import HttpError from six.moves import http_client + download = self._make_one(_Stream()) response = _makeResponse(http_client.NOT_FOUND) with self.assertRaises(HttpError): @@ -466,6 +485,7 @@ def test__process_response_w_NOT_FOUND(self): def test__process_response_w_other_error(self): from google.cloud.streaming.exceptions import TransferRetryError from six.moves import http_client + download = self._make_one(_Stream()) response = _makeResponse(http_client.BAD_REQUEST) with self.assertRaises(TransferRetryError): @@ -473,6 +493,7 @@ def test__process_response_w_other_error(self): def test__process_response_w_OK_wo_encoding(self): from six.moves import http_client + stream = _Stream() download = self._make_one(stream) response = _makeResponse(http_client.OK, content='OK') @@ -484,6 +505,7 @@ def test__process_response_w_OK_wo_encoding(self): def test__process_response_w_PARTIAL_CONTENT_w_encoding(self): from six.moves import http_client + stream = _Stream() download = self._make_one(stream) info = {'content-encoding': 'blah'} @@ -496,6 +518,7 @@ def test__process_response_w_PARTIAL_CONTENT_w_encoding(self): def test__process_response_w_REQUESTED_RANGE_NOT_SATISFIABLE(self): from six.moves import http_client + stream = _Stream() download = self._make_one(stream) response = _makeResponse( @@ -508,6 +531,7 @@ def test__process_response_w_REQUESTED_RANGE_NOT_SATISFIABLE(self): def test__process_response_w_NO_CONTENT(self): from six.moves import http_client + stream = _Stream() download = self._make_one(stream) response = _makeResponse(status_code=http_client.NO_CONTENT) @@ -519,6 +543,7 @@ def test__process_response_w_NO_CONTENT(self): def test_get_range_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): download.get_range(0, 10) @@ -527,6 +552,7 @@ def test_get_range_wo_total_size_complete(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) REQ_RANGE = 'bytes=0-%d' % (LEN,) @@ -554,6 +580,7 @@ def test_get_range_wo_total_size_wo_end(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) START = 5 @@ -583,6 +610,7 @@ def test_get_range_w_total_size_partial(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) PARTIAL_LEN = 5 @@ -613,6 +641,7 @@ def test_get_range_w_empty_chunk(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.exceptions import TransferRetryError + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) START = 5 @@ -643,6 +672,7 @@ def test_get_range_w_total_size_wo_use_chunks(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) CHUNK_SIZE = 3 @@ -671,6 +701,7 @@ def test_get_range_w_multiple_chunks(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDE' LEN = len(CONTENT) CHUNK_SIZE = 3 @@ -705,6 +736,7 @@ def test_get_range_w_multiple_chunks(self): def test_stream_file_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): @@ -712,6 +744,7 @@ def test_stream_file_not_initialized(self): def test_stream_file_w_initial_response_complete(self): from six.moves import http_client + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) @@ -732,6 +765,7 @@ def test_stream_file_w_initial_response_incomplete(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CHUNK_SIZE = 3 CONTENT = b'ABCDEF' LEN = len(CONTENT) @@ -769,6 +803,7 @@ def test_stream_file_wo_initial_response_wo_total_size(self): from six.moves import http_client from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) CHUNK_SIZE = 123 @@ -804,6 +839,7 @@ class Test_Upload(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.streaming.transfer import Upload + return Upload def _make_one(self, stream, mime_type=MIME_TYPE, *args, **kw): @@ -811,6 +847,7 @@ def _make_one(self, stream, mime_type=MIME_TYPE, *args, **kw): def test_ctor_defaults(self): from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE + stream = _Stream() upload = self._make_one(stream) self.assertIs(upload.stream, stream) @@ -840,6 +877,7 @@ def test_from_file_w_nonesuch_file(self): def test_from_file_wo_mimetype_w_unguessable_filename(self): import os from google.cloud._testing import _tempdir + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ UNGUESSABLE MIMETYPE' with _tempdir() as tempdir: @@ -852,6 +890,7 @@ def test_from_file_wo_mimetype_w_unguessable_filename(self): def test_from_file_wo_mimetype_w_guessable_filename(self): import os from google.cloud._testing import _tempdir + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ GUESSABLE MIMETYPE' with _tempdir() as tempdir: @@ -867,6 +906,7 @@ def test_from_file_wo_mimetype_w_guessable_filename(self): def test_from_file_w_mimetype_w_auto_transfer_w_kwds(self): import os from google.cloud._testing import _tempdir + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ GUESSABLE MIMETYPE' CHUNK_SIZE = 3 @@ -924,18 +964,21 @@ def test_strategy_setter_invalid(self): def test_strategy_setter_SIMPLE_UPLOAD(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD self.assertEqual(upload.strategy, SIMPLE_UPLOAD) def test_strategy_setter_RESUMABLE_UPLOAD(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD self.assertEqual(upload.strategy, RESUMABLE_UPLOAD) def test_total_size_setter_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + SIZE = 123 upload = self._make_one(_Stream) http = object() @@ -951,6 +994,7 @@ def test_total_size_setter_not_initialized(self): def test__set_default_strategy_w_existing_strategy(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + config = _Dummy( resumable_path='/resumable/endpoint', simple_multipart=True, @@ -964,6 +1008,7 @@ def test__set_default_strategy_w_existing_strategy(self): def test__set_default_strategy_wo_resumable_path(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + config = _Dummy( resumable_path=None, simple_multipart=True, @@ -977,6 +1022,7 @@ def test__set_default_strategy_wo_resumable_path(self): def test__set_default_strategy_w_total_size_gt_threshhold(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD_THRESHOLD from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + config = _UploadConfig() request = _Request() upload = self._make_one( @@ -986,6 +1032,7 @@ def test__set_default_strategy_w_total_size_gt_threshhold(self): def test__set_default_strategy_w_body_wo_multipart(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' config = _UploadConfig() config.simple_multipart = False @@ -996,6 +1043,7 @@ def test__set_default_strategy_w_body_wo_multipart(self): def test__set_default_strategy_w_body_w_multipart_wo_simple_path(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' config = _UploadConfig() config.simple_path = None @@ -1006,6 +1054,7 @@ def test__set_default_strategy_w_body_w_multipart_wo_simple_path(self): def test__set_default_strategy_w_body_w_multipart_w_simple_path(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' config = _UploadConfig() request = _Request(body=CONTENT) @@ -1034,6 +1083,7 @@ def test_configure_request_w_invalid_mimetype(self): def test_configure_request_w_simple_wo_body(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + CONTENT = b'CONTENT' config = _UploadConfig() request = _Request() @@ -1053,6 +1103,7 @@ def test_configure_request_w_simple_wo_body(self): def test_configure_request_w_simple_w_body(self): from google.cloud._helpers import _to_bytes from google.cloud.streaming.transfer import SIMPLE_UPLOAD + CONTENT = b'CONTENT' BODY = b'BODY' config = _UploadConfig() @@ -1095,6 +1146,7 @@ def test_configure_request_w_simple_w_body(self): def test_configure_request_w_resumable_wo_total_size(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'CONTENT' config = _UploadConfig() request = _Request() @@ -1112,6 +1164,7 @@ def test_configure_request_w_resumable_wo_total_size(self): def test_configure_request_w_resumable_w_total_size(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'CONTENT' LEN = len(CONTENT) config = _UploadConfig() @@ -1132,6 +1185,7 @@ def test_configure_request_w_resumable_w_total_size(self): def test_refresh_upload_state_w_simple_strategy(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD upload.refresh_upload_state() # no-op @@ -1139,6 +1193,7 @@ def test_refresh_upload_state_w_simple_strategy(self): def test_refresh_upload_state_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD with self.assertRaises(TransferInvalidError): @@ -1149,6 +1204,7 @@ def test_refresh_upload_state_w_OK(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) @@ -1176,6 +1232,7 @@ def test_refresh_upload_state_w_CREATED(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) @@ -1203,6 +1260,7 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_w_range(self): from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE from google.cloud._testing import _Monkey from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) LAST = 5 @@ -1230,6 +1288,7 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_wo_range(self): from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE from google.cloud._testing import _Monkey from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) http = object() @@ -1256,6 +1315,7 @@ def test_refresh_upload_state_w_error(self): from google.cloud.streaming import transfer as MUT from google.cloud.streaming.exceptions import HttpError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' LEN = len(CONTENT) http = object() @@ -1295,6 +1355,7 @@ def test_initialize_upload_no_strategy(self): def test_initialize_upload_simple_w_http(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + request = _Request() upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD @@ -1303,6 +1364,7 @@ def test_initialize_upload_simple_w_http(self): def test_initialize_upload_resumable_already_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + request = _Request() upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD @@ -1316,6 +1378,7 @@ def test_initialize_upload_w_http_resumable_not_initialized_w_error(self): from google.cloud.streaming import transfer as MUT from google.cloud.streaming.exceptions import HttpError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + request = _Request() upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD @@ -1331,6 +1394,7 @@ def test_initialize_upload_w_http_wo_auto_transfer_w_OK(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + request = _Request() upload = self._make_one(_Stream(), auto_transfer=False) upload.strategy = RESUMABLE_UPLOAD @@ -1352,6 +1416,7 @@ def test_initialize_upload_w_granularity_w_auto_transfer_w_OK(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() request = _Request() @@ -1400,6 +1465,7 @@ def test__validate_chunksize_w__server_chunk_granularity_hit(self): def test_stream_file_w_simple_strategy(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD with self.assertRaises(ValueError): @@ -1407,6 +1473,7 @@ def test_stream_file_w_simple_strategy(self): def test_stream_file_w_use_chunks_invalid_chunk_size(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + upload = self._make_one(_Stream(), chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 100 @@ -1416,6 +1483,7 @@ def test_stream_file_w_use_chunks_invalid_chunk_size(self): def test_stream_file_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + upload = self._make_one(_Stream(), chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 @@ -1424,6 +1492,7 @@ def test_stream_file_not_initialized(self): def test_stream_file_already_complete_w_unseekable_stream(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + http = object() stream = object() response = object() @@ -1438,6 +1507,7 @@ def test_stream_file_already_complete_w_unseekable_stream(self): def test_stream_file_already_complete_w_seekable_stream_unsynced(self): from google.cloud.streaming.exceptions import CommunicationError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) @@ -1454,6 +1524,7 @@ def test_stream_file_already_complete_w_seekable_stream_unsynced(self): def test_stream_file_already_complete_wo_seekable_method_synced(self): import os from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) @@ -1470,6 +1541,7 @@ def test_stream_file_already_complete_wo_seekable_method_synced(self): def test_stream_file_already_complete_w_seekable_method_true_synced(self): import os from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _StreamWithSeekableMethod(CONTENT, True) @@ -1486,6 +1558,7 @@ def test_stream_file_already_complete_w_seekable_method_true_synced(self): def test_stream_file_already_complete_w_seekable_method_false(self): import os from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _StreamWithSeekableMethod(CONTENT, False) @@ -1505,6 +1578,7 @@ def test_stream_file_incomplete(self): from google.cloud.streaming import transfer as MUT from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) @@ -1550,6 +1624,7 @@ def test_stream_file_incomplete_w_transfer_error(self): from google.cloud.streaming.exceptions import CommunicationError from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) @@ -1586,6 +1661,7 @@ def test__send_media_request_wo_error(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE + CONTENT = b'ABCDEFGHIJ' bytes_http = object() stream = _Stream(CONTENT) @@ -1616,6 +1692,7 @@ def test__send_media_request_w_error(self): from google.cloud.streaming.exceptions import HttpError from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE from google.cloud.streaming.transfer import RESUMABLE_UPLOAD + CONTENT = b'ABCDEFGHIJ' bytes_http = object() http = object() @@ -1652,12 +1729,14 @@ def test__send_media_request_w_error(self): def test__send_media_body_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + upload = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): upload._send_media_body(0) def test__send_media_body_wo_total_size(self): from google.cloud.streaming.exceptions import TransferInvalidError + http = object() upload = self._make_one(_Stream()) upload._initialize(http, _Request.URL) @@ -1666,6 +1745,7 @@ def test__send_media_body_wo_total_size(self): def test__send_media_body_start_lt_total_size(self): from google.cloud.streaming.stream_slice import StreamSlice + SIZE = 1234 http = object() stream = _Stream() @@ -1693,6 +1773,7 @@ def test__send_media_body_start_lt_total_size(self): def test__send_media_body_start_eq_total_size(self): from google.cloud.streaming.stream_slice import StreamSlice + SIZE = 1234 http = object() stream = _Stream() @@ -1720,6 +1801,7 @@ def test__send_media_body_start_eq_total_size(self): def test__send_chunk_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError + upload = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): upload._send_chunk(0) @@ -1779,6 +1861,7 @@ def test__send_chunk_wo_total_size_stream_not_exhausted(self): def test__send_chunk_w_total_size_stream_not_exhausted(self): from google.cloud.streaming.stream_slice import StreamSlice + CONTENT = b'ABCDEFGHIJ' SIZE = len(CONTENT) CHUNK_SIZE = SIZE - 5 @@ -1810,6 +1893,7 @@ def test__send_chunk_w_total_size_stream_not_exhausted(self): def test__send_chunk_w_total_size_stream_exhausted(self): from google.cloud.streaming.stream_slice import StreamSlice + CONTENT = b'ABCDEFGHIJ' SIZE = len(CONTENT) CHUNK_SIZE = 1000 @@ -1840,12 +1924,15 @@ def test__send_chunk_w_total_size_stream_exhausted(self): def _email_chunk_parser(): import six + if six.PY3: # pragma: NO COVER Python3 from email.parser import BytesParser + parser = BytesParser() return parser.parsebytes else: from email.parser import Parser + parser = Parser() return parser.parsestr @@ -1868,6 +1955,7 @@ class _Stream(object): def __init__(self, to_read=b''): import io + self._written = [] self._to_read = io.BytesIO(to_read) diff --git a/core/unit_tests/streaming/test_util.py b/core/unit_tests/streaming/test_util.py index 1ee1c03d073f..4da788182cb9 100644 --- a/core/unit_tests/streaming/test_util.py +++ b/core/unit_tests/streaming/test_util.py @@ -19,17 +19,20 @@ class Test_calculate_wait_for_retry(unittest.TestCase): def _call_fut(self, *args, **kw): from google.cloud.streaming.util import calculate_wait_for_retry + return calculate_wait_for_retry(*args, **kw) def test_w_negative_jitter_lt_max_wait(self): import random from google.cloud._testing import _Monkey + with _Monkey(random, uniform=lambda lower, upper: lower): self.assertEqual(self._call_fut(1), 1.5) def test_w_positive_jitter_gt_max_wait(self): import random from google.cloud._testing import _Monkey + with _Monkey(random, uniform=lambda lower, upper: upper): self.assertEqual(self._call_fut(4), 20) @@ -38,6 +41,7 @@ class Test_acceptable_mime_type(unittest.TestCase): def _call_fut(self, *args, **kw): from google.cloud.streaming.util import acceptable_mime_type + return acceptable_mime_type(*args, **kw) def test_pattern_wo_slash(self): diff --git a/core/unit_tests/test__helpers.py b/core/unit_tests/test__helpers.py index bc1a4dafb6b7..f9fa5d58ea0f 100644 --- a/core/unit_tests/test__helpers.py +++ b/core/unit_tests/test__helpers.py @@ -51,6 +51,7 @@ class Test__UTC(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud._helpers import _UTC + return _UTC def _make_one(self): @@ -58,6 +59,7 @@ def _make_one(self): def test_module_property(self): from google.cloud import _helpers as MUT + klass = self._get_target_class() try: import pytz @@ -104,6 +106,7 @@ class Test__ensure_tuple_or_list(unittest.TestCase): def _call_fut(self, arg_name, tuple_or_list): from google.cloud._helpers import _ensure_tuple_or_list + return _ensure_tuple_or_list(arg_name, tuple_or_list) def test_valid_tuple(self): @@ -131,6 +134,7 @@ class Test__determine_default_project(unittest.TestCase): def _call_fut(self, project=None): from google.cloud._helpers import _determine_default_project + return _determine_default_project(project=project) def test_it(self): @@ -154,6 +158,7 @@ class Test__millis(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _millis + return _millis(value) def test_one_second_from_epoch(self): @@ -168,6 +173,7 @@ class Test__microseconds_from_datetime(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _microseconds_from_datetime + return _microseconds_from_datetime(value) def test_it(self): @@ -185,6 +191,7 @@ class Test__millis_from_datetime(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _millis_from_datetime + return _millis_from_datetime(value) def test_w_none(self): @@ -240,6 +247,7 @@ class Test__datetime_from_microseconds(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _datetime_from_microseconds + return _datetime_from_microseconds(value) def test_it(self): @@ -257,10 +265,12 @@ class Test___date_from_iso8601_date(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _date_from_iso8601_date + return _date_from_iso8601_date(value) def test_todays_date(self): import datetime + TODAY = datetime.date.today() self.assertEqual(self._call_fut(TODAY.strftime("%Y-%m-%d")), TODAY) @@ -269,10 +279,12 @@ class Test___time_from_iso8601_time_naive(unittest.TestCase): def _call_fut(self, value): from google.cloud._helpers import _time_from_iso8601_time_naive + return _time_from_iso8601_time_naive(value) def test_todays_date(self): import datetime + WHEN = datetime.time(12, 9, 42) self.assertEqual(self._call_fut(("12:09:42")), WHEN) @@ -281,6 +293,7 @@ class Test__rfc3339_to_datetime(unittest.TestCase): def _call_fut(self, dt_str): from google.cloud._helpers import _rfc3339_to_datetime + return _rfc3339_to_datetime(dt_str) def test_w_bogus_zone(self): @@ -335,6 +348,7 @@ class Test__rfc3339_nanos_to_datetime(unittest.TestCase): def _call_fut(self, dt_str): from google.cloud._helpers import _rfc3339_nanos_to_datetime + return _rfc3339_nanos_to_datetime(dt_str) def test_w_bogus_zone(self): @@ -423,6 +437,7 @@ class Test__datetime_to_rfc3339(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import _datetime_to_rfc3339 + return _datetime_to_rfc3339(*args, **kwargs) @staticmethod @@ -471,6 +486,7 @@ class Test__to_bytes(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import _to_bytes + return _to_bytes(*args, **kwargs) def test_with_bytes(self): @@ -498,6 +514,7 @@ class Test__bytes_to_unicode(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import _bytes_to_unicode + return _bytes_to_unicode(*args, **kwargs) def test_with_bytes(self): @@ -519,6 +536,7 @@ class Test__pb_timestamp_to_datetime(unittest.TestCase): def _call_fut(self, timestamp): from google.cloud._helpers import _pb_timestamp_to_datetime + return _pb_timestamp_to_datetime(timestamp) def test_it(self): @@ -540,6 +558,7 @@ class Test__pb_timestamp_to_rfc3339(unittest.TestCase): def _call_fut(self, timestamp): from google.cloud._helpers import _pb_timestamp_to_rfc3339 + return _pb_timestamp_to_rfc3339(timestamp) def test_it(self): @@ -557,6 +576,7 @@ class Test__datetime_to_pb_timestamp(unittest.TestCase): def _call_fut(self, when): from google.cloud._helpers import _datetime_to_pb_timestamp + return _datetime_to_pb_timestamp(when) def test_it(self): @@ -603,6 +623,7 @@ def test_w_mismatched_project(self): def test_w_valid_data_w_compiled_regex(self): import re + template = re.compile(self.TEMPLATE) PATH = 'projects/%s/things/%s' % (self.PROJECT, self.THING_NAME) name = self._call_fut(PATH, self.PROJECT, template) @@ -620,6 +641,7 @@ class Test_make_secure_channel(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_secure_channel + return make_secure_channel(*args, **kwargs) def test_it(self): @@ -676,6 +698,7 @@ class Test_make_secure_stub(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_secure_stub + return make_secure_stub(*args, **kwargs) def test_it(self): @@ -714,6 +737,7 @@ class Test_make_insecure_stub(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_insecure_stub + return make_insecure_stub(*args, **kwargs) def _helper(self, target, host, port=None): diff --git a/core/unit_tests/test__http.py b/core/unit_tests/test__http.py index b27f0240d82a..23a198d1f68b 100644 --- a/core/unit_tests/test__http.py +++ b/core/unit_tests/test__http.py @@ -62,6 +62,7 @@ def test_http_w_existing(self): def test_http_wo_creds(self): import httplib2 + conn = self._make_one() self.assertIsInstance(conn.http, httplib2.Http) @@ -78,6 +79,7 @@ def test_http_w_creds(self): def test_user_agent_format(self): from pkg_resources import get_distribution + expected_ua = 'gcloud-python/{0}'.format( get_distribution('google-cloud-core').version) conn = self._make_one() @@ -123,6 +125,7 @@ def test_http_w_existing(self): def test_http_wo_creds(self): import httplib2 + conn = self._make_one() self.assertIsInstance(conn.http, httplib2.Http) @@ -151,6 +154,7 @@ def test_build_api_url_no_extra_query_params(self): def test_build_api_url_w_extra_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit + conn = self._makeMockOne() uri = conn.build_api_url('/foo', {'bar': 'baz'}) @@ -271,6 +275,7 @@ def test_api_request_wo_json_expected(self): def test_api_request_w_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit + conn = self._makeMockOne() http = conn._http = _Http( {'status': '200', 'content-type': 'application/json'}, @@ -301,6 +306,7 @@ def test_api_request_w_query_params(self): def test_api_request_w_headers(self): from six.moves.urllib.parse import urlsplit + conn = self._makeMockOne() http = conn._http = _Http( {'status': '200', 'content-type': 'application/json'}, @@ -332,6 +338,7 @@ def test_api_request_w_headers(self): def test_api_request_w_data(self): import json + DATA = {'foo': 'bar'} DATAJ = json.dumps(DATA) conn = self._makeMockOne() @@ -360,6 +367,7 @@ def test_api_request_w_data(self): def test_api_request_w_404(self): from google.cloud.exceptions import NotFound + conn = self._makeMockOne() conn._http = _Http( {'status': '404', 'content-type': 'text/plain'}, @@ -369,6 +377,7 @@ def test_api_request_w_404(self): def test_api_request_w_500(self): from google.cloud.exceptions import InternalServerError + conn = self._makeMockOne() conn._http = _Http( {'status': '500', 'content-type': 'text/plain'}, @@ -408,6 +417,7 @@ class _Http(object): def __init__(self, headers, content): from httplib2 import Response + self._response = Response(headers) self._content = content diff --git a/core/unit_tests/test_client.py b/core/unit_tests/test_client.py index dd1075aae5f8..a503891bc0c6 100644 --- a/core/unit_tests/test_client.py +++ b/core/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -27,6 +28,7 @@ class Test_ClientFactoryMixin(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.client import _ClientFactoryMixin + return _ClientFactoryMixin def test_virtual(self): @@ -39,6 +41,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.client import Client + return Client def _make_one(self, *args, **kw): @@ -106,6 +109,7 @@ class TestJSONClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.client import JSONClient + return JSONClient def _make_one(self, *args, **kw): diff --git a/core/unit_tests/test_credentials.py b/core/unit_tests/test_credentials.py index 6489dd19c4dd..53370a061494 100644 --- a/core/unit_tests/test_credentials.py +++ b/core/unit_tests/test_credentials.py @@ -21,6 +21,7 @@ class Test_get_credentials(unittest.TestCase): def _call_fut(self): from google.cloud import credentials + return credentials.get_credentials() def test_it(self): @@ -37,6 +38,7 @@ class Test_generate_signed_url(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud.credentials import generate_signed_url + return generate_signed_url(*args, **kwargs) def _generate_helper(self, response_type=None, response_disposition=None, @@ -108,6 +110,7 @@ def test_with_google_credentials(self): import time import google.auth.credentials from google.cloud.credentials import generate_signed_url + RESOURCE = '/name/path' credentials = mock.Mock(spec=google.auth.credentials.Credentials) @@ -120,6 +123,7 @@ class Test__get_signed_query_params(unittest.TestCase): def _call_fut(self, credentials, expiration, string_to_sign): from google.cloud.credentials import _get_signed_query_params + return _get_signed_query_params(credentials, expiration, string_to_sign) @@ -149,10 +153,12 @@ class Test__get_expiration_seconds(unittest.TestCase): def _call_fut(self, expiration): from google.cloud.credentials import _get_expiration_seconds + return _get_expiration_seconds(expiration) def _utc_seconds(self, when): import calendar + return int(calendar.timegm(when.timetuple())) def test_w_invalid(self): diff --git a/core/unit_tests/test_exceptions.py b/core/unit_tests/test_exceptions.py index 36cdc3f3e360..4ab41cb8d576 100644 --- a/core/unit_tests/test_exceptions.py +++ b/core/unit_tests/test_exceptions.py @@ -20,6 +20,7 @@ class Test_GoogleCloudError(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.exceptions import GoogleCloudError + return GoogleCloudError def _make_one(self, message, errors=()): @@ -51,11 +52,13 @@ class Test_make_exception(unittest.TestCase): def _call_fut(self, response, content, error_info=None, use_json=True): from google.cloud.exceptions import make_exception + return make_exception(response, content, error_info=error_info, use_json=use_json) def test_hit_w_content_as_str(self): from google.cloud.exceptions import NotFound + response = _Response(404) content = b'{"error": {"message": "Not Found"}}' exception = self._call_fut(response, content) @@ -67,6 +70,7 @@ def test_hit_w_content_as_unicode(self): import six from google.cloud._helpers import _to_bytes from google.cloud.exceptions import NotFound + error_message = u'That\u2019s not found.' expected = u'404 %s' % (error_message,) @@ -88,6 +92,7 @@ def test_hit_w_content_as_unicode_as_py3(self): import six from google.cloud._testing import _Monkey from google.cloud.exceptions import NotFound + error_message = u'That is not found.' expected = u'404 %s' % (error_message,) @@ -103,6 +108,7 @@ def test_hit_w_content_as_unicode_as_py3(self): def test_miss_w_content_as_dict(self): from google.cloud.exceptions import GoogleCloudError + ERROR = { 'domain': 'global', 'location': 'test', @@ -119,6 +125,7 @@ def test_miss_w_content_as_dict(self): def test_html_when_json_expected(self): from google.cloud.exceptions import NotFound + response = _Response(NotFound.code) content = '404 Not Found' exception = self._call_fut(response, content, use_json=True) diff --git a/core/unit_tests/test_iterator.py b/core/unit_tests/test_iterator.py index 7f10ea47f104..a7d9e4f0924d 100644 --- a/core/unit_tests/test_iterator.py +++ b/core/unit_tests/test_iterator.py @@ -19,6 +19,7 @@ class Test__do_nothing_page_start(unittest.TestCase): def _call_fut(self, iterator, page, response): from google.cloud.iterator import _do_nothing_page_start + return _do_nothing_page_start(iterator, page, response) def test_do_nothing(self): @@ -31,6 +32,7 @@ class TestPage(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.iterator import Page + return Page def _make_one(self, *args, **kw): @@ -95,6 +97,7 @@ class TestIterator(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.iterator import Iterator + return Iterator def _make_one(self, *args, **kw): @@ -238,6 +241,7 @@ class TestHTTPIterator(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.iterator import HTTPIterator + return HTTPIterator def _make_one(self, *args, **kw): @@ -471,6 +475,7 @@ class TestGAXIterator(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.iterator import GAXIterator + return GAXIterator def _make_one(self, *args, **kw): diff --git a/core/unit_tests/test_operation.py b/core/unit_tests/test_operation.py index 41c469ba336d..375484d1d60c 100644 --- a/core/unit_tests/test_operation.py +++ b/core/unit_tests/test_operation.py @@ -19,6 +19,7 @@ class Test__compute_type_url(unittest.TestCase): def _call_fut(self, klass, prefix=None): from google.cloud.operation import _compute_type_url + if prefix is None: return _compute_type_url(klass) return _compute_type_url(klass, prefix) @@ -35,6 +36,7 @@ def test_wo_prefix(self): def test_w_prefix(self): from google.protobuf.struct_pb2 import Struct + PREFIX = 'test.google-cloud-python.com' type_url = self._call_fut(Struct, PREFIX) @@ -48,6 +50,7 @@ class Test_register_type(unittest.TestCase): def _call_fut(self, klass, type_url=None): from google.cloud.operation import register_type + register_type(klass, type_url=type_url) def test_explicit(self): @@ -110,6 +113,7 @@ class TestOperation(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.operation import Operation + return Operation def _make_one(self, *args, **kw): @@ -144,6 +148,7 @@ def test_ctor_explicit(self): def test_from_pb_wo_metadata_or_kw(self): from google.longrunning import operations_pb2 + client = _Client() operation_pb = operations_pb2.Operation(name=self.OPERATION_NAME) klass = self._get_target_class() @@ -345,7 +350,6 @@ def test__update_state_metadata(self): def test__update_state_error(self): from google.longrunning import operations_pb2 from google.rpc.status_pb2 import Status - from google.cloud._testing import _Monkey operation = self._make_one(None, None) self.assertIsNone(operation.error) diff --git a/datastore/unit_tests/test__http.py b/datastore/unit_tests/test__http.py index 6515767bd0ca..d779aacedf92 100644 --- a/datastore/unit_tests/test__http.py +++ b/datastore/unit_tests/test__http.py @@ -14,6 +14,8 @@ import unittest +import mock + from google.cloud.datastore._http import _HAVE_GRPC @@ -22,6 +24,7 @@ class Test_DatastoreAPIOverHttp(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore._http import _DatastoreAPIOverHttp + return _DatastoreAPIOverHttp def _make_one(self, *args, **kw): @@ -112,6 +115,7 @@ class Test__grpc_catch_rendezvous(unittest.TestCase): def _call_fut(self): from google.cloud.datastore._http import _grpc_catch_rendezvous + return _grpc_catch_rendezvous() @staticmethod @@ -178,11 +182,10 @@ class Test_DatastoreAPIOverGRPC(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore._http import _DatastoreAPIOverGRPC + return _DatastoreAPIOverGRPC def _make_one(self, stub, connection=None, secure=True, mock_args=None): - import mock - if connection is None: connection = _Connection(None) connection.credentials = object() @@ -364,6 +367,7 @@ def _get_target_class(): def _make_key_pb(self, project, id_=1234): from google.cloud.datastore.key import Key + path_args = ('Kind',) if id_ is not None: path_args += (id_,) @@ -371,13 +375,12 @@ def _make_key_pb(self, project, id_=1234): def _make_query_pb(self, kind): from google.cloud.grpc.datastore.v1 import query_pb2 + pb = query_pb2.Query() pb.kind.add().name = kind return pb def _make_one(self, credentials=None, http=None, use_grpc=False): - import mock - with mock.patch('google.cloud.datastore._http._USE_GRPC', new=use_grpc): return self._get_target_class()(credentials=credentials, http=http) @@ -396,7 +399,6 @@ def test_default_url(self): self.assertEqual(conn.api_base_url, klass.API_BASE_URL) def test_custom_url_from_env(self): - import mock from google.cloud._http import API_BASE_URL from google.cloud.environment_vars import GCD_HOST @@ -414,8 +416,6 @@ def test_ctor_defaults(self): self.assertIsNone(conn.credentials) def test_ctor_without_grpc(self): - import mock - connections = [] return_val = object() @@ -434,8 +434,6 @@ def mock_api(connection): self.assertEqual(connections, [conn]) def test_ctor_with_grpc(self): - import mock - api_args = [] return_val = object() @@ -917,7 +915,6 @@ def test_begin_transaction(self): request.ParseFromString(cw['body']) def test_commit_wo_transaction(self): - import mock from google.cloud.grpc.datastore.v1 import datastore_pb2 from google.cloud.datastore.helpers import _new_value_pb @@ -965,7 +962,6 @@ def mock_parse(response): self.assertEqual(_parsed, [rsp_pb]) def test_commit_w_transaction(self): - import mock from google.cloud.grpc.datastore.v1 import datastore_pb2 from google.cloud.datastore.helpers import _new_value_pb @@ -1014,6 +1010,7 @@ def mock_parse(response): def test_rollback_ok(self): from google.cloud.grpc.datastore.v1 import datastore_pb2 + PROJECT = 'PROJECT' TRANSACTION = b'xact' @@ -1094,6 +1091,7 @@ class Test__parse_commit_response(unittest.TestCase): def _call_fut(self, commit_response_pb): from google.cloud.datastore._http import _parse_commit_response + return _parse_commit_response(commit_response_pb) def test_it(self): @@ -1135,6 +1133,7 @@ class Http(object): def __init__(self, headers, content): from httplib2 import Response + self._response = Response(headers) self._content = content diff --git a/datastore/unit_tests/test_batch.py b/datastore/unit_tests/test_batch.py index 7681a8fd9201..6f2cda6bfbc3 100644 --- a/datastore/unit_tests/test_batch.py +++ b/datastore/unit_tests/test_batch.py @@ -28,6 +28,7 @@ def _make_one(self, client): def test_ctor(self): from google.cloud.grpc.datastore.v1 import datastore_pb2 + _PROJECT = 'PROJECT' _NAMESPACE = 'NAMESPACE' connection = _Connection() @@ -417,6 +418,7 @@ def is_partial(self): def to_protobuf(self): from google.cloud.grpc.datastore.v1 import entity_pb2 + key = self._key = entity_pb2.Key() # Don't assign it, because it will just get ripped out # key.partition_id.project_id = self.project diff --git a/datastore/unit_tests/test_client.py b/datastore/unit_tests/test_client.py index 67a0229870c0..8481b8a759e3 100644 --- a/datastore/unit_tests/test_client.py +++ b/datastore/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -42,6 +43,7 @@ class Test__get_gcd_project(unittest.TestCase): def _call_fut(self): from google.cloud.datastore.client import _get_gcd_project + return _get_gcd_project() def test_no_value(self): @@ -65,6 +67,7 @@ class Test__determine_default_project(unittest.TestCase): def _call_fut(self, project=None): from google.cloud.datastore.client import ( _determine_default_project) + return _determine_default_project(project=project) def _determine_default_helper(self, gcd=None, fallback=None, @@ -131,6 +134,7 @@ def tearDown(self): @staticmethod def _get_target_class(): from google.cloud.datastore.client import Client + return Client def _make_one(self, project=PROJECT, namespace=None, @@ -952,6 +956,7 @@ class _NoCommitBatch(object): def __init__(self, client): from google.cloud.datastore.batch import Batch + self._client = client self._batch = Batch(client) self._batch.begin() @@ -969,6 +974,7 @@ class _NoCommitTransaction(object): def __init__(self, client, transaction_id='TRANSACTION'): from google.cloud.datastore.batch import Batch from google.cloud.datastore.transaction import Transaction + self._client = client xact = self._transaction = Transaction(client) xact._id = transaction_id @@ -1005,6 +1011,7 @@ def is_partial(self): def to_protobuf(self): from google.cloud.grpc.datastore.v1 import entity_pb2 + key = self._key = entity_pb2.Key() # Don't assign it, because it will just get ripped out # key.partition_id.project_id = self.project diff --git a/datastore/unit_tests/test_entity.py b/datastore/unit_tests/test_entity.py index 31c60a172001..4a04ac259577 100644 --- a/datastore/unit_tests/test_entity.py +++ b/datastore/unit_tests/test_entity.py @@ -24,6 +24,7 @@ class TestEntity(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.entity import Entity + return Entity def _make_one(self, key=None, exclude_from_indexes=()): @@ -53,6 +54,7 @@ def test_ctor_bad_exclude_from_indexes(self): def test___eq_____ne___w_non_entity(self): from google.cloud.datastore.key import Key + key = Key(_KIND, _ID, project=_PROJECT) entity = self._make_one(key=key) self.assertFalse(entity == object()) @@ -60,6 +62,7 @@ def test___eq_____ne___w_non_entity(self): def test___eq_____ne___w_different_keys(self): from google.cloud.datastore.key import Key + _ID1 = 1234 _ID2 = 2345 key1 = Key(_KIND, _ID1, project=_PROJECT) @@ -91,6 +94,7 @@ def test___eq_____ne___w_same_keys(self): def test___eq_____ne___w_same_keys_different_props(self): from google.cloud.datastore.key import Key + key1 = Key(_KIND, _ID, project=_PROJECT) entity1 = self._make_one(key=key1) entity1['foo'] = 'Foo' @@ -102,6 +106,7 @@ def test___eq_____ne___w_same_keys_different_props(self): def test___eq_____ne___w_same_keys_props_w_equiv_keys_as_value(self): from google.cloud.datastore.key import Key + key1 = Key(_KIND, _ID, project=_PROJECT) key2 = Key(_KIND, _ID, project=_PROJECT) entity1 = self._make_one(key=key1) @@ -113,6 +118,7 @@ def test___eq_____ne___w_same_keys_props_w_equiv_keys_as_value(self): def test___eq_____ne___w_same_keys_props_w_diff_keys_as_value(self): from google.cloud.datastore.key import Key + _ID1 = 1234 _ID2 = 2345 key1 = Key(_KIND, _ID1, project=_PROJECT) @@ -126,6 +132,7 @@ def test___eq_____ne___w_same_keys_props_w_diff_keys_as_value(self): def test___eq_____ne___w_same_keys_props_w_equiv_entities_as_value(self): from google.cloud.datastore.key import Key + key = Key(_KIND, _ID, project=_PROJECT) entity1 = self._make_one(key=key) sub1 = self._make_one() @@ -140,6 +147,7 @@ def test___eq_____ne___w_same_keys_props_w_equiv_entities_as_value(self): def test___eq_____ne___w_same_keys_props_w_diff_entities_as_value(self): from google.cloud.datastore.key import Key + key = Key(_KIND, _ID, project=_PROJECT) entity1 = self._make_one(key=key) sub1 = self._make_one() diff --git a/datastore/unit_tests/test_helpers.py b/datastore/unit_tests/test_helpers.py index f3d144e6a591..2ea54d5afe52 100644 --- a/datastore/unit_tests/test_helpers.py +++ b/datastore/unit_tests/test_helpers.py @@ -19,6 +19,7 @@ class Test__new_value_pb(unittest.TestCase): def _call_fut(self, entity_pb, name): from google.cloud.datastore.helpers import _new_value_pb + return _new_value_pb(entity_pb, name) def test_it(self): @@ -37,6 +38,7 @@ class Test__property_tuples(unittest.TestCase): def _call_fut(self, entity_pb): from google.cloud.datastore.helpers import _property_tuples + return _property_tuples(entity_pb) def test_it(self): @@ -60,6 +62,7 @@ class Test_entity_from_protobuf(unittest.TestCase): def _call_fut(self, val): from google.cloud.datastore.helpers import entity_from_protobuf + return entity_from_protobuf(val) def test_it(self): @@ -193,6 +196,7 @@ class Test_entity_to_protobuf(unittest.TestCase): def _call_fut(self, entity): from google.cloud.datastore.helpers import entity_to_protobuf + return entity_to_protobuf(entity) def _compareEntityProto(self, entity_pb1, entity_pb2): @@ -377,6 +381,7 @@ def _call_fut(self, val): def _makePB(self, project=None, namespace=None, path=()): from google.cloud.grpc.datastore.v1 import entity_pb2 + pb = entity_pb2.Key() if project is not None: pb.partition_id.project_id = project @@ -485,6 +490,7 @@ def test_long(self): def test_native_str(self): import six + name, value = self._call_fut('str') if six.PY2: self.assertEqual(name, 'blob_value') @@ -504,6 +510,7 @@ def test_unicode(self): def test_entity(self): from google.cloud.datastore.entity import Entity + entity = Entity() name, value = self._call_fut(entity) self.assertEqual(name, 'entity_value') @@ -718,6 +725,7 @@ def test_long(self): def test_native_str(self): import six + pb = self._makePB() self._call_fut(pb, 'str') if six.PY2: @@ -796,6 +804,7 @@ class Test__get_meaning(unittest.TestCase): def _call_fut(self, *args, **kwargs): from google.cloud.datastore.helpers import _get_meaning + return _get_meaning(*args, **kwargs) def test_no_meaning(self): @@ -877,6 +886,7 @@ class TestGeoPoint(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.helpers import GeoPoint + return GeoPoint def _make_one(self, *args, **kwargs): diff --git a/datastore/unit_tests/test_key.py b/datastore/unit_tests/test_key.py index ed2eb45b4cca..c699ec773885 100644 --- a/datastore/unit_tests/test_key.py +++ b/datastore/unit_tests/test_key.py @@ -22,6 +22,7 @@ class TestKey(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.key import Key + return Key def _make_one(self, *args, **kwargs): diff --git a/datastore/unit_tests/test_query.py b/datastore/unit_tests/test_query.py index 255bfa8f014f..e0a5a955beca 100644 --- a/datastore/unit_tests/test_query.py +++ b/datastore/unit_tests/test_query.py @@ -22,6 +22,7 @@ class TestQuery(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.query import Query + return Query def _make_one(self, *args, **kw): @@ -47,6 +48,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): from google.cloud.datastore.key import Key + _PROJECT = 'OTHER_PROJECT' _KIND = 'KIND' _NAMESPACE = 'OTHER_NAMESPACE' @@ -145,6 +147,7 @@ def _assign(val): def test_ancestor_setter_w_key(self): from google.cloud.datastore.key import Key + _NAME = u'NAME' key = Key('KIND', 123, project=self._PROJECT) query = self._make_one(self._makeClient()) @@ -154,6 +157,7 @@ def test_ancestor_setter_w_key(self): def test_ancestor_deleter_w_key(self): from google.cloud.datastore.key import Key + key = Key('KIND', 123, project=self._PROJECT) query = self._make_one(client=self._makeClient(), ancestor=key) del query.ancestor @@ -185,6 +189,7 @@ def test_add_filter_w_all_operators(self): def test_add_filter_w_known_operator_and_entity(self): from google.cloud.datastore.entity import Entity + query = self._make_one(self._makeClient()) other = Entity() other['firstname'] = u'John' @@ -200,6 +205,7 @@ def test_add_filter_w_whitespace_property_name(self): def test_add_filter___key__valid_key(self): from google.cloud.datastore.key import Key + query = self._make_one(self._makeClient()) key = Key('Foo', project=self._PROJECT) query.add_filter('__key__', '=', key) @@ -207,6 +213,7 @@ def test_add_filter___key__valid_key(self): def test_filter___key__not_equal_operator(self): from google.cloud.datastore.key import Key + key = Key('Foo', project=self._PROJECT) query = self._make_one(self._makeClient()) query.add_filter('__key__', '<', key) @@ -343,6 +350,7 @@ class TestIterator(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.query import Iterator + return Iterator def _make_one(self, *args, **kw): @@ -519,6 +527,7 @@ class Test__item_to_entity(unittest.TestCase): def _call_fut(self, iterator, entity_pb): from google.cloud.datastore.query import _item_to_entity + return _item_to_entity(iterator, entity_pb) def test_it(self): @@ -543,6 +552,7 @@ class Test__pb_from_query(unittest.TestCase): def _call_fut(self, query): from google.cloud.datastore.query import _pb_from_query + return _pb_from_query(query) def test_empty(self): diff --git a/datastore/unit_tests/test_transaction.py b/datastore/unit_tests/test_transaction.py index 6b6b005a6fa3..7aa295bf7fca 100644 --- a/datastore/unit_tests/test_transaction.py +++ b/datastore/unit_tests/test_transaction.py @@ -20,6 +20,7 @@ class TestTransaction(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.transaction import Transaction + return Transaction def _make_one(self, client, **kw): @@ -220,6 +221,7 @@ class _Entity(dict): def __init__(self): super(_Entity, self).__init__() from google.cloud.datastore.key import Key + self.key = Key('KIND', project='PROJECT') @@ -246,6 +248,7 @@ class _NoCommitBatch(object): def __init__(self, client): from google.cloud.datastore.batch import Batch + self._client = client self._batch = Batch(client) diff --git a/dns/unit_tests/test_changes.py b/dns/unit_tests/test_changes.py index 1543bbfb1921..2eb8390eddf7 100644 --- a/dns/unit_tests/test_changes.py +++ b/dns/unit_tests/test_changes.py @@ -23,6 +23,7 @@ class TestChanges(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.dns.changes import Changes + return Changes def _make_one(self, *args, **kw): @@ -31,10 +32,12 @@ def _make_one(self, *args, **kw): def _setUpConstants(self): from google.cloud._helpers import UTC from google.cloud._helpers import _NOW + self.WHEN = _NOW().replace(tzinfo=UTC) def _makeResource(self): from google.cloud._helpers import _datetime_to_rfc3339 + when_str = _datetime_to_rfc3339(self.WHEN) return { 'kind': 'dns#change', @@ -57,6 +60,7 @@ def _makeResource(self): def _verifyResourceProperties(self, changes, resource, zone): from google.cloud._helpers import _rfc3339_to_datetime + self.assertEqual(changes.name, resource['id']) started = _rfc3339_to_datetime(resource['startTime']) self.assertEqual(changes.started, started) @@ -135,6 +139,7 @@ def test_add_record_set_invalid_value(self): def test_add_record_set(self): from google.cloud.dns.resource_record_set import ResourceRecordSet + zone = _Zone() changes = self._make_one(zone) rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600, @@ -151,6 +156,7 @@ def test_delete_record_set_invalid_value(self): def test_delete_record_set(self): from google.cloud.dns.resource_record_set import ResourceRecordSet + zone = _Zone() changes = self._make_one(zone) rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600, @@ -173,6 +179,7 @@ def test_create_wo_additions_or_deletions(self): def test_create_w_bound_client(self): from google.cloud.dns.resource_record_set import ResourceRecordSet + self._setUpConstants() RESOURCE = self._makeResource() PATH = 'projects/%s/managedZones/%s/changes' % ( @@ -201,6 +208,7 @@ def test_create_w_bound_client(self): def test_create_w_alternate_client(self): from google.cloud.dns.resource_record_set import ResourceRecordSet + self._setUpConstants() RESOURCE = self._makeResource() PATH = 'projects/%s/managedZones/%s/changes' % ( @@ -334,6 +342,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: diff --git a/dns/unit_tests/test_client.py b/dns/unit_tests/test_client.py index e633207d3a25..09b861e15cb6 100644 --- a/dns/unit_tests/test_client.py +++ b/dns/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -30,6 +31,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.dns.client import Client + return Client def _make_one(self, *args, **kw): @@ -37,6 +39,7 @@ def _make_one(self, *args, **kw): def test_ctor(self): from google.cloud.dns.connection import Connection + creds = _make_credentials() http = object() client = self._make_one(project=self.PROJECT, credentials=creds, @@ -116,6 +119,7 @@ def test_quotas_w_kind_key(self): def test_list_zones_defaults(self): import six from google.cloud.dns.zone import ManagedZone + ID_1 = '123' ZONE_1 = 'zone_one' DNS_1 = 'one.example.com' @@ -162,6 +166,7 @@ def test_list_zones_defaults(self): def test_list_zones_explicit(self): import six from google.cloud.dns.zone import ManagedZone + ID_1 = '123' ZONE_1 = 'zone_one' DNS_1 = 'one.example.com' @@ -208,6 +213,7 @@ def test_list_zones_explicit(self): def test_zone_explicit(self): from google.cloud.dns.zone import ManagedZone + DESCRIPTION = 'DESCRIPTION' DNS_NAME = 'test.example.com' creds = _make_credentials() @@ -221,6 +227,7 @@ def test_zone_explicit(self): def test_zone_w_dns_name_wo_description(self): from google.cloud.dns.zone import ManagedZone + DNS_NAME = 'test.example.com' creds = _make_credentials() client = self._make_one(self.PROJECT, creds) @@ -233,6 +240,7 @@ def test_zone_w_dns_name_wo_description(self): def test_zone_wo_dns_name(self): from google.cloud.dns.zone import ManagedZone + creds = _make_credentials() client = self._make_one(self.PROJECT, creds) zone = client.zone(self.ZONE_NAME) diff --git a/dns/unit_tests/test_connection.py b/dns/unit_tests/test_connection.py index 88f1aa93b577..2878bacf2ce6 100644 --- a/dns/unit_tests/test_connection.py +++ b/dns/unit_tests/test_connection.py @@ -20,6 +20,7 @@ class TestConnection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.dns.connection import Connection + return Connection def _make_one(self, *args, **kw): @@ -38,6 +39,7 @@ def test_build_api_url_no_extra_query_params(self): def test_build_api_url_w_extra_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) diff --git a/dns/unit_tests/test_resource_record_set.py b/dns/unit_tests/test_resource_record_set.py index 6b71bd5cea67..a8760a8bbf09 100644 --- a/dns/unit_tests/test_resource_record_set.py +++ b/dns/unit_tests/test_resource_record_set.py @@ -20,6 +20,7 @@ class TestResourceRecordSet(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.dns.resource_record_set import ResourceRecordSet + return ResourceRecordSet def _make_one(self, *args, **kw): diff --git a/dns/unit_tests/test_zone.py b/dns/unit_tests/test_zone.py index c02c231f7b9d..bf16f2fde010 100644 --- a/dns/unit_tests/test_zone.py +++ b/dns/unit_tests/test_zone.py @@ -24,6 +24,7 @@ class TestManagedZone(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.dns.zone import ManagedZone + return ManagedZone def _make_one(self, *args, **kw): @@ -62,7 +63,6 @@ def _makeResource(self): } def _verifyReadonlyResourceProperties(self, zone, resource): - self.assertEqual(zone.zone_id, resource.get('id')) if 'creationTime' in resource: @@ -76,7 +76,6 @@ def _verifyReadonlyResourceProperties(self, zone, resource): self.assertIsNone(zone.name_servers) def _verifyResourceProperties(self, zone, resource): - self._verifyReadonlyResourceProperties(zone, resource) self.assertEqual(zone.name, resource.get('name')) @@ -186,6 +185,7 @@ def test_name_server_set_setter(self): def test_resource_record_set(self): from google.cloud.dns.resource_record_set import ResourceRecordSet + RRS_NAME = 'other.example.com' RRS_TYPE = 'CNAME' TTL = 3600 @@ -202,6 +202,7 @@ def test_resource_record_set(self): def test_changes(self): from google.cloud.dns.changes import Changes + client = _Client(self.PROJECT) zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) changes = zone.changes() @@ -262,6 +263,7 @@ def test_create_w_alternate_client(self): def test_create_wo_dns_name_or_description(self): from google.cloud.exceptions import BadRequest + PATH = 'projects/%s/managedZones' % self.PROJECT _requested = [] @@ -412,6 +414,7 @@ def test_delete_w_alternate_client(self): def test_list_resource_record_sets_defaults(self): import six from google.cloud.dns.resource_record_set import ResourceRecordSet + PATH = 'projects/%s/managedZones/%s/rrsets' % ( self.PROJECT, self.ZONE_NAME) TOKEN = 'TOKEN' @@ -465,6 +468,7 @@ def test_list_resource_record_sets_defaults(self): def test_list_resource_record_sets_explicit(self): import six from google.cloud.dns.resource_record_set import ResourceRecordSet + PATH = 'projects/%s/managedZones/%s/rrsets' % ( self.PROJECT, self.ZONE_NAME) TOKEN = 'TOKEN' @@ -684,6 +688,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: diff --git a/error_reporting/unit_tests/test_client.py b/error_reporting/unit_tests/test_client.py index 2750cd20dba4..c1b105990f0d 100644 --- a/error_reporting/unit_tests/test_client.py +++ b/error_reporting/unit_tests/test_client.py @@ -20,6 +20,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -28,10 +29,12 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.error_reporting.client import Client + return Client def _getHttpContext(self): from google.cloud.error_reporting.client import HTTPContext + return HTTPContext def _make_one(self, *args, **kw): diff --git a/error_reporting/unit_tests/test_util.py b/error_reporting/unit_tests/test_util.py index fcaf9167a061..fa48ba14c649 100644 --- a/error_reporting/unit_tests/test_util.py +++ b/error_reporting/unit_tests/test_util.py @@ -19,6 +19,7 @@ class Test_build_flask_context(unittest.TestCase): def _call_fut(self, request): from google.cloud.error_reporting.util import build_flask_context + return build_flask_context(request) def test_flask_helper(self): diff --git a/language/unit_tests/test_client.py b/language/unit_tests/test_client.py index 7eb04bcf1b8e..56b6aa22b235 100644 --- a/language/unit_tests/test_client.py +++ b/language/unit_tests/test_client.py @@ -28,6 +28,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.client import Client + return Client def _make_one(self, *args, **kw): diff --git a/language/unit_tests/test_connection.py b/language/unit_tests/test_connection.py index 534582002292..4b5694a437ff 100644 --- a/language/unit_tests/test_connection.py +++ b/language/unit_tests/test_connection.py @@ -20,6 +20,7 @@ class TestConnection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.connection import Connection + return Connection def _make_one(self, *args, **kw): diff --git a/language/unit_tests/test_document.py b/language/unit_tests/test_document.py index 48ebfd1c1188..ab345ce1bb82 100644 --- a/language/unit_tests/test_document.py +++ b/language/unit_tests/test_document.py @@ -110,6 +110,7 @@ class TestDocument(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.document import Document + return Document def _make_one(self, *args, **kw): diff --git a/language/unit_tests/test_entity.py b/language/unit_tests/test_entity.py index b595220f00bf..77562e39e612 100644 --- a/language/unit_tests/test_entity.py +++ b/language/unit_tests/test_entity.py @@ -20,6 +20,7 @@ class TestEntity(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.entity import Entity + return Entity def _make_one(self, *args, **kw): diff --git a/language/unit_tests/test_sentiment.py b/language/unit_tests/test_sentiment.py index 37cc52df954d..b02254ed7592 100644 --- a/language/unit_tests/test_sentiment.py +++ b/language/unit_tests/test_sentiment.py @@ -20,6 +20,7 @@ class TestSentiment(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.sentiment import Sentiment + return Sentiment def _make_one(self, *args, **kw): diff --git a/language/unit_tests/test_syntax.py b/language/unit_tests/test_syntax.py index b09bc2ce7004..369f9988720c 100644 --- a/language/unit_tests/test_syntax.py +++ b/language/unit_tests/test_syntax.py @@ -20,6 +20,7 @@ class TestPartOfSpeech(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.syntax import PartOfSpeech + return PartOfSpeech def test_reverse(self): @@ -39,6 +40,7 @@ class TestToken(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.syntax import Token + return Token def _make_one(self, *args, **kw): @@ -100,6 +102,7 @@ class TestSentence(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.language.syntax import Sentence + return Sentence def _make_one(self, *args, **kw): @@ -129,6 +132,7 @@ def test_from_api_repr(self): def test_from_api_repr_with_sentiment(self): from google.cloud.language.sentiment import Sentiment + klass = self._get_target_class() content = 'All the pretty horses.' begin = -1 diff --git a/logging/unit_tests/test__gax.py b/logging/unit_tests/test__gax.py index 9020c44236e0..4d150535db22 100644 --- a/logging/unit_tests/test__gax.py +++ b/logging/unit_tests/test__gax.py @@ -32,6 +32,7 @@ def _make_credentials(): # pylint: disable=redefined-outer-name import google.auth.credentials # pylint: enable=redefined-outer-name + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -333,6 +334,7 @@ def test_list_entries_with_extra_properties(self): def test_write_entries_single(self): from google.cloud.grpc.logging.v2.log_entry_pb2 import LogEntry + TEXT = 'TEXT' ENTRY = { 'logName': self.LOG_PATH, @@ -367,6 +369,7 @@ def test_write_entries_w_extra_properties(self): from google.logging.type.log_severity_pb2 import WARNING from google.cloud.grpc.logging.v2.log_entry_pb2 import LogEntry from google.cloud._helpers import UTC, _pb_timestamp_to_datetime + NOW = datetime.utcnow().replace(tzinfo=UTC) TEXT = 'TEXT' SEVERITY = 'WARNING' @@ -462,7 +465,9 @@ def _write_entries_multiple_helper(self, json_payload, json_struct_pb): from google.logging.type.log_severity_pb2 import WARNING from google.cloud.grpc.logging.v2.log_entry_pb2 import LogEntry from google.protobuf.any_pb2 import Any - from google.cloud._helpers import _datetime_to_rfc3339, UTC + from google.cloud._helpers import _datetime_to_rfc3339 + from google.cloud._helpers import UTC + TEXT = 'TEXT' NOW = datetime.datetime.utcnow().replace(tzinfo=UTC) TIMESTAMP_TYPE_URL = 'type.googleapis.com/google.protobuf.Timestamp' @@ -616,6 +621,7 @@ class Test_SinksAPI(_Base, unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._gax import _SinksAPI + return _SinksAPI def test_ctor(self): @@ -700,6 +706,7 @@ def test_list_sinks_w_paging(self): def test_sink_create_error(self): from google.gax.errors import GaxError + gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -710,6 +717,7 @@ def test_sink_create_error(self): def test_sink_create_conflict(self): from google.cloud.exceptions import Conflict + gax_api = _GAXSinksAPI(_create_sink_conflict=True) api = self._make_one(gax_api, None) @@ -720,6 +728,7 @@ def test_sink_create_conflict(self): def test_sink_create_ok(self): from google.cloud.grpc.logging.v2.logging_config_pb2 import LogSink + gax_api = _GAXSinksAPI() api = self._make_one(gax_api, None) @@ -737,6 +746,7 @@ def test_sink_create_ok(self): def test_sink_get_error(self): from google.cloud.exceptions import NotFound + gax_api = _GAXSinksAPI() api = self._make_one(gax_api, None) @@ -745,6 +755,7 @@ def test_sink_get_error(self): def test_sink_get_miss(self): from google.gax.errors import GaxError + gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -775,6 +786,7 @@ def test_sink_get_hit(self): def test_sink_update_error(self): from google.gax.errors import GaxError + gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -785,6 +797,7 @@ def test_sink_update_error(self): def test_sink_update_miss(self): from google.cloud.exceptions import NotFound + gax_api = _GAXSinksAPI() api = self._make_one(gax_api, None) @@ -816,6 +829,7 @@ def test_sink_update_hit(self): def test_sink_delete_error(self): from google.gax.errors import GaxError + gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -824,6 +838,7 @@ def test_sink_delete_error(self): def test_sink_delete_miss(self): from google.cloud.exceptions import NotFound + gax_api = _GAXSinksAPI(_sink_not_found=True) api = self._make_one(gax_api, None) @@ -850,6 +865,7 @@ class Test_MetricsAPI(_Base, unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._gax import _MetricsAPI + return _MetricsAPI def test_ctor(self): @@ -932,6 +948,7 @@ def test_list_metrics_w_paging(self): def test_metric_create_error(self): from google.gax.errors import GaxError + gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -942,6 +959,7 @@ def test_metric_create_error(self): def test_metric_create_conflict(self): from google.cloud.exceptions import Conflict + gax_api = _GAXMetricsAPI(_create_log_metric_conflict=True) api = self._make_one(gax_api, None) @@ -952,6 +970,7 @@ def test_metric_create_conflict(self): def test_metric_create_ok(self): from google.cloud.grpc.logging.v2.logging_metrics_pb2 import LogMetric + gax_api = _GAXMetricsAPI() api = self._make_one(gax_api, None) @@ -969,6 +988,7 @@ def test_metric_create_ok(self): def test_metric_get_error(self): from google.cloud.exceptions import NotFound + gax_api = _GAXMetricsAPI() api = self._make_one(gax_api, None) @@ -977,6 +997,7 @@ def test_metric_get_error(self): def test_metric_get_miss(self): from google.gax.errors import GaxError + gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -1007,6 +1028,7 @@ def test_metric_get_hit(self): def test_metric_update_error(self): from google.gax.errors import GaxError + gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -1017,6 +1039,7 @@ def test_metric_update_error(self): def test_metric_update_miss(self): from google.cloud.exceptions import NotFound + gax_api = _GAXMetricsAPI() api = self._make_one(gax_api, None) @@ -1048,6 +1071,7 @@ def test_metric_update_hit(self): def test_metric_delete_error(self): from google.gax.errors import GaxError + gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._make_one(gax_api, None) @@ -1056,6 +1080,7 @@ def test_metric_delete_error(self): def test_metric_delete_miss(self): from google.cloud.exceptions import NotFound + gax_api = _GAXMetricsAPI(_log_metric_not_found=True) api = self._make_one(gax_api, None) @@ -1078,6 +1103,7 @@ class Test_make_gax_logging_api(unittest.TestCase): def _call_fut(self, client): from google.cloud.logging._gax import make_gax_logging_api + return make_gax_logging_api(client) def test_it(self): @@ -1124,6 +1150,7 @@ class Test_make_gax_metrics_api(unittest.TestCase): def _call_fut(self, client): from google.cloud.logging._gax import make_gax_metrics_api + return make_gax_metrics_api(client) def test_it(self): @@ -1170,6 +1197,7 @@ class Test_make_gax_sinks_api(unittest.TestCase): def _call_fut(self, client): from google.cloud.logging._gax import make_gax_sinks_api + return make_gax_sinks_api(client) def test_it(self): @@ -1230,6 +1258,7 @@ def write_log_entries(self, entries, log_name, resource, labels, def delete_log(self, log_name, options): from google.gax.errors import GaxError + self._delete_log_called_with = log_name, options if self._random_gax_error: raise GaxError('error') @@ -1248,6 +1277,7 @@ def list_sinks(self, parent, page_size, options): def create_sink(self, parent, sink, options): from google.gax.errors import GaxError + self._create_sink_called_with = parent, sink, options if self._random_gax_error: raise GaxError('error') @@ -1256,6 +1286,7 @@ def create_sink(self, parent, sink, options): def get_sink(self, sink_name, options): from google.gax.errors import GaxError + self._get_sink_called_with = sink_name, options if self._random_gax_error: raise GaxError('error') @@ -1266,6 +1297,7 @@ def get_sink(self, sink_name, options): def update_sink(self, sink_name, sink, options=None): from google.gax.errors import GaxError + self._update_sink_called_with = sink_name, sink, options if self._random_gax_error: raise GaxError('error') @@ -1276,6 +1308,7 @@ def update_sink(self, sink_name, sink, options=None): def delete_sink(self, sink_name, options=None): from google.gax.errors import GaxError + self._delete_sink_called_with = sink_name, options if self._random_gax_error: raise GaxError('error') @@ -1294,6 +1327,7 @@ def list_log_metrics(self, parent, page_size, options): def create_log_metric(self, parent, metric, options): from google.gax.errors import GaxError + self._create_log_metric_called_with = parent, metric, options if self._random_gax_error: raise GaxError('error') @@ -1302,6 +1336,7 @@ def create_log_metric(self, parent, metric, options): def get_log_metric(self, metric_name, options): from google.gax.errors import GaxError + self._get_log_metric_called_with = metric_name, options if self._random_gax_error: raise GaxError('error') @@ -1312,6 +1347,7 @@ def get_log_metric(self, metric_name, options): def update_log_metric(self, metric_name, metric, options=None): from google.gax.errors import GaxError + self._update_log_metric_called_with = metric_name, metric, options if self._random_gax_error: raise GaxError('error') @@ -1322,6 +1358,7 @@ def update_log_metric(self, metric_name, metric, options=None): def delete_log_metric(self, metric_name, options=None): from google.gax.errors import GaxError + self._delete_log_metric_called_with = metric_name, options if self._random_gax_error: raise GaxError('error') diff --git a/logging/unit_tests/test__helpers.py b/logging/unit_tests/test__helpers.py index 8f8e43f36734..7cc2d392514c 100644 --- a/logging/unit_tests/test__helpers.py +++ b/logging/unit_tests/test__helpers.py @@ -21,6 +21,7 @@ class Test_entry_from_resource(unittest.TestCase): @staticmethod def _call_fut(resource, client, loggers): from google.cloud.logging._helpers import entry_from_resource + return entry_from_resource(resource, client, loggers) def test_unknown_type(self): diff --git a/logging/unit_tests/test__http.py b/logging/unit_tests/test__http.py index bfc8d7981e46..953291dad1e9 100644 --- a/logging/unit_tests/test__http.py +++ b/logging/unit_tests/test__http.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -30,6 +31,7 @@ class TestConnection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._http import Connection + return Connection def _make_one(self, *args, **kw): @@ -52,6 +54,7 @@ class Test_LoggingAPI(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._http import _LoggingAPI + return _LoggingAPI def _make_one(self, *args, **kw): @@ -302,6 +305,7 @@ class Test_SinksAPI(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._http import _SinksAPI + return _SinksAPI def _make_one(self, *args, **kw): @@ -400,6 +404,7 @@ def test_list_sinks_w_paging(self): def test_sink_create_conflict(self): from google.cloud.exceptions import Conflict + SENT = { 'name': self.SINK_NAME, 'filter': self.FILTER, @@ -440,6 +445,7 @@ def test_sink_create_ok(self): def test_sink_get_miss(self): from google.cloud.exceptions import NotFound + conn = _Connection() client = _Client(conn) api = self._make_one(client) @@ -470,6 +476,7 @@ def test_sink_get_hit(self): def test_sink_update_miss(self): from google.cloud.exceptions import NotFound + SENT = { 'name': self.SINK_NAME, 'filter': self.FILTER, @@ -509,6 +516,7 @@ def test_sink_update_hit(self): def test_sink_delete_miss(self): from google.cloud.exceptions import NotFound + conn = _Connection() client = _Client(conn) api = self._make_one(client) @@ -544,6 +552,7 @@ class Test_MetricsAPI(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging._http import _MetricsAPI + return _MetricsAPI def _make_one(self, *args, **kw): @@ -633,6 +642,7 @@ def test_list_metrics_w_paging(self): def test_metric_create_conflict(self): from google.cloud.exceptions import Conflict + SENT = { 'name': self.METRIC_NAME, 'filter': self.FILTER, @@ -673,6 +683,7 @@ def test_metric_create_ok(self): def test_metric_get_miss(self): from google.cloud.exceptions import NotFound + conn = _Connection() client = _Client(conn) api = self._make_one(client) @@ -703,6 +714,7 @@ def test_metric_get_hit(self): def test_metric_update_miss(self): from google.cloud.exceptions import NotFound + SENT = { 'name': self.METRIC_NAME, 'filter': self.FILTER, @@ -742,6 +754,7 @@ def test_metric_update_hit(self): def test_metric_delete_miss(self): from google.cloud.exceptions import NotFound + conn = _Connection() client = _Client(conn) api = self._make_one(client) @@ -776,6 +789,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import Conflict from google.cloud.exceptions import NotFound + self._called_with = kw if self._raise_conflict: raise Conflict('oops') @@ -788,6 +802,7 @@ def api_request(self, **kw): def _datetime_to_rfc3339_w_nanos(value): from google.cloud._helpers import _RFC3339_NO_FRACTION + no_fraction = value.strftime(_RFC3339_NO_FRACTION) return '%s.%09dZ' % (no_fraction, value.microsecond * 1000) diff --git a/logging/unit_tests/test_client.py b/logging/unit_tests/test_client.py index 0e215ad1f510..85d464a83af0 100644 --- a/logging/unit_tests/test_client.py +++ b/logging/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -36,6 +37,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.client import Client + return Client def _make_one(self, *args, **kw): @@ -182,6 +184,7 @@ def make_api(client_obj): def test_logger(self): from google.cloud.logging.logger import Logger + creds = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=creds) logger = client.logger(self.LOGGER_NAME) @@ -322,6 +325,7 @@ def test_list_entries_explicit(self): def test_sink_defaults(self): from google.cloud.logging.sink import Sink + creds = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=creds) sink = client.sink(self.SINK_NAME) @@ -334,6 +338,7 @@ def test_sink_defaults(self): def test_sink_explicit(self): from google.cloud.logging.sink import Sink + creds = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=creds) sink = client.sink(self.SINK_NAME, self.FILTER, self.DESTINATION_URI) @@ -440,6 +445,7 @@ def test_list_sinks_with_paging(self): def test_metric_defaults(self): from google.cloud.logging.metric import Metric + creds = _make_credentials() client_obj = self._make_one(project=self.PROJECT, credentials=creds) @@ -453,6 +459,7 @@ def test_metric_defaults(self): def test_metric_explicit(self): from google.cloud.logging.metric import Metric + creds = _make_credentials() client_obj = self._make_one(project=self.PROJECT, credentials=creds) diff --git a/logging/unit_tests/test_entries.py b/logging/unit_tests/test_entries.py index 0ae4a5e112f9..d39d72a27af8 100644 --- a/logging/unit_tests/test_entries.py +++ b/logging/unit_tests/test_entries.py @@ -19,6 +19,7 @@ class Test_logger_name_from_path(unittest.TestCase): def _call_fut(self, path): from google.cloud.logging.entries import logger_name_from_path + return logger_name_from_path(path) def test_w_simple_name(self): @@ -67,6 +68,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): import datetime + PAYLOAD = 'PAYLOAD' IID = 'IID' TIMESTAMP = datetime.datetime.now() @@ -120,6 +122,7 @@ def test_from_api_repr_missing_data_no_loggers(self): def test_from_api_repr_w_loggers_no_logger_match(self): from datetime import datetime from google.cloud._helpers import UTC + klass = self._get_target_class() client = _Client(self.PROJECT) PAYLOAD = 'PAYLOAD' @@ -164,6 +167,7 @@ def test_from_api_repr_w_loggers_no_logger_match(self): def test_from_api_repr_w_loggers_w_logger_match(self): from datetime import datetime from google.cloud._helpers import UTC + client = _Client(self.PROJECT) PAYLOAD = 'PAYLOAD' IID = 'IID' @@ -197,6 +201,7 @@ class TestProtobufEntry(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.entries import ProtobufEntry + return ProtobufEntry def _make_one(self, *args, **kw): @@ -206,6 +211,7 @@ def test_parse_message(self): import json from google.protobuf.json_format import MessageToJson from google.protobuf.struct_pb2 import Struct, Value + LOGGER = object() message = Struct(fields={'foo': Value(bool_value=False)}) with_true = Struct(fields={'foo': Value(bool_value=True)}) @@ -217,6 +223,7 @@ def test_parse_message(self): def _datetime_to_rfc3339_w_nanos(value): from google.cloud._helpers import _RFC3339_NO_FRACTION + no_fraction = value.strftime(_RFC3339_NO_FRACTION) return '%s.%09dZ' % (no_fraction, value.microsecond * 1000) diff --git a/logging/unit_tests/test_logger.py b/logging/unit_tests/test_logger.py index 48edaf0ed5a4..31bad0402d86 100644 --- a/logging/unit_tests/test_logger.py +++ b/logging/unit_tests/test_logger.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -30,6 +31,7 @@ class TestLogger(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.logger import Logger + return Logger def _make_one(self, *args, **kw): @@ -64,6 +66,7 @@ def test_ctor_explicit(self): def test_batch_w_bound_client(self): from google.cloud.logging.logger import Batch + conn = object() client = _Client(self.PROJECT, conn) logger = self._make_one(self.LOGGER_NAME, client=client) @@ -74,6 +77,7 @@ def test_batch_w_bound_client(self): def test_batch_w_alternate_client(self): from google.cloud.logging.logger import Batch + conn1 = object() conn2 = object() client1 = _Client(self.PROJECT, conn1) @@ -268,6 +272,7 @@ def test_log_struct_w_explicit_client_labels_severity_httpreq(self): def test_log_struct_w_timestamp(self): import datetime + STRUCT = {'message': 'MESSAGE', 'weather': 'cloudy'} TIMESTAMP = datetime.datetime(2016, 12, 31, 0, 1, 2, 999999) ENTRIES = [{ @@ -292,6 +297,7 @@ def test_log_proto_w_implicit_client(self): import json from google.protobuf.json_format import MessageToJson from google.protobuf.struct_pb2 import Struct, Value + message = Struct(fields={'foo': Value(bool_value=True)}) ENTRIES = [{ 'logName': 'projects/%s/logs/%s' % ( @@ -314,6 +320,7 @@ def test_log_proto_w_default_labels(self): import json from google.protobuf.json_format import MessageToJson from google.protobuf.struct_pb2 import Struct, Value + message = Struct(fields={'foo': Value(bool_value=True)}) DEFAULT_LABELS = {'foo': 'spam'} ENTRIES = [{ @@ -338,7 +345,9 @@ def test_log_proto_w_default_labels(self): def test_log_proto_w_explicit_client_labels_severity_httpreq(self): import json from google.protobuf.json_format import MessageToJson - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + message = Struct(fields={'foo': Value(bool_value=True)}) DEFAULT_LABELS = {'foo': 'spam'} LABELS = {'foo': 'bar', 'baz': 'qux'} @@ -381,7 +390,9 @@ def test_log_proto_w_timestamp(self): import json import datetime from google.protobuf.json_format import MessageToJson - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + message = Struct(fields={'foo': Value(bool_value=True)}) TIMESTAMP = datetime.datetime(2016, 12, 31, 0, 1, 2, 999999) ENTRIES = [{ @@ -504,6 +515,7 @@ class TestBatch(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.logger import Batch + return Batch def _make_one(self, *args, **kwargs): @@ -528,6 +540,7 @@ def test_log_text_defaults(self): def test_log_text_explicit(self): import datetime + TEXT = 'This is the entry text' LABELS = {'foo': 'bar', 'baz': 'qux'} IID = 'IID' @@ -562,6 +575,7 @@ def test_log_struct_defaults(self): def test_log_struct_explicit(self): import datetime + STRUCT = {'message': 'Message text', 'weather': 'partly cloudy'} LABELS = {'foo': 'bar', 'baz': 'qux'} IID = 'IID' @@ -586,7 +600,9 @@ def test_log_struct_explicit(self): [('struct', STRUCT, LABELS, IID, SEVERITY, REQUEST, TIMESTAMP)]) def test_log_proto_defaults(self): - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + message = Struct(fields={'foo': Value(bool_value=True)}) client = _Client(project=self.PROJECT, connection=_make_credentials()) logger = _Logger() @@ -597,7 +613,9 @@ def test_log_proto_defaults(self): def test_log_proto_explicit(self): import datetime - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + message = Struct(fields={'foo': Value(bool_value=True)}) LABELS = {'foo': 'bar', 'baz': 'qux'} IID = 'IID' @@ -633,7 +651,9 @@ def test_commit_w_bound_client(self): import json import datetime from google.protobuf.json_format import MessageToJson - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + TEXT = 'This is the entry text' STRUCT = {'message': TEXT, 'weather': 'partly cloudy'} message = Struct(fields={'foo': Value(bool_value=True)}) @@ -669,8 +689,10 @@ def test_commit_w_bound_client(self): def test_commit_w_alternate_client(self): import json from google.protobuf.json_format import MessageToJson - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value from google.cloud.logging.logger import Logger + TEXT = 'This is the entry text' STRUCT = {'message': TEXT, 'weather': 'partly cloudy'} message = Struct(fields={'foo': Value(bool_value=True)}) @@ -713,8 +735,10 @@ def test_commit_w_alternate_client(self): def test_context_mgr_success(self): import json from google.protobuf.json_format import MessageToJson - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value from google.cloud.logging.logger import Logger + TEXT = 'This is the entry text' STRUCT = {'message': TEXT, 'weather': 'partly cloudy'} message = Struct(fields={'foo': Value(bool_value=True)}) @@ -754,7 +778,9 @@ def test_context_mgr_success(self): def test_context_mgr_failure(self): import datetime - from google.protobuf.struct_pb2 import Struct, Value + from google.protobuf.struct_pb2 import Struct + from google.protobuf.struct_pb2 import Value + TEXT = 'This is the entry text' STRUCT = {'message': TEXT, 'weather': 'partly cloudy'} LABELS = {'foo': 'bar', 'baz': 'qux'} diff --git a/logging/unit_tests/test_metric.py b/logging/unit_tests/test_metric.py index 5f4b05c054d2..12bf250ca2aa 100644 --- a/logging/unit_tests/test_metric.py +++ b/logging/unit_tests/test_metric.py @@ -25,6 +25,7 @@ class TestMetric(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.metric import Metric + return Metric def _make_one(self, *args, **kw): @@ -238,6 +239,7 @@ def metric_create(self, project, metric_name, filter_, description): def metric_get(self, project, metric_name): from google.cloud.exceptions import NotFound + self._metric_get_called_with = (project, metric_name) try: return self._metric_get_response diff --git a/logging/unit_tests/test_sink.py b/logging/unit_tests/test_sink.py index ca2a7a6df9c4..15acc46ce12d 100644 --- a/logging/unit_tests/test_sink.py +++ b/logging/unit_tests/test_sink.py @@ -25,6 +25,7 @@ class TestSink(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.logging.sink import Sink + return Sink def _make_one(self, *args, **kw): @@ -260,6 +261,7 @@ def sink_create(self, project, sink_name, filter_, destination): def sink_get(self, project, sink_name): from google.cloud.exceptions import NotFound + self._sink_get_called_with = (project, sink_name) try: return self._sink_get_response diff --git a/pubsub/unit_tests/test__gax.py b/pubsub/unit_tests/test__gax.py index d7e3409a18e6..cb3bb0ee7c07 100644 --- a/pubsub/unit_tests/test__gax.py +++ b/pubsub/unit_tests/test__gax.py @@ -424,6 +424,7 @@ class Test_SubscriberAPI(_Base, unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.pubsub._gax import _SubscriberAPI + return _SubscriberAPI def test_ctor(self): diff --git a/resource_manager/unit_tests/test_client.py b/resource_manager/unit_tests/test_client.py index 3d19c6d717dc..95c7c90cff49 100644 --- a/resource_manager/unit_tests/test_client.py +++ b/resource_manager/unit_tests/test_client.py @@ -19,6 +19,7 @@ def _make_credentials(): import google.auth.credentials + return mock.Mock(spec=google.auth.credentials.Credentials) @@ -27,6 +28,7 @@ class TestClient(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.resource_manager.client import Client + return Client def _make_one(self, *args, **kw): diff --git a/resource_manager/unit_tests/test_connection.py b/resource_manager/unit_tests/test_connection.py index 41fef83b585b..5f967b262ebf 100644 --- a/resource_manager/unit_tests/test_connection.py +++ b/resource_manager/unit_tests/test_connection.py @@ -20,6 +20,7 @@ class TestConnection(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.resource_manager.connection import Connection + return Connection def _make_one(self, *args, **kw): @@ -37,6 +38,7 @@ def test_build_api_url_no_extra_query_params(self): def test_build_api_url_w_extra_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) diff --git a/resource_manager/unit_tests/test_project.py b/resource_manager/unit_tests/test_project.py index 964a9f463e8b..a6905fc9a179 100644 --- a/resource_manager/unit_tests/test_project.py +++ b/resource_manager/unit_tests/test_project.py @@ -20,6 +20,7 @@ class TestProject(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.resource_manager.project import Project + return Project def _make_one(self, *args, **kw): @@ -325,6 +326,7 @@ def __init__(self, *responses): def api_request(self, **kw): from google.cloud.exceptions import NotFound + self._requested.append(kw) try: