diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index ddb396cb5607..ebf34a43cb75 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -174,7 +174,7 @@ Coding Style Exceptions to PEP8: -- Many unit tests use a helper method, ``_callFUT`` ("FUT" is short for +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for "Function-Under-Test"), which is PEP8-incompliant, but more readable. Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). diff --git a/bigquery/unit_tests/test__helpers.py b/bigquery/unit_tests/test__helpers.py index 5631abe6c184..46c58c8ea405 100644 --- a/bigquery/unit_tests/test__helpers.py +++ b/bigquery/unit_tests/test__helpers.py @@ -17,111 +17,111 @@ class Test_not_null(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertFalse(self._callFUT(None, _Field('NULLABLE'))) + self.assertFalse(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): - self.assertTrue(self._callFUT(None, _Field('REQUIRED'))) + self.assertTrue(self._call_fut(None, _Field('REQUIRED'))) def test_w_value(self): - self.assertTrue(self._callFUT(object(), object())) + self.assertTrue(self._call_fut(object(), object())) class Test_int_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(TypeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_string_value(self): - coerced = self._callFUT('42', object()) + coerced = self._call_fut('42', object()) self.assertEqual(coerced, 42) def test_w_float_value(self): - coerced = self._callFUT(42, object()) + coerced = self._call_fut(42, object()) self.assertEqual(coerced, 42) class Test_float_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(TypeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_string_value(self): - coerced = self._callFUT('3.1415', object()) + coerced = self._call_fut('3.1415', object()) self.assertEqual(coerced, 3.1415) def test_w_float_value(self): - coerced = self._callFUT(3.1415, object()) + coerced = self._call_fut(3.1415, object()) self.assertEqual(coerced, 3.1415) class Test_bool_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(AttributeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_value_t(self): - coerced = self._callFUT('T', object()) + coerced = self._call_fut('T', object()) self.assertTrue(coerced) def test_w_value_true(self): - coerced = self._callFUT('True', object()) + coerced = self._call_fut('True', object()) self.assertTrue(coerced) def test_w_value_1(self): - coerced = self._callFUT('1', object()) + coerced = self._call_fut('1', object()) self.assertTrue(coerced) def test_w_value_other(self): - coerced = self._callFUT('f', object()) + coerced = self._call_fut('f', object()) self.assertFalse(coerced) class Test_datetime_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(TypeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_string_value(self): import datetime from google.cloud._helpers import _EPOCH - coerced = self._callFUT('1.234567', object()) + coerced = self._call_fut('1.234567', object()) self.assertEqual( coerced, _EPOCH + datetime.timedelta(seconds=1, microseconds=234567)) @@ -129,7 +129,7 @@ def test_w_string_value(self): def test_w_float_value(self): import datetime from google.cloud._helpers import _EPOCH - coerced = self._callFUT(1.234567, object()) + coerced = self._call_fut(1.234567, object()) self.assertEqual( coerced, _EPOCH + datetime.timedelta(seconds=1, microseconds=234567)) @@ -137,20 +137,20 @@ def test_w_float_value(self): class Test_date_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(TypeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_string_value(self): import datetime - coerced = self._callFUT('1987-09-22', object()) + coerced = self._call_fut('1987-09-22', object()) self.assertEqual( coerced, datetime.date(1987, 9, 22)) @@ -158,36 +158,36 @@ def test_w_string_value(self): class Test_record_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): with self.assertRaises(TypeError): - self._callFUT(None, _Field('REQUIRED')) + self._call_fut(None, _Field('REQUIRED')) def test_w_nullable_subfield_none(self): subfield = _Field('NULLABLE', 'age', 'INTEGER') field = _Field('REQUIRED', fields=[subfield]) value = {'f': [{'v': None}]} - coerced = self._callFUT(value, field) + coerced = self._call_fut(value, field) self.assertEqual(coerced, {'age': None}) def test_w_scalar_subfield(self): subfield = _Field('REQUIRED', 'age', 'INTEGER') field = _Field('REQUIRED', fields=[subfield]) value = {'f': [{'v': 42}]} - coerced = self._callFUT(value, field) + coerced = self._call_fut(value, field) self.assertEqual(coerced, {'age': 42}) def test_w_repeated_subfield(self): subfield = _Field('REPEATED', 'color', 'STRING') field = _Field('REQUIRED', fields=[subfield]) value = {'f': [{'v': ['red', 'yellow', 'blue']}]} - coerced = self._callFUT(value, field) + coerced = self._call_fut(value, field) self.assertEqual(coerced, {'color': ['red', 'yellow', 'blue']}) def test_w_record_subfield(self): @@ -213,30 +213,30 @@ def test_w_record_subfield(self): 'rank': 1, } } - coerced = self._callFUT(value, person) + coerced = self._call_fut(value, person) self.assertEqual(coerced, expected) class Test_string_from_json(unittest.TestCase): - def _callFUT(self, value, field): + 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): - self.assertIsNone(self._callFUT(None, _Field('NULLABLE'))) + self.assertIsNone(self._call_fut(None, _Field('NULLABLE'))) def test_w_none_required(self): - self.assertIsNone(self._callFUT(None, _Field('RECORD'))) + self.assertIsNone(self._call_fut(None, _Field('RECORD'))) def test_w_string_value(self): - coerced = self._callFUT('Wonderful!', object()) + coerced = self._call_fut('Wonderful!', object()) self.assertEqual(coerced, 'Wonderful!') class Test_rows_from_json(unittest.TestCase): - def _callFUT(self, value, field): + def _call_fut(self, value, field): from google.cloud.bigquery._helpers import _rows_from_json return _rows_from_json(value, field) @@ -281,7 +281,7 @@ def test_w_record_subfield(self): ('Bharney Rhubble', bharney_phone, ['brown']), ('Wylma Phlyntstone', None, []), ] - coerced = self._callFUT(rows, schema) + coerced = self._call_fut(rows, schema) self.assertEqual(coerced, expected) def test_w_int64_float64(self): @@ -312,18 +312,19 @@ def test_w_int64_float64(self): ('Bharney Rhubble', 4, 0.125), ('Wylma Phlyntstone', 20, 0.625), ] - coerced = self._callFUT(rows, schema) + coerced = self._call_fut(rows, schema) self.assertEqual(coerced, expected) class Test_ConfigurationProperty(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery._helpers import _ConfigurationProperty return _ConfigurationProperty - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_it(self): @@ -331,7 +332,7 @@ class Configuration(object): _attr = None class Wrapper(object): - attr = self._makeOne('attr') + attr = self._make_one('attr') def __init__(self): self._configuration = Configuration() @@ -353,12 +354,13 @@ def __init__(self): class Test_TypedProperty(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery._helpers import _TypedProperty return _TypedProperty - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_it(self): @@ -366,7 +368,7 @@ class Configuration(object): _attr = None class Wrapper(object): - attr = self._makeOne('attr', int) + attr = self._make_one('attr', int) def __init__(self): self._configuration = Configuration() @@ -386,13 +388,14 @@ def __init__(self): class Test_EnumProperty(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery._helpers import _EnumProperty return _EnumProperty def test_it(self): - class Sub(self._getTargetClass()): + class Sub(self._get_target_class()): ALLOWED = ('FOO', 'BAR', 'BAZ') class Configuration(object): @@ -419,15 +422,16 @@ def __init__(self): class Test_UDFResourcesProperty(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery._helpers import UDFResourcesProperty return UDFResourcesProperty - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _descriptor_and_klass(self): - descriptor = self._makeOne() + descriptor = self._make_one() class _Test(object): _udf_resources = () diff --git a/bigquery/unit_tests/test__http.py b/bigquery/unit_tests/test__http.py index a2564ee278b8..0592b98178cd 100644 --- a/bigquery/unit_tests/test__http.py +++ b/bigquery/unit_tests/test__http.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery._http import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, 'bigquery', @@ -37,7 +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._makeOne() + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL) diff --git a/bigquery/unit_tests/test_client.py b/bigquery/unit_tests/test_client.py index cd2198078f74..9034658692d9 100644 --- a/bigquery/unit_tests/test_client.py +++ b/bigquery/unit_tests/test_client.py @@ -17,19 +17,20 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from google.cloud.bigquery._http import Connection PROJECT = 'PROJECT' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) self.assertIsInstance(client.connection, Connection) self.assertIs(client.connection.credentials, creds) self.assertIs(client.connection.http, http) @@ -57,7 +58,7 @@ def test_list_projects_defaults(self): ] } creds = _Credentials() - client = self._makeOne(PROJECT_1, creds) + client = self._make_one(PROJECT_1, creds) conn = client.connection = _Connection(DATA) iterator = client.list_projects() @@ -86,7 +87,7 @@ def test_list_projects_explicit_response_missing_projects_key(self): TOKEN = 'TOKEN' DATA = {} creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_projects(max_results=3, page_token=TOKEN) @@ -128,7 +129,7 @@ def test_list_datasets_defaults(self): ] } creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_datasets() @@ -156,7 +157,7 @@ def test_list_datasets_explicit_response_missing_datasets_key(self): TOKEN = 'TOKEN' DATA = {} creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_datasets( @@ -181,7 +182,7 @@ def test_dataset(self): DATASET = 'dataset_name' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) self.assertIsInstance(dataset, Dataset) self.assertEqual(dataset.name, DATASET) @@ -190,7 +191,7 @@ def test_dataset(self): def test_job_from_resource_unknown_type(self): PROJECT = 'PROJECT' creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) with self.assertRaises(ValueError): client.job_from_resource({'configuration': {'nonesuch': {}}}) @@ -304,7 +305,7 @@ def test_list_jobs_defaults(self): ] } creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_jobs() @@ -360,7 +361,7 @@ def test_list_jobs_load_job_wo_sourceUris(self): ] } creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_jobs() @@ -388,7 +389,7 @@ def test_list_jobs_explicit_missing(self): DATA = {} TOKEN = 'TOKEN' creds = _Credentials() - client = self._makeOne(PROJECT, creds) + client = self._make_one(PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_jobs(max_results=1000, page_token=TOKEN, @@ -420,7 +421,7 @@ def test_load_table_from_storage(self): SOURCE_URI = 'http://example.com/source.csv' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) destination = dataset.table(DESTINATION) job = client.load_table_from_storage(JOB, destination, SOURCE_URI) @@ -439,7 +440,7 @@ def test_copy_table(self): DESTINATION = 'destination_table' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) source = dataset.table(SOURCE) destination = dataset.table(DESTINATION) @@ -459,7 +460,7 @@ def test_extract_table_to_storage(self): DESTINATION = 'gs://bucket_name/object_name' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) source = dataset.table(SOURCE) job = client.extract_table_to_storage(JOB, source, DESTINATION) @@ -476,7 +477,7 @@ def test_run_async_query(self): QUERY = 'select count(*) from persons' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) job = client.run_async_query(JOB, QUERY) self.assertIsInstance(job, QueryJob) self.assertIs(job._client, client) @@ -489,7 +490,7 @@ def test_run_sync_query(self): QUERY = 'select count(*) from persons' creds = _Credentials() http = object() - client = self._makeOne(project=PROJECT, credentials=creds, http=http) + client = self._make_one(project=PROJECT, credentials=creds, http=http) job = client.run_sync_query(QUERY) self.assertIsInstance(job, QueryResults) self.assertIs(job._client, client) diff --git a/bigquery/unit_tests/test_dataset.py b/bigquery/unit_tests/test_dataset.py index 24c270b5005b..1493d266d44f 100644 --- a/bigquery/unit_tests/test_dataset.py +++ b/bigquery/unit_tests/test_dataset.py @@ -17,34 +17,35 @@ class TestAccessGrant(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.dataset import AccessGrant return AccessGrant - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): - grant = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') + grant = self._make_one('OWNER', 'userByEmail', 'phred@example.com') self.assertEqual(grant.role, 'OWNER') self.assertEqual(grant.entity_type, 'userByEmail') self.assertEqual(grant.entity_id, 'phred@example.com') def test_ctor_bad_entity_type(self): with self.assertRaises(ValueError): - self._makeOne(None, 'unknown', None) + self._make_one(None, 'unknown', None) def test_ctor_view_with_role(self): role = 'READER' entity_type = 'view' with self.assertRaises(ValueError): - self._makeOne(role, entity_type, None) + self._make_one(role, entity_type, None) def test_ctor_view_success(self): role = None entity_type = 'view' entity_id = object() - grant = self._makeOne(role, entity_type, entity_id) + grant = self._make_one(role, entity_type, entity_id) self.assertEqual(grant.role, role) self.assertEqual(grant.entity_type, entity_type) self.assertEqual(grant.entity_id, entity_id) @@ -53,26 +54,26 @@ def test_ctor_nonview_without_role(self): role = None entity_type = 'userByEmail' with self.assertRaises(ValueError): - self._makeOne(role, entity_type, None) + self._make_one(role, entity_type, None) def test___eq___role_mismatch(self): - grant = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') - other = self._makeOne('WRITER', 'userByEmail', 'phred@example.com') + grant = self._make_one('OWNER', 'userByEmail', 'phred@example.com') + other = self._make_one('WRITER', 'userByEmail', 'phred@example.com') self.assertNotEqual(grant, other) def test___eq___entity_type_mismatch(self): - grant = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') - other = self._makeOne('OWNER', 'groupByEmail', 'phred@example.com') + grant = self._make_one('OWNER', 'userByEmail', 'phred@example.com') + other = self._make_one('OWNER', 'groupByEmail', 'phred@example.com') self.assertNotEqual(grant, other) def test___eq___entity_id_mismatch(self): - grant = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') - other = self._makeOne('OWNER', 'userByEmail', 'bharney@example.com') + grant = self._make_one('OWNER', 'userByEmail', 'phred@example.com') + other = self._make_one('OWNER', 'userByEmail', 'bharney@example.com') self.assertNotEqual(grant, other) def test___eq___hit(self): - grant = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') - other = self._makeOne('OWNER', 'userByEmail', 'phred@example.com') + grant = self._make_one('OWNER', 'userByEmail', 'phred@example.com') + other = self._make_one('OWNER', 'userByEmail', 'phred@example.com') self.assertEqual(grant, other) @@ -80,12 +81,13 @@ class TestDataset(unittest.TestCase): PROJECT = 'project' DS_NAME = 'dataset-name' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.dataset import Dataset return Dataset - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _setUpConstants(self): import datetime @@ -174,7 +176,7 @@ def _verifyResourceProperties(self, dataset, resource): def test_ctor(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) self.assertEqual(dataset.name, self.DS_NAME) self.assertIs(dataset._client, client) self.assertEqual(dataset.project, client.project) @@ -196,14 +198,14 @@ def test_ctor(self): def test_access_roles_setter_non_list(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) with self.assertRaises(TypeError): dataset.access_grants = object() def test_access_roles_setter_invalid_field(self): from google.cloud.bigquery.dataset import AccessGrant client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com') with self.assertRaises(ValueError): dataset.access_grants = [phred, object()] @@ -211,7 +213,7 @@ def test_access_roles_setter_invalid_field(self): def test_access_roles_setter(self): from google.cloud.bigquery.dataset import AccessGrant client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com') bharney = AccessGrant('OWNER', 'userByEmail', 'bharney@example.com') dataset.access_grants = [phred, bharney] @@ -219,49 +221,49 @@ def test_access_roles_setter(self): def test_default_table_expiration_ms_setter_bad_value(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) with self.assertRaises(ValueError): dataset.default_table_expiration_ms = 'bogus' def test_default_table_expiration_ms_setter(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) dataset.default_table_expiration_ms = 12345 self.assertEqual(dataset.default_table_expiration_ms, 12345) def test_description_setter_bad_value(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) with self.assertRaises(ValueError): dataset.description = 12345 def test_description_setter(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) dataset.description = 'DESCRIPTION' self.assertEqual(dataset.description, 'DESCRIPTION') def test_friendly_name_setter_bad_value(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) with self.assertRaises(ValueError): dataset.friendly_name = 12345 def test_friendly_name_setter(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) dataset.friendly_name = 'FRIENDLY' self.assertEqual(dataset.friendly_name, 'FRIENDLY') def test_location_setter_bad_value(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) with self.assertRaises(ValueError): dataset.location = 12345 def test_location_setter(self): client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client) + dataset = self._make_one(self.DS_NAME, client) dataset.location = 'LOCATION' self.assertEqual(dataset.location, 'LOCATION') @@ -269,7 +271,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -283,7 +285,7 @@ def test_from_api_repr_bare(self): 'datasetId': self.DS_NAME, } } - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -291,7 +293,7 @@ def test_from_api_repr_bare(self): def test_from_api_repr_w_properties(self): client = _Client(self.PROJECT) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -301,7 +303,7 @@ def test__parse_access_grants_w_unknown_entity_type(self): {'role': 'READER', 'unknown': 'UNKNOWN'}, ] client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) with self.assertRaises(ValueError): dataset._parse_access_grants(ACCESS) @@ -315,7 +317,7 @@ def test__parse_access_grants_w_extra_keys(self): }, ] client = _Client(self.PROJECT) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) with self.assertRaises(ValueError): dataset._parse_access_grants(ACCESS) @@ -324,7 +326,7 @@ def test_create_w_bound_client(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.create() @@ -353,7 +355,7 @@ def test_create_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) dataset.friendly_name = TITLE dataset.description = DESCRIPTION VIEW = { @@ -406,7 +408,7 @@ def test_create_w_missing_output_properties(self): self.WHEN = None conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.create() @@ -425,7 +427,7 @@ def test_exists_miss_w_bound_client(self): PATH = 'projects/%s/datasets/%s' % (self.PROJECT, self.DS_NAME) conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) self.assertFalse(dataset.exists()) @@ -441,7 +443,7 @@ def test_exists_hit_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) self.assertTrue(dataset.exists(client=CLIENT2)) @@ -457,7 +459,7 @@ def test_reload_w_bound_client(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.reload() @@ -474,7 +476,7 @@ def test_reload_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) dataset.reload(client=CLIENT2) @@ -489,7 +491,7 @@ def test_patch_w_invalid_expiration(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) with self.assertRaises(ValueError): dataset.patch(default_table_expiration_ms='BOGUS') @@ -503,7 +505,7 @@ def test_patch_w_bound_client(self): RESOURCE['friendlyName'] = TITLE conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.patch(description=DESCRIPTION, friendly_name=TITLE) @@ -529,7 +531,7 @@ def test_patch_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) dataset.patch(client=CLIENT2, default_table_expiration_ms=DEF_TABLE_EXP, @@ -556,7 +558,7 @@ def test_update_w_bound_client(self): RESOURCE['friendlyName'] = TITLE conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.description = DESCRIPTION dataset.friendly_name = TITLE @@ -586,7 +588,7 @@ def test_update_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) dataset.default_table_expiration_ms = DEF_TABLE_EXP dataset.location = LOCATION @@ -610,7 +612,7 @@ def test_delete_w_bound_client(self): PATH = 'projects/%s/datasets/%s' % (self.PROJECT, self.DS_NAME) conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) dataset.delete() @@ -625,7 +627,7 @@ def test_delete_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - dataset = self._makeOne(self.DS_NAME, client=CLIENT1) + dataset = self._make_one(self.DS_NAME, client=CLIENT1) dataset.delete(client=CLIENT2) @@ -640,7 +642,7 @@ def test_list_tables_empty(self): conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) iterator = dataset.list_tables() self.assertIs(iterator.dataset, dataset) @@ -684,7 +686,7 @@ def test_list_tables_defaults(self): conn = _Connection(DATA) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) iterator = dataset.list_tables() self.assertIs(iterator.dataset, dataset) @@ -731,7 +733,7 @@ def test_list_tables_explicit(self): conn = _Connection(DATA) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) iterator = dataset.list_tables(max_results=3, page_token=TOKEN) self.assertIs(iterator.dataset, dataset) @@ -757,7 +759,7 @@ def test_table_wo_schema(self): from google.cloud.bigquery.table import Table conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) table = dataset.table('table_name') self.assertIsInstance(table, Table) self.assertEqual(table.name, 'table_name') @@ -769,7 +771,7 @@ def test_table_w_schema(self): from google.cloud.bigquery.table import Table conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - dataset = self._makeOne(self.DS_NAME, client=client) + dataset = self._make_one(self.DS_NAME, client=client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') table = dataset.table('table_name', schema=[full_name, age]) diff --git a/bigquery/unit_tests/test_job.py b/bigquery/unit_tests/test_job.py index 592d81910f59..67b1477f9732 100644 --- a/bigquery/unit_tests/test_job.py +++ b/bigquery/unit_tests/test_job.py @@ -22,8 +22,8 @@ class _Base(object): TABLE_NAME = 'table_name' JOB_NAME = 'job_name' - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _setUpConstants(self): import datetime @@ -122,7 +122,8 @@ def _verifyReadonlyResourceProperties(self, job, resource): class TestLoadTableFromStorageJob(unittest.TestCase, _Base): JOB_TYPE = 'load' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.job import LoadTableFromStorageJob return LoadTableFromStorageJob @@ -230,7 +231,7 @@ def _verifyResourceProperties(self, job, resource): def test_ctor(self): client = _Client(self.PROJECT) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) self.assertIs(job.destination, table) self.assertEqual(list(job.source_uris), [self.SOURCE1]) self.assertIs(job._client, client) @@ -267,14 +268,14 @@ def test_ctor_w_schema(self): table = _Table() full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client, - schema=[full_name, age]) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client, + schema=[full_name, age]) self.assertEqual(job.schema, [full_name, age]) def test_schema_setter_non_list(self): client = _Client(self.PROJECT) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) with self.assertRaises(TypeError): job.schema = object() @@ -282,7 +283,7 @@ def test_schema_setter_invalid_field(self): from google.cloud.bigquery.schema import SchemaField client = _Client(self.PROJECT) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') with self.assertRaises(ValueError): job.schema = [full_name, object()] @@ -291,7 +292,7 @@ def test_schema_setter(self): from google.cloud.bigquery.schema import SchemaField client = _Client(self.PROJECT) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') job.schema = [full_name, age] @@ -316,7 +317,7 @@ def test_props_set_by_server(self): client = _Client(self.PROJECT) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) job._properties['etag'] = 'ETAG' job._properties['id'] = JOB_ID job._properties['selfLink'] = URL @@ -363,7 +364,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -377,7 +378,7 @@ def test_from_api_repr_missing_config(self): 'jobId': self.JOB_NAME, } } - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -401,7 +402,7 @@ def test_from_api_repr_bare(self): } }, } - klass = self._getTargetClass() + klass = self._get_target_class() job = klass.from_api_repr(RESOURCE, client=client) self.assertIs(job._client, client) self._verifyResourceProperties(job, RESOURCE) @@ -409,7 +410,7 @@ def test_from_api_repr_bare(self): def test_from_api_repr_w_properties(self): client = _Client(self.PROJECT) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -418,7 +419,7 @@ def test_begin_w_already_running(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) job._properties['status'] = {'state': 'RUNNING'} with self.assertRaises(ValueError): @@ -435,7 +436,7 @@ def test_begin_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) job.begin() @@ -497,8 +498,8 @@ def test_begin_w_alternate_client(self): table = _Table() full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client1, - schema=[full_name, age]) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client1, + schema=[full_name, age]) job.allow_jagged_rows = True job.allow_quoted_newlines = True @@ -536,7 +537,7 @@ def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) self.assertFalse(job.exists()) @@ -553,7 +554,7 @@ def test_exists_hit_w_alternate_client(self): conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client1) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client1) self.assertTrue(job.exists(client=client2)) @@ -570,7 +571,7 @@ def test_reload_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) job.reload() @@ -588,7 +589,7 @@ def test_reload_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client1) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client1) job.reload(client=client2) @@ -606,7 +607,7 @@ def test_cancel_w_bound_client(self): conn = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=conn) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client) job.cancel() @@ -625,7 +626,7 @@ def test_cancel_w_alternate_client(self): conn2 = _Connection(RESPONSE) client2 = _Client(project=self.PROJECT, connection=conn2) table = _Table() - job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client1) + job = self._make_one(self.JOB_NAME, table, [self.SOURCE1], client1) job.cancel(client=client2) @@ -642,7 +643,8 @@ class TestCopyJob(unittest.TestCase, _Base): SOURCE_TABLE = 'source_table' DESTINATION_TABLE = 'destination_table' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.job import CopyJob return CopyJob @@ -696,7 +698,7 @@ def test_ctor(self): client = _Client(self.PROJECT) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client) + job = self._make_one(self.JOB_NAME, destination, [source], client) self.assertIs(job.destination, destination) self.assertEqual(job.sources, [source]) self.assertIs(job._client, client) @@ -715,7 +717,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -729,7 +731,7 @@ def test_from_api_repr_missing_config(self): 'jobId': self.JOB_NAME, } } - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -757,7 +759,7 @@ def test_from_api_repr_bare(self): } }, } - klass = self._getTargetClass() + klass = self._get_target_class() job = klass.from_api_repr(RESOURCE, client=client) self.assertIs(job._client, client) self._verifyResourceProperties(job, RESOURCE) @@ -765,7 +767,7 @@ def test_from_api_repr_bare(self): def test_from_api_repr_w_properties(self): client = _Client(self.PROJECT) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -782,7 +784,7 @@ def test_begin_w_bound_client(self): client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client) + job = self._make_one(self.JOB_NAME, destination, [source], client) job.begin() @@ -837,7 +839,7 @@ def test_begin_w_alternate_client(self): client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client1) + job = self._make_one(self.JOB_NAME, destination, [source], client1) job.create_disposition = 'CREATE_NEVER' job.write_disposition = 'WRITE_TRUNCATE' @@ -867,7 +869,7 @@ def test_exists_miss_w_bound_client(self): client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client) + job = self._make_one(self.JOB_NAME, destination, [source], client) self.assertFalse(job.exists()) @@ -885,7 +887,7 @@ def test_exists_hit_w_alternate_client(self): client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client1) + job = self._make_one(self.JOB_NAME, destination, [source], client1) self.assertTrue(job.exists(client=client2)) @@ -903,7 +905,7 @@ def test_reload_w_bound_client(self): client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client) + job = self._make_one(self.JOB_NAME, destination, [source], client) job.reload() @@ -922,7 +924,7 @@ def test_reload_w_alternate_client(self): client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) destination = _Table(self.DESTINATION_TABLE) - job = self._makeOne(self.JOB_NAME, destination, [source], client1) + job = self._make_one(self.JOB_NAME, destination, [source], client1) job.reload(client=client2) @@ -939,7 +941,8 @@ class TestExtractTableToStorageJob(unittest.TestCase, _Base): SOURCE_TABLE = 'source_table' DESTINATION_URI = 'gs://bucket_name/object_name' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.job import ExtractTableToStorageJob return ExtractTableToStorageJob @@ -994,8 +997,8 @@ def _verifyResourceProperties(self, job, resource): def test_ctor(self): client = _Client(self.PROJECT) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client) self.assertEqual(job.source, source) self.assertEqual(job.destination_uris, [self.DESTINATION_URI]) self.assertIs(job._client, client) @@ -1016,7 +1019,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -1030,7 +1033,7 @@ def test_from_api_repr_missing_config(self): 'jobId': self.JOB_NAME, } } - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -1054,7 +1057,7 @@ def test_from_api_repr_bare(self): } }, } - klass = self._getTargetClass() + klass = self._get_target_class() job = klass.from_api_repr(RESOURCE, client=client) self.assertIs(job._client, client) self._verifyResourceProperties(job, RESOURCE) @@ -1062,7 +1065,7 @@ def test_from_api_repr_bare(self): def test_from_api_repr_w_properties(self): client = _Client(self.PROJECT) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -1078,8 +1081,8 @@ def test_begin_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client) job.begin() @@ -1127,8 +1130,8 @@ def test_begin_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client1) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client1) job.compression = 'GZIP' job.destination_format = 'NEWLINE_DELIMITED_JSON' @@ -1159,8 +1162,8 @@ def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client) self.assertFalse(job.exists()) @@ -1177,8 +1180,8 @@ def test_exists_hit_w_alternate_client(self): conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client1) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client1) self.assertTrue(job.exists(client=client2)) @@ -1195,8 +1198,8 @@ def test_reload_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client) job.reload() @@ -1214,8 +1217,8 @@ def test_reload_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) source = _Table(self.SOURCE_TABLE) - job = self._makeOne(self.JOB_NAME, source, [self.DESTINATION_URI], - client1) + job = self._make_one(self.JOB_NAME, source, [self.DESTINATION_URI], + client1) job.reload(client=client2) @@ -1232,7 +1235,8 @@ class TestQueryJob(unittest.TestCase, _Base): QUERY = 'select count(*) from persons' DESTINATION_TABLE = 'destination_table' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.job import QueryJob return QueryJob @@ -1328,7 +1332,7 @@ def _verifyResourceProperties(self, job, resource): def test_ctor(self): client = _Client(self.PROJECT) - job = self._makeOne(self.JOB_NAME, self.QUERY, client) + job = self._make_one(self.JOB_NAME, self.QUERY, client) self.assertEqual(job.query, self.QUERY) self.assertIs(job._client, client) self.assertEqual(job.job_type, self.JOB_TYPE) @@ -1356,7 +1360,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -1370,7 +1374,7 @@ def test_from_api_repr_missing_config(self): 'jobId': self.JOB_NAME, } } - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -1387,7 +1391,7 @@ def test_from_api_repr_bare(self): 'query': {'query': self.QUERY} }, } - klass = self._getTargetClass() + klass = self._get_target_class() job = klass.from_api_repr(RESOURCE, client=client) self.assertIs(job._client, client) self._verifyResourceProperties(job, RESOURCE) @@ -1400,7 +1404,7 @@ def test_from_api_repr_w_properties(self): 'datasetId': self.DS_NAME, 'tableId': self.DESTINATION_TABLE, } - klass = self._getTargetClass() + klass = self._get_target_class() dataset = klass.from_api_repr(RESOURCE, client=client) self.assertIs(dataset._client, client) self._verifyResourceProperties(dataset, RESOURCE) @@ -1408,7 +1412,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._makeOne(self.JOB_NAME, self.QUERY, client) + job = self._make_one(self.JOB_NAME, self.QUERY, client) results = job.results() self.assertIsInstance(results, QueryResults) self.assertIs(results._job, job) @@ -1423,7 +1427,7 @@ def test_begin_w_bound_client(self): del RESOURCE['user_email'] conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - job = self._makeOne(self.JOB_NAME, self.QUERY, client) + job = self._make_one(self.JOB_NAME, self.QUERY, client) job.begin() self.assertEqual(job.udf_resources, []) @@ -1479,7 +1483,7 @@ def test_begin_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) - job = self._makeOne(self.JOB_NAME, self.QUERY, client1) + job = self._make_one(self.JOB_NAME, self.QUERY, client1) dataset = Dataset(DS_NAME, client1) table = Table(TABLE, dataset) @@ -1528,10 +1532,10 @@ def test_begin_w_bound_client_and_udf(self): del RESOURCE['user_email'] conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - job = self._makeOne(self.JOB_NAME, self.QUERY, client, - udf_resources=[ - UDFResource("resourceUri", RESOURCE_URI) - ]) + job = self._make_one(self.JOB_NAME, self.QUERY, client, + udf_resources=[ + UDFResource("resourceUri", RESOURCE_URI) + ]) job.begin() @@ -1561,7 +1565,7 @@ def test_exists_miss_w_bound_client(self): PATH = 'projects/%s/jobs/%s' % (self.PROJECT, self.JOB_NAME) conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - job = self._makeOne(self.JOB_NAME, self.QUERY, client) + job = self._make_one(self.JOB_NAME, self.QUERY, client) self.assertFalse(job.exists()) @@ -1577,7 +1581,7 @@ def test_exists_hit_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) - job = self._makeOne(self.JOB_NAME, self.QUERY, client1) + job = self._make_one(self.JOB_NAME, self.QUERY, client1) self.assertTrue(job.exists(client=client2)) @@ -1597,7 +1601,7 @@ def test_reload_w_bound_client(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - job = self._makeOne(self.JOB_NAME, None, client) + job = self._make_one(self.JOB_NAME, None, client) dataset = Dataset(DS_NAME, client) table = Table(DEST_TABLE, dataset) @@ -1628,7 +1632,7 @@ def test_reload_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) - job = self._makeOne(self.JOB_NAME, self.QUERY, client1) + job = self._make_one(self.JOB_NAME, self.QUERY, client1) job.reload(client=client2) diff --git a/bigquery/unit_tests/test_query.py b/bigquery/unit_tests/test_query.py index 9bcb865df5a7..58bc8ced8e1b 100644 --- a/bigquery/unit_tests/test_query.py +++ b/bigquery/unit_tests/test_query.py @@ -23,12 +23,13 @@ class TestQueryResults(unittest.TestCase): QUERY = 'select count(*) from persons' TOKEN = 'TOKEN' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.query import QueryResults return QueryResults - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _makeResource(self, complete=False): resource = { @@ -118,7 +119,7 @@ def _verifyResourceProperties(self, query, resource): def test_ctor(self): client = _Client(self.PROJECT) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) self.assertEqual(query.query, self.QUERY) self.assertIs(query._client, client) @@ -151,7 +152,7 @@ def test_from_query_job(self): dataset = job.default_dataset = Dataset(DS_NAME, client) job.use_query_cache = True job.use_legacy_sql = True - klass = self._getTargetClass() + klass = self._get_target_class() query = klass.from_query_job(job) @@ -172,7 +173,7 @@ def test_from_query_job_wo_default_dataset(self): job = QueryJob( self.JOB_NAME, self.QUERY, client, udf_resources=[UDFResource("resourceUri", RESOURCE_URI)]) - klass = self._getTargetClass() + klass = self._get_target_class() query = klass.from_query_job(job) @@ -186,14 +187,14 @@ def test_from_query_job_wo_default_dataset(self): def test_job_wo_jobid(self): client = _Client(self.PROJECT) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) self.assertIsNone(query.job) def test_job_w_jobid(self): from google.cloud.bigquery.job import QueryJob SERVER_GENERATED = 'SERVER_GENERATED' client = _Client(self.PROJECT) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query._properties['jobReference'] = { 'projectId': self.PROJECT, 'jobId': SERVER_GENERATED, @@ -208,7 +209,7 @@ def test_job_w_jobid(self): def test_schema(self): client = _Client(self.PROJECT) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) self._verifyResourceProperties(query, {}) resource = { 'schema': { @@ -224,7 +225,7 @@ def test_schema(self): def test_run_w_already_has_job(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query._job = object() # simulate already running with self.assertRaises(ValueError): query.run() @@ -234,7 +235,7 @@ def test_run_w_bound_client(self): RESOURCE = self._makeResource(complete=False) conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) self.assertEqual(query.udf_resources, []) query.run() @@ -254,7 +255,7 @@ def test_run_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) - query = self._makeOne(self.QUERY, client1) + query = self._make_one(self.QUERY, client1) query.default_dataset = client2.dataset(DATASET) query.max_results = 100 @@ -294,7 +295,7 @@ def test_run_w_inline_udf(self): RESOURCE = self._makeResource(complete=False) conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query.udf_resources = [UDFResource("inlineCode", INLINE_UDF_CODE)] query.run() @@ -316,7 +317,7 @@ def test_run_w_udf_resource_uri(self): RESOURCE = self._makeResource(complete=False) conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query.udf_resources = [UDFResource("resourceUri", RESOURCE_URI)] query.run() @@ -339,7 +340,7 @@ def test_run_w_mixed_udfs(self): RESOURCE = self._makeResource(complete=False) conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query.udf_resources = [UDFResource("resourceUri", RESOURCE_URI), UDFResource("inlineCode", INLINE_UDF_CODE)] @@ -362,7 +363,7 @@ def test_run_w_mixed_udfs(self): def test_fetch_data_query_not_yet_run(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) self.assertRaises(ValueError, query.fetch_data) def test_fetch_data_w_bound_client(self): @@ -373,7 +374,7 @@ def test_fetch_data_w_bound_client(self): conn = _Connection(AFTER) client = _Client(project=self.PROJECT, connection=conn) - query = self._makeOne(self.QUERY, client) + query = self._make_one(self.QUERY, client) query._set_properties(BEFORE) self.assertFalse(query.complete) @@ -406,7 +407,7 @@ def test_fetch_data_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(AFTER) client2 = _Client(project=self.PROJECT, connection=conn2) - query = self._makeOne(self.QUERY, client1) + query = self._make_one(self.QUERY, client1) query._set_properties(BEFORE) self.assertFalse(query.complete) diff --git a/bigquery/unit_tests/test_schema.py b/bigquery/unit_tests/test_schema.py index a8272728b742..8b49bff5b29a 100644 --- a/bigquery/unit_tests/test_schema.py +++ b/bigquery/unit_tests/test_schema.py @@ -17,15 +17,16 @@ class TestSchemaField(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.schema import SchemaField return SchemaField - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): - field = self._makeOne('test', 'STRING') + field = self._make_one('test', 'STRING') self.assertEqual(field.name, 'test') self.assertEqual(field.field_type, 'STRING') self.assertEqual(field.mode, 'NULLABLE') @@ -33,8 +34,8 @@ def test_ctor_defaults(self): self.assertIsNone(field.fields) def test_ctor_explicit(self): - field = self._makeOne('test', 'STRING', mode='REQUIRED', - description='Testing') + field = self._make_one('test', 'STRING', mode='REQUIRED', + description='Testing') self.assertEqual(field.name, 'test') self.assertEqual(field.field_type, 'STRING') self.assertEqual(field.mode, 'REQUIRED') @@ -42,9 +43,10 @@ def test_ctor_explicit(self): self.assertIsNone(field.fields) def test_ctor_subfields(self): - field = self._makeOne('phone_number', 'RECORD', - fields=[self._makeOne('area_code', 'STRING'), - self._makeOne('local_number', 'STRING')]) + field = self._make_one( + 'phone_number', 'RECORD', + fields=[self._make_one('area_code', 'STRING'), + self._make_one('local_number', 'STRING')]) self.assertEqual(field.name, 'phone_number') self.assertEqual(field.field_type, 'RECORD') self.assertEqual(field.mode, 'NULLABLE') @@ -62,49 +64,49 @@ def test_ctor_subfields(self): self.assertIsNone(field.fields[1].fields) def test___eq___name_mismatch(self): - field = self._makeOne('test', 'STRING') - other = self._makeOne('other', 'STRING') + field = self._make_one('test', 'STRING') + other = self._make_one('other', 'STRING') self.assertNotEqual(field, other) def test___eq___field_type_mismatch(self): - field = self._makeOne('test', 'STRING') - other = self._makeOne('test', 'INTEGER') + field = self._make_one('test', 'STRING') + other = self._make_one('test', 'INTEGER') self.assertNotEqual(field, other) def test___eq___mode_mismatch(self): - field = self._makeOne('test', 'STRING', mode='REQUIRED') - other = self._makeOne('test', 'STRING', mode='NULLABLE') + field = self._make_one('test', 'STRING', mode='REQUIRED') + other = self._make_one('test', 'STRING', mode='NULLABLE') self.assertNotEqual(field, other) def test___eq___description_mismatch(self): - field = self._makeOne('test', 'STRING', description='Testing') - other = self._makeOne('test', 'STRING', description='Other') + field = self._make_one('test', 'STRING', description='Testing') + other = self._make_one('test', 'STRING', description='Other') self.assertNotEqual(field, other) def test___eq___fields_mismatch(self): - sub1 = self._makeOne('sub1', 'STRING') - sub2 = self._makeOne('sub2', 'STRING') - field = self._makeOne('test', 'RECORD', fields=[sub1]) - other = self._makeOne('test', 'RECORD', fields=[sub2]) + sub1 = self._make_one('sub1', 'STRING') + sub2 = self._make_one('sub2', 'STRING') + field = self._make_one('test', 'RECORD', fields=[sub1]) + other = self._make_one('test', 'RECORD', fields=[sub2]) self.assertNotEqual(field, other) def test___eq___hit(self): - field = self._makeOne('test', 'STRING', mode='REQUIRED', - description='Testing') - other = self._makeOne('test', 'STRING', mode='REQUIRED', - description='Testing') + field = self._make_one('test', 'STRING', mode='REQUIRED', + description='Testing') + other = self._make_one('test', 'STRING', mode='REQUIRED', + description='Testing') self.assertEqual(field, other) def test___eq___hit_case_diff_on_type(self): - field = self._makeOne('test', 'STRING', mode='REQUIRED', - description='Testing') - other = self._makeOne('test', 'string', mode='REQUIRED', - description='Testing') + field = self._make_one('test', 'STRING', mode='REQUIRED', + description='Testing') + other = self._make_one('test', 'string', mode='REQUIRED', + description='Testing') self.assertEqual(field, other) def test___eq___hit_w_fields(self): - sub1 = self._makeOne('sub1', 'STRING') - sub2 = self._makeOne('sub2', 'STRING') - field = self._makeOne('test', 'RECORD', fields=[sub1, sub2]) - other = self._makeOne('test', 'RECORD', fields=[sub1, sub2]) + sub1 = self._make_one('sub1', 'STRING') + sub2 = self._make_one('sub2', 'STRING') + field = self._make_one('test', 'RECORD', fields=[sub1, sub2]) + other = self._make_one('test', 'RECORD', fields=[sub1, sub2]) self.assertEqual(field, other) diff --git a/bigquery/unit_tests/test_table.py b/bigquery/unit_tests/test_table.py index b46e3a2974df..45b784e84437 100644 --- a/bigquery/unit_tests/test_table.py +++ b/bigquery/unit_tests/test_table.py @@ -35,12 +35,13 @@ class TestTable(unittest.TestCase, _SchemaBase): DS_NAME = 'dataset-name' TABLE_NAME = 'table-name' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigquery.table import Table return Table - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _setUpConstants(self): import datetime @@ -133,7 +134,7 @@ def _verifyResourceProperties(self, table, resource): def test_ctor(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) self.assertEqual(table.name, self.TABLE_NAME) self.assertIs(table._dataset, dataset) self.assertEqual(table.project, self.PROJECT) @@ -165,14 +166,14 @@ def test_ctor_w_schema(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertEqual(table.schema, [full_name, age]) def test_num_bytes_getter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) # Check with no value set. self.assertIsNone(table.num_bytes) @@ -194,7 +195,7 @@ def test_num_bytes_getter(self): def test_num_rows_getter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) # Check with no value set. self.assertIsNone(table.num_rows) @@ -216,7 +217,7 @@ def test_num_rows_getter(self): def test_schema_setter_non_list(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(TypeError): table.schema = object() @@ -224,7 +225,7 @@ def test_schema_setter_invalid_field(self): from google.cloud.bigquery.table import SchemaField client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') with self.assertRaises(ValueError): table.schema = [full_name, object()] @@ -233,7 +234,7 @@ def test_schema_setter(self): from google.cloud.bigquery.table import SchemaField client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') table.schema = [full_name, age] @@ -252,7 +253,7 @@ def test_props_set_by_server(self): self.PROJECT, self.DS_NAME, self.TABLE_NAME) client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table._properties['creationTime'] = _millis(CREATED) table._properties['etag'] = 'ETAG' table._properties['lastModifiedTime'] = _millis(MODIFIED) @@ -274,21 +275,21 @@ def test_props_set_by_server(self): def test_description_setter_bad_value(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.description = 12345 def test_description_setter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.description = 'DESCRIPTION' self.assertEqual(table.description, 'DESCRIPTION') def test_expires_setter_bad_value(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.expires = object() @@ -299,56 +300,56 @@ def test_expires_setter(self): WHEN = datetime.datetime(2015, 7, 28, 16, 39, tzinfo=UTC) client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.expires = WHEN self.assertEqual(table.expires, WHEN) def test_friendly_name_setter_bad_value(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.friendly_name = 12345 def test_friendly_name_setter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.friendly_name = 'FRIENDLY' self.assertEqual(table.friendly_name, 'FRIENDLY') def test_location_setter_bad_value(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.location = 12345 def test_location_setter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.location = 'LOCATION' self.assertEqual(table.location, 'LOCATION') def test_view_query_setter_bad_value(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.view_query = 12345 def test_view_query_setter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.view_query = 'select * from foo' self.assertEqual(table.view_query, 'select * from foo') def test_view_query_deleter(self): client = _Client(self.PROJECT) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) table.view_query = 'select * from foo' del table.view_query self.assertIsNone(table.view_query) @@ -358,7 +359,7 @@ def test_from_api_repr_missing_identity(self): client = _Client(self.PROJECT) dataset = _Dataset(client) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, dataset) @@ -375,7 +376,7 @@ def test_from_api_repr_bare(self): }, 'type': 'TABLE', } - klass = self._getTargetClass() + klass = self._get_target_class() table = klass.from_api_repr(RESOURCE, dataset) self.assertEqual(table.name, self.TABLE_NAME) self.assertIs(table._dataset, dataset) @@ -385,7 +386,7 @@ def test_from_api_repr_w_properties(self): client = _Client(self.PROJECT) dataset = _Dataset(client) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() table = klass.from_api_repr(RESOURCE, dataset) self.assertIs(table._dataset._client, client) self._verifyResourceProperties(table, RESOURCE) @@ -394,7 +395,7 @@ def test_create_no_view_query_no_schema(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset) + table = self._make_one(self.TABLE_NAME, dataset) with self.assertRaises(ValueError): table.create() @@ -408,8 +409,8 @@ def test_create_w_bound_client(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) table.create() @@ -438,8 +439,8 @@ def test_create_w_partition_no_expire(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partitioning_type) table.partitioning_type = "DAY" @@ -472,8 +473,8 @@ def test_create_w_partition_and_expire(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partition_expiration) table.partition_expiration = 100 self.assertEqual(table.partitioning_type, "DAY") @@ -505,8 +506,8 @@ def test_partition_type_setter_bad_type(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) with self.assertRaises(ValueError): table.partitioning_type = 123 @@ -518,8 +519,8 @@ def test_partition_type_setter_unknown_value(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) with self.assertRaises(ValueError): table.partitioning_type = "HASH" @@ -531,8 +532,8 @@ def test_partition_type_setter_w_known_value(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partitioning_type) table.partitioning_type = 'DAY' self.assertEqual(table.partitioning_type, 'DAY') @@ -545,8 +546,8 @@ def test_partition_type_setter_w_none(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) table._properties['timePartitioning'] = {'type': 'DAY'} table.partitioning_type = None self.assertIsNone(table.partitioning_type) @@ -560,8 +561,8 @@ def test_partition_experation_bad_type(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) with self.assertRaises(ValueError): table.partition_expiration = "NEVER" @@ -573,8 +574,8 @@ def test_partition_expiration_w_integer(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partition_expiration) table.partition_expiration = 100 self.assertEqual(table.partitioning_type, "DAY") @@ -588,8 +589,8 @@ def test_partition_expiration_w_none(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partition_expiration) table._properties['timePartitioning'] = { 'type': 'DAY', @@ -607,8 +608,8 @@ def test_partition_expiration_w_none_no_partition_set(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertIsNone(table.partition_expiration) table.partition_expiration = None self.assertIsNone(table.partitioning_type) @@ -622,8 +623,8 @@ def test_list_partitions(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) self.assertEqual(table.list_partitions(), [20160804, 20160805]) def test_create_w_alternate_client(self): @@ -652,8 +653,8 @@ def test_create_w_alternate_client(self): dataset = _Dataset(client=client1) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age]) table.friendly_name = TITLE table.description = DESCRIPTION table.view_query = QUERY @@ -691,8 +692,8 @@ def test_create_w_missing_output_properties(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset, + schema=[full_name, age]) table.create() @@ -718,7 +719,7 @@ def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) self.assertFalse(table.exists()) @@ -736,7 +737,7 @@ def test_exists_hit_w_alternate_client(self): conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) dataset = _Dataset(client1) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) self.assertTrue(table.exists(client=client2)) @@ -754,7 +755,7 @@ def test_reload_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.reload() @@ -773,7 +774,7 @@ def test_reload_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) dataset = _Dataset(client1) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.reload(client=client2) @@ -789,7 +790,7 @@ def test_patch_w_invalid_expiration(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) with self.assertRaises(ValueError): table.patch(expires='BOGUS') @@ -805,7 +806,7 @@ def test_patch_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.patch(description=DESCRIPTION, friendly_name=TITLE, @@ -845,7 +846,7 @@ def test_patch_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) dataset = _Dataset(client1) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='NULLABLE') @@ -881,7 +882,7 @@ def test_patch_w_schema_None(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.patch(schema=None) @@ -907,8 +908,8 @@ def test_update_w_bound_client(self): dataset = _Dataset(client) full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age]) table.description = DESCRIPTION table.friendly_name = TITLE @@ -955,7 +956,7 @@ def test_update_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) dataset = _Dataset(client1) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.default_table_expiration_ms = DEF_TABLE_EXP table.location = LOCATION table.expires = self.EXP_TIME @@ -986,7 +987,7 @@ def test_delete_w_bound_client(self): conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.delete() @@ -1003,7 +1004,7 @@ def test_delete_w_alternate_client(self): conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) dataset = _Dataset(client1) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) table.delete(client=client2) @@ -1066,8 +1067,8 @@ def _bigquery_timestamp_float_repr(ts_float): full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='NULLABLE') joined = SchemaField('joined', 'TIMESTAMP', mode='NULLABLE') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age, joined]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age, joined]) iterator = table.fetch_data() page = six.next(iterator.pages) @@ -1133,8 +1134,8 @@ def test_fetch_data_w_alternate_client(self): age = SchemaField('age', 'INTEGER', mode='REQUIRED') voter = SchemaField('voter', 'BOOLEAN', mode='NULLABLE') score = SchemaField('score', 'FLOAT', mode='NULLABLE') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age, voter, score]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age, voter, score]) iterator = table.fetch_data( client=client2, max_results=MAX, page_token=TOKEN) @@ -1186,8 +1187,8 @@ def test_fetch_data_w_repeated_fields(self): score = SchemaField('score', 'FLOAT', 'REPEATED') struct = SchemaField('struct', 'RECORD', mode='REPEATED', fields=[index, score]) - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, struct]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, struct]) iterator = table.fetch_data() page = six.next(iterator.pages) @@ -1242,8 +1243,8 @@ def test_fetch_data_w_record_schema(self): rank = SchemaField('rank', 'INTEGER', 'REQUIRED') phone = SchemaField('phone', 'RECORD', mode='NULLABLE', fields=[area_code, local_number, rank]) - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, phone]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, phone]) iterator = table.fetch_data() page = six.next(iterator.pages) @@ -1274,7 +1275,7 @@ 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._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) ROWS = [ ('Phred Phlyntstone', 32), ('Bharney Rhubble', 33), @@ -1304,8 +1305,8 @@ def test_insert_data_w_bound_client(self): full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') joined = SchemaField('joined', 'TIMESTAMP', mode='NULLABLE') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age, joined]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age, joined]) ROWS = [ ('Phred Phlyntstone', 32, WHEN), ('Bharney Rhubble', 33, WHEN + datetime.timedelta(seconds=1)), @@ -1356,8 +1357,8 @@ def test_insert_data_w_alternate_client(self): full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') voter = SchemaField('voter', 'BOOLEAN', mode='NULLABLE') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age, voter]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age, voter]) ROWS = [ ('Phred Phlyntstone', 32, True), ('Bharney Rhubble', 33, False), @@ -1410,8 +1411,8 @@ def test_insert_data_w_repeated_fields(self): score = SchemaField('score', 'FLOAT', 'REPEATED') struct = SchemaField('struct', 'RECORD', mode='REPEATED', fields=[index, score]) - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, struct]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, struct]) ROWS = [ (['red', 'green'], [{'index': [1, 2], 'score': [3.1415, 1.414]}]), ] @@ -1446,8 +1447,8 @@ def test_insert_data_w_record_schema(self): rank = SchemaField('rank', 'INTEGER', 'REQUIRED') phone = SchemaField('phone', 'RECORD', mode='NULLABLE', fields=[area_code, local_number, rank]) - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, phone]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, phone]) ROWS = [ ('Phred Phlyntstone', {'area_code': '800', 'local_number': '555-1212', @@ -1484,7 +1485,7 @@ class TextModeFile(object): client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) file_obj = TextModeFile() - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) with self.assertRaises(ValueError): table.upload_from_file(file_obj, 'CSV', size=1234) @@ -1496,7 +1497,7 @@ def test_upload_from_file_size_failure(self): client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) file_obj = object() - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) with self.assertRaises(ValueError): table.upload_from_file(file_obj, 'CSV', size=None) @@ -1516,7 +1517,7 @@ def test_upload_from_file_multipart_w_400(self): ) client = _Client(project=self.PROJECT, connection=conn) dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) with _NamedTemporaryFile() as temp: with open(temp.name, 'w') as file_obj: @@ -1556,8 +1557,8 @@ def _upload_from_file_helper(self, **kw): full_name = SchemaField('full_name', 'STRING', mode='REQUIRED') age = SchemaField('age', 'INTEGER', mode='REQUIRED') joined = SchemaField('joined', 'TIMESTAMP', mode='NULLABLE') - table = self._makeOne(self.TABLE_NAME, dataset=dataset, - schema=[full_name, age, joined]) + table = self._make_one(self.TABLE_NAME, dataset=dataset, + schema=[full_name, age, joined]) ROWS = [ ('Phred Phlyntstone', 32, WHEN), ('Bharney Rhubble', 33, WHEN + datetime.timedelta(seconds=1)), @@ -1662,7 +1663,7 @@ class _UploadConfig(object): simple_multipart = True simple_path = u'' # force resumable dataset = _Dataset(client) - table = self._makeOne(self.TABLE_NAME, dataset=dataset) + table = self._make_one(self.TABLE_NAME, dataset=dataset) with _Monkey(MUT, _UploadConfig=_UploadConfig): with _NamedTemporaryFile() as temp: @@ -1767,7 +1768,7 @@ class _UploadConfig(object): class Test_parse_schema_resource(unittest.TestCase, _SchemaBase): - def _callFUT(self, resource): + def _call_fut(self, resource): from google.cloud.bigquery.table import _parse_schema_resource return _parse_schema_resource(resource) @@ -1781,7 +1782,7 @@ def _makeResource(self): def test__parse_schema_resource_defaults(self): RESOURCE = self._makeResource() - schema = self._callFUT(RESOURCE['schema']) + schema = self._call_fut(RESOURCE['schema']) self._verifySchema(schema, RESOURCE) def test__parse_schema_resource_subfields(self): @@ -1796,7 +1797,7 @@ def test__parse_schema_resource_subfields(self): {'name': 'number', 'type': 'STRING', 'mode': 'REQUIRED'}]}) - schema = self._callFUT(RESOURCE['schema']) + schema = self._call_fut(RESOURCE['schema']) self._verifySchema(schema, RESOURCE) def test__parse_schema_resource_fields_without_mode(self): @@ -1805,13 +1806,13 @@ def test__parse_schema_resource_fields_without_mode(self): {'name': 'phone', 'type': 'STRING'}) - schema = self._callFUT(RESOURCE['schema']) + schema = self._call_fut(RESOURCE['schema']) self._verifySchema(schema, RESOURCE) class Test_build_schema_resource(unittest.TestCase, _SchemaBase): - def _callFUT(self, resource): + def _call_fut(self, resource): from google.cloud.bigquery.table import _build_schema_resource return _build_schema_resource(resource) @@ -1819,7 +1820,7 @@ 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._callFUT([full_name, age]) + resource = self._call_fut([full_name, age]) self.assertEqual(len(resource), 2) self.assertEqual(resource[0], {'name': 'full_name', @@ -1836,7 +1837,7 @@ def test_w_description(self): full_name = SchemaField('full_name', 'STRING', mode='REQUIRED', description=DESCRIPTION) age = SchemaField('age', 'INTEGER', mode='REQUIRED') - resource = self._callFUT([full_name, age]) + resource = self._call_fut([full_name, age]) self.assertEqual(len(resource), 2) self.assertEqual(resource[0], {'name': 'full_name', @@ -1855,7 +1856,7 @@ def test_w_subfields(self): ph_num = SchemaField('number', 'STRING', 'REQUIRED') phone = SchemaField('phone', 'RECORD', mode='REPEATABLE', fields=[ph_type, ph_num]) - resource = self._callFUT([full_name, phone]) + resource = self._call_fut([full_name, phone]) self.assertEqual(len(resource), 2) self.assertEqual(resource[0], {'name': 'full_name', diff --git a/bigtable/unit_tests/test_client.py b/bigtable/unit_tests/test_client.py index 94989e244775..bd880c6dc669 100644 --- a/bigtable/unit_tests/test_client.py +++ b/bigtable/unit_tests/test_client.py @@ -18,7 +18,7 @@ class Test__make_data_stub(unittest.TestCase): - def _callFUT(self, client): + def _call_fut(self, client): from google.cloud.bigtable.client import _make_data_stub return _make_data_stub(client) @@ -38,7 +38,7 @@ def mock_make_secure_stub(*args): return fake_stub with _Monkey(MUT, make_secure_stub=mock_make_secure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_secure_stub_args, [ @@ -65,7 +65,7 @@ def mock_make_insecure_stub(*args): return fake_stub with _Monkey(MUT, make_insecure_stub=mock_make_insecure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_insecure_stub_args, [ @@ -78,7 +78,7 @@ def mock_make_insecure_stub(*args): class Test__make_instance_stub(unittest.TestCase): - def _callFUT(self, client): + def _call_fut(self, client): from google.cloud.bigtable.client import _make_instance_stub return _make_instance_stub(client) @@ -98,7 +98,7 @@ def mock_make_secure_stub(*args): return fake_stub with _Monkey(MUT, make_secure_stub=mock_make_secure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_secure_stub_args, [ @@ -125,7 +125,7 @@ def mock_make_insecure_stub(*args): return fake_stub with _Monkey(MUT, make_insecure_stub=mock_make_insecure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_insecure_stub_args, [ @@ -138,7 +138,7 @@ def mock_make_insecure_stub(*args): class Test__make_operations_stub(unittest.TestCase): - def _callFUT(self, client): + def _call_fut(self, client): from google.cloud.bigtable.client import _make_operations_stub return _make_operations_stub(client) @@ -160,7 +160,7 @@ def mock_make_secure_stub(*args): return fake_stub with _Monkey(MUT, make_secure_stub=mock_make_secure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_secure_stub_args, [ @@ -189,7 +189,7 @@ def mock_make_insecure_stub(*args): return fake_stub with _Monkey(MUT, make_insecure_stub=mock_make_insecure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_insecure_stub_args, [ @@ -202,7 +202,7 @@ def mock_make_insecure_stub(*args): class Test__make_table_stub(unittest.TestCase): - def _callFUT(self, client): + def _call_fut(self, client): from google.cloud.bigtable.client import _make_table_stub return _make_table_stub(client) @@ -222,7 +222,7 @@ def mock_make_secure_stub(*args): return fake_stub with _Monkey(MUT, make_secure_stub=mock_make_secure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_secure_stub_args, [ @@ -249,7 +249,7 @@ def mock_make_insecure_stub(*args): return fake_stub with _Monkey(MUT, make_insecure_stub=mock_make_insecure_stub): - result = self._callFUT(client) + result = self._call_fut(client) self.assertIs(result, fake_stub) self.assertEqual(make_insecure_stub_args, [ @@ -267,14 +267,15 @@ class TestClient(unittest.TestCase): DISPLAY_NAME = 'display-name' USER_AGENT = 'you-sir-age-int' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.client import Client return Client - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) - def _makeOneWithMocks(self, *args, **kwargs): + def _make_oneWithMocks(self, *args, **kwargs): from google.cloud._testing import _Monkey from google.cloud.bigtable import client as MUT @@ -286,7 +287,7 @@ def _makeOneWithMocks(self, *args, **kwargs): _make_instance_stub=mock_make_instance_stub, _make_operations_stub=mock_make_operations_stub, _make_table_stub=mock_make_table_stub): - return self._makeOne(*args, **kwargs) + return self._make_one(*args, **kwargs) def _constructor_test_helper(self, expected_scopes, creds, read_only=False, admin=False, @@ -304,9 +305,9 @@ def _constructor_test_helper(self, expected_scopes, creds, _make_instance_stub=mock_make_instance_stub, _make_operations_stub=mock_make_operations_stub, _make_table_stub=mock_make_table_stub): - client = self._makeOne(project=self.PROJECT, credentials=creds, - read_only=read_only, admin=admin, - user_agent=user_agent) + client = self._make_one(project=self.PROJECT, credentials=creds, + read_only=read_only, admin=admin, + user_agent=user_agent) # Verify the mocks. self.assertEqual(mock_make_data_stub.calls, [client]) @@ -400,7 +401,7 @@ def _copy_test_helper(self, read_only=False, admin=False): from google.cloud.bigtable import client as MUT credentials = _Credentials('value') - client = self._makeOneWithMocks( + client = self._make_oneWithMocks( project=self.PROJECT, credentials=credentials, read_only=read_only, @@ -448,61 +449,61 @@ def test_copy_read_only(self): def test_credentials_getter(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials) + client = self._make_oneWithMocks(project=project, + credentials=credentials) self.assertIs(client.credentials, credentials) def test_project_name_property(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials) + client = self._make_oneWithMocks(project=project, + credentials=credentials) project_name = 'projects/' + project self.assertEqual(client.project_name, project_name) def test_instance_stub_getter(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=True) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=True) self.assertIs(client._instance_stub, client._instance_stub_internal) def test_instance_stub_non_admin_failure(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=False) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=False) with self.assertRaises(ValueError): getattr(client, '_instance_stub') def test_operations_stub_getter(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=True) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=True) self.assertIs(client._operations_stub, client._operations_stub_internal) def test_operations_stub_non_admin_failure(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=False) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=False) with self.assertRaises(ValueError): getattr(client, '_operations_stub') def test_table_stub_getter(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=True) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=True) self.assertIs(client._table_stub, client._table_stub_internal) def test_table_stub_non_admin_failure(self): credentials = _Credentials() project = 'PROJECT' - client = self._makeOneWithMocks(project=project, - credentials=credentials, admin=False) + client = self._make_oneWithMocks(project=project, + credentials=credentials, admin=False) with self.assertRaises(ValueError): getattr(client, '_table_stub') @@ -516,8 +517,8 @@ def test_instance_factory_defaults(self): INSTANCE_ID = 'instance-id' DISPLAY_NAME = 'display-name' credentials = _Credentials() - client = self._makeOneWithMocks(project=PROJECT, - credentials=credentials) + client = self._make_oneWithMocks(project=PROJECT, + credentials=credentials) instance = client.instance(INSTANCE_ID, display_name=DISPLAY_NAME) @@ -538,8 +539,8 @@ def test_instance_factory_w_explicit_serve_nodes(self): LOCATION_ID = 'locname' SERVE_NODES = 5 credentials = _Credentials() - client = self._makeOneWithMocks(project=PROJECT, - credentials=credentials) + client = self._make_oneWithMocks(project=PROJECT, + credentials=credentials) instance = client.instance( INSTANCE_ID, display_name=DISPLAY_NAME, @@ -569,7 +570,7 @@ def test_list_instances(self): 'projects/' + self.PROJECT + '/instances/' + INSTANCE_ID2) credentials = _Credentials() - client = self._makeOneWithMocks( + client = self._make_oneWithMocks( project=self.PROJECT, credentials=credentials, admin=True, diff --git a/bigtable/unit_tests/test_cluster.py b/bigtable/unit_tests/test_cluster.py index d55510ec5147..9730d9b5ab44 100644 --- a/bigtable/unit_tests/test_cluster.py +++ b/bigtable/unit_tests/test_cluster.py @@ -25,19 +25,20 @@ class TestCluster(unittest.TestCase): '/instances/' + INSTANCE_ID + '/clusters/' + CLUSTER_ID) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.cluster import Cluster return Cluster - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*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) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) self.assertEqual(cluster.cluster_id, self.CLUSTER_ID) self.assertIs(cluster._instance, instance) self.assertEqual(cluster.serve_nodes, DEFAULT_SERVE_NODES) @@ -47,8 +48,8 @@ def test_constructor_non_default(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance, - serve_nodes=SERVE_NODES) + cluster = self._make_one(self.CLUSTER_ID, instance, + serve_nodes=SERVE_NODES) self.assertEqual(cluster.cluster_id, self.CLUSTER_ID) self.assertIs(cluster._instance, instance) self.assertEqual(cluster.serve_nodes, SERVE_NODES) @@ -58,8 +59,8 @@ def test_copy(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance, - serve_nodes=SERVE_NODES) + cluster = self._make_one(self.CLUSTER_ID, instance, + serve_nodes=SERVE_NODES) new_cluster = cluster.copy() # Make sure the client copy succeeded. @@ -79,7 +80,7 @@ def test__update_from_pb_success(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) self.assertEqual(cluster.serve_nodes, DEFAULT_SERVE_NODES) cluster._update_from_pb(cluster_pb) self.assertEqual(cluster.serve_nodes, SERVE_NODES) @@ -91,7 +92,7 @@ def test__update_from_pb_no_serve_nodes(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) self.assertEqual(cluster.serve_nodes, DEFAULT_SERVE_NODES) with self.assertRaises(ValueError): cluster._update_from_pb(cluster_pb) @@ -107,7 +108,7 @@ def test_from_pb_success(self): serve_nodes=SERVE_NODES, ) - klass = self._getTargetClass() + klass = self._get_target_class() cluster = klass.from_pb(cluster_pb, instance) self.assertIsInstance(cluster, klass) self.assertIs(cluster._instance, instance) @@ -120,7 +121,7 @@ def test_from_pb_bad_cluster_name(self): instance = _Instance(self.INSTANCE_ID, client) cluster_pb = _ClusterPB(name=BAD_CLUSTER_NAME) - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_pb(cluster_pb, instance) @@ -133,7 +134,7 @@ def test_from_pb_project_mistmatch(self): cluster_pb = _ClusterPB(name=self.CLUSTER_NAME) - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_pb(cluster_pb, instance) @@ -146,7 +147,7 @@ def test_from_pb_instance_mistmatch(self): cluster_pb = _ClusterPB(name=self.CLUSTER_NAME) - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_pb(cluster_pb, instance) @@ -154,36 +155,36 @@ def test_name_property(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) self.assertEqual(cluster.name, self.CLUSTER_NAME) def test___eq__(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster1 = self._makeOne(self.CLUSTER_ID, instance) - cluster2 = self._makeOne(self.CLUSTER_ID, instance) + cluster1 = self._make_one(self.CLUSTER_ID, instance) + cluster2 = self._make_one(self.CLUSTER_ID, instance) self.assertEqual(cluster1, cluster2) def test___eq__type_differ(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster1 = self._makeOne(self.CLUSTER_ID, instance) + cluster1 = self._make_one(self.CLUSTER_ID, instance) cluster2 = object() self.assertNotEqual(cluster1, cluster2) def test___ne__same_value(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster1 = self._makeOne(self.CLUSTER_ID, instance) - cluster2 = self._makeOne(self.CLUSTER_ID, instance) + cluster1 = self._make_one(self.CLUSTER_ID, instance) + cluster2 = self._make_one(self.CLUSTER_ID, instance) comparison_val = (cluster1 != cluster2) self.assertFalse(comparison_val) def test___ne__(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster1 = self._makeOne('cluster_id1', instance) - cluster2 = self._makeOne('cluster_id2', instance) + cluster1 = self._make_one('cluster_id1', instance) + cluster2 = self._make_one('cluster_id2', instance) self.assertNotEqual(cluster1, cluster2) def test_reload(self): @@ -194,7 +195,7 @@ def test_reload(self): LOCATION = 'LOCATION' client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) # Create request_pb request_pb = _GetClusterRequestPB(name=self.CLUSTER_NAME) @@ -237,7 +238,7 @@ def test_create(self): SERVE_NODES = 4 client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne( + cluster = self._make_one( self.CLUSTER_ID, instance, serve_nodes=SERVE_NODES) # Create response_pb @@ -291,8 +292,8 @@ def test_update(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance, - serve_nodes=SERVE_NODES) + cluster = self._make_one(self.CLUSTER_ID, instance, + serve_nodes=SERVE_NODES) # Create request_pb request_pb = _ClusterPB( @@ -346,7 +347,7 @@ def test_delete(self): client = _Client(self.PROJECT) instance = _Instance(self.INSTANCE_ID, client) - cluster = self._makeOne(self.CLUSTER_ID, instance) + cluster = self._make_one(self.CLUSTER_ID, instance) # Create request_pb request_pb = _DeleteClusterRequestPB(name=self.CLUSTER_NAME) @@ -373,7 +374,7 @@ def test_delete(self): class Test__prepare_create_request(unittest.TestCase): - def _callFUT(self, cluster): + def _call_fut(self, cluster): from google.cloud.bigtable.cluster import _prepare_create_request return _prepare_create_request(cluster) @@ -390,7 +391,7 @@ def test_it(self): cluster = Cluster(CLUSTER_ID, instance, serve_nodes=SERVE_NODES) - request_pb = self._callFUT(cluster) + request_pb = self._call_fut(cluster) self.assertEqual(request_pb.cluster_id, CLUSTER_ID) self.assertEqual(request_pb.parent, instance.name) diff --git a/bigtable/unit_tests/test_column_family.py b/bigtable/unit_tests/test_column_family.py index dee8db4e169b..90baf9193691 100644 --- a/bigtable/unit_tests/test_column_family.py +++ b/bigtable/unit_tests/test_column_family.py @@ -18,7 +18,7 @@ class Test__timedelta_to_duration_pb(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.bigtable.column_family import ( _timedelta_to_duration_pb) return _timedelta_to_duration_pb(*args, **kwargs) @@ -30,7 +30,7 @@ def test_it(self): seconds = microseconds = 1 timedelta_val = datetime.timedelta(seconds=seconds, microseconds=microseconds) - result = self._callFUT(timedelta_val) + result = self._call_fut(timedelta_val) self.assertIsInstance(result, duration_pb2.Duration) self.assertEqual(result.seconds, seconds) self.assertEqual(result.nanos, 1000 * microseconds) @@ -43,7 +43,7 @@ def test_with_negative_microseconds(self): microseconds = -5 timedelta_val = datetime.timedelta(seconds=seconds, microseconds=microseconds) - result = self._callFUT(timedelta_val) + result = self._call_fut(timedelta_val) self.assertIsInstance(result, duration_pb2.Duration) self.assertEqual(result.seconds, seconds - 1) self.assertEqual(result.nanos, 10**9 + 1000 * microseconds) @@ -56,7 +56,7 @@ def test_with_negative_seconds(self): microseconds = 5 timedelta_val = datetime.timedelta(seconds=seconds, microseconds=microseconds) - result = self._callFUT(timedelta_val) + result = self._call_fut(timedelta_val) self.assertIsInstance(result, duration_pb2.Duration) self.assertEqual(result.seconds, seconds + 1) self.assertEqual(result.nanos, -(10**9 - 1000 * microseconds)) @@ -64,7 +64,7 @@ def test_with_negative_seconds(self): class Test__duration_pb_to_timedelta(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.bigtable.column_family import ( _duration_pb_to_timedelta) return _duration_pb_to_timedelta(*args, **kwargs) @@ -78,39 +78,40 @@ def test_it(self): nanos=1000 * microseconds) timedelta_val = datetime.timedelta(seconds=seconds, microseconds=microseconds) - result = self._callFUT(duration_pb) + result = self._call_fut(duration_pb) self.assertIsInstance(result, datetime.timedelta) self.assertEqual(result, timedelta_val) class TestMaxVersionsGCRule(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.column_family import MaxVersionsGCRule return MaxVersionsGCRule - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test___eq__type_differ(self): - gc_rule1 = self._makeOne(10) + gc_rule1 = self._make_one(10) gc_rule2 = object() self.assertNotEqual(gc_rule1, gc_rule2) def test___eq__same_value(self): - gc_rule1 = self._makeOne(2) - gc_rule2 = self._makeOne(2) + gc_rule1 = self._make_one(2) + gc_rule2 = self._make_one(2) self.assertEqual(gc_rule1, gc_rule2) def test___ne__same_value(self): - gc_rule1 = self._makeOne(99) - gc_rule2 = self._makeOne(99) + gc_rule1 = self._make_one(99) + gc_rule2 = self._make_one(99) comparison_val = (gc_rule1 != gc_rule2) self.assertFalse(comparison_val) def test_to_pb(self): max_num_versions = 1337 - gc_rule = self._makeOne(max_num_versions=max_num_versions) + gc_rule = self._make_one(max_num_versions=max_num_versions) pb_val = gc_rule.to_pb() expected = _GcRulePB(max_num_versions=max_num_versions) self.assertEqual(pb_val, expected) @@ -118,29 +119,30 @@ def test_to_pb(self): class TestMaxAgeGCRule(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.column_family import MaxAgeGCRule return MaxAgeGCRule - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test___eq__type_differ(self): max_age = object() - gc_rule1 = self._makeOne(max_age=max_age) + gc_rule1 = self._make_one(max_age=max_age) gc_rule2 = object() self.assertNotEqual(gc_rule1, gc_rule2) def test___eq__same_value(self): max_age = object() - gc_rule1 = self._makeOne(max_age=max_age) - gc_rule2 = self._makeOne(max_age=max_age) + gc_rule1 = self._make_one(max_age=max_age) + gc_rule2 = self._make_one(max_age=max_age) self.assertEqual(gc_rule1, gc_rule2) def test___ne__same_value(self): max_age = object() - gc_rule1 = self._makeOne(max_age=max_age) - gc_rule2 = self._makeOne(max_age=max_age) + gc_rule1 = self._make_one(max_age=max_age) + gc_rule2 = self._make_one(max_age=max_age) comparison_val = (gc_rule1 != gc_rule2) self.assertFalse(comparison_val) @@ -150,41 +152,42 @@ def test_to_pb(self): max_age = datetime.timedelta(seconds=1) duration = duration_pb2.Duration(seconds=1) - gc_rule = self._makeOne(max_age=max_age) + gc_rule = self._make_one(max_age=max_age) pb_val = gc_rule.to_pb() self.assertEqual(pb_val, _GcRulePB(max_age=duration)) class TestGCRuleUnion(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.column_family import GCRuleUnion return GCRuleUnion - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): rules = object() - rule_union = self._makeOne(rules) + rule_union = self._make_one(rules) self.assertIs(rule_union.rules, rules) def test___eq__(self): rules = object() - gc_rule1 = self._makeOne(rules) - gc_rule2 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) + gc_rule2 = self._make_one(rules) self.assertEqual(gc_rule1, gc_rule2) def test___eq__type_differ(self): rules = object() - gc_rule1 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) gc_rule2 = object() self.assertNotEqual(gc_rule1, gc_rule2) def test___ne__same_value(self): rules = object() - gc_rule1 = self._makeOne(rules) - gc_rule2 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) + gc_rule2 = self._make_one(rules) comparison_val = (gc_rule1 != gc_rule2) self.assertFalse(comparison_val) @@ -203,7 +206,7 @@ def test_to_pb(self): pb_rule2 = _GcRulePB( max_age=duration_pb2.Duration(seconds=1)) - rule3 = self._makeOne(rules=[rule1, rule2]) + rule3 = self._make_one(rules=[rule1, rule2]) pb_rule3 = _GcRulePB( union=_GcRuleUnionPB(rules=[pb_rule1, pb_rule2])) @@ -225,7 +228,7 @@ def test_to_pb_nested(self): pb_rule2 = _GcRulePB( max_age=duration_pb2.Duration(seconds=1)) - rule3 = self._makeOne(rules=[rule1, rule2]) + rule3 = self._make_one(rules=[rule1, rule2]) pb_rule3 = _GcRulePB( union=_GcRuleUnionPB(rules=[pb_rule1, pb_rule2])) @@ -233,7 +236,7 @@ def test_to_pb_nested(self): rule4 = MaxVersionsGCRule(max_num_versions2) pb_rule4 = _GcRulePB(max_num_versions=max_num_versions2) - rule5 = self._makeOne(rules=[rule3, rule4]) + rule5 = self._make_one(rules=[rule3, rule4]) pb_rule5 = _GcRulePB( union=_GcRuleUnionPB(rules=[pb_rule3, pb_rule4])) @@ -243,34 +246,35 @@ def test_to_pb_nested(self): class TestGCRuleIntersection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.column_family import GCRuleIntersection return GCRuleIntersection - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): rules = object() - rule_intersection = self._makeOne(rules) + rule_intersection = self._make_one(rules) self.assertIs(rule_intersection.rules, rules) def test___eq__(self): rules = object() - gc_rule1 = self._makeOne(rules) - gc_rule2 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) + gc_rule2 = self._make_one(rules) self.assertEqual(gc_rule1, gc_rule2) def test___eq__type_differ(self): rules = object() - gc_rule1 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) gc_rule2 = object() self.assertNotEqual(gc_rule1, gc_rule2) def test___ne__same_value(self): rules = object() - gc_rule1 = self._makeOne(rules) - gc_rule2 = self._makeOne(rules) + gc_rule1 = self._make_one(rules) + gc_rule2 = self._make_one(rules) comparison_val = (gc_rule1 != gc_rule2) self.assertFalse(comparison_val) @@ -289,7 +293,7 @@ def test_to_pb(self): pb_rule2 = _GcRulePB( max_age=duration_pb2.Duration(seconds=1)) - rule3 = self._makeOne(rules=[rule1, rule2]) + rule3 = self._make_one(rules=[rule1, rule2]) pb_rule3 = _GcRulePB( intersection=_GcRuleIntersectionPB( rules=[pb_rule1, pb_rule2])) @@ -312,7 +316,7 @@ def test_to_pb_nested(self): pb_rule2 = _GcRulePB( max_age=duration_pb2.Duration(seconds=1)) - rule3 = self._makeOne(rules=[rule1, rule2]) + rule3 = self._make_one(rules=[rule1, rule2]) pb_rule3 = _GcRulePB( intersection=_GcRuleIntersectionPB( rules=[pb_rule1, pb_rule2])) @@ -321,7 +325,7 @@ def test_to_pb_nested(self): rule4 = MaxVersionsGCRule(max_num_versions2) pb_rule4 = _GcRulePB(max_num_versions=max_num_versions2) - rule5 = self._makeOne(rules=[rule3, rule4]) + rule5 = self._make_one(rules=[rule3, rule4]) pb_rule5 = _GcRulePB( intersection=_GcRuleIntersectionPB( rules=[pb_rule3, pb_rule4])) @@ -332,18 +336,19 @@ def test_to_pb_nested(self): class TestColumnFamily(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.column_family import ColumnFamily return ColumnFamily - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): column_family_id = u'column-family-id' table = object() gc_rule = object() - column_family = self._makeOne( + column_family = self._make_one( column_family_id, table, gc_rule=gc_rule) self.assertEqual(column_family.column_family_id, column_family_id) @@ -354,7 +359,7 @@ def test_name_property(self): column_family_id = u'column-family-id' table_name = 'table_name' table = _Table(table_name) - column_family = self._makeOne(column_family_id, table) + column_family = self._make_one(column_family_id, table) expected_name = table_name + '/columnFamilies/' + column_family_id self.assertEqual(column_family.name, expected_name) @@ -363,14 +368,14 @@ def test___eq__(self): column_family_id = 'column_family_id' table = object() gc_rule = object() - column_family1 = self._makeOne(column_family_id, table, - gc_rule=gc_rule) - column_family2 = self._makeOne(column_family_id, table, - gc_rule=gc_rule) + column_family1 = self._make_one(column_family_id, table, + gc_rule=gc_rule) + column_family2 = self._make_one(column_family_id, table, + gc_rule=gc_rule) self.assertEqual(column_family1, column_family2) def test___eq__type_differ(self): - column_family1 = self._makeOne('column_family_id', None) + column_family1 = self._make_one('column_family_id', None) column_family2 = object() self.assertNotEqual(column_family1, column_family2) @@ -378,20 +383,20 @@ def test___ne__same_value(self): column_family_id = 'column_family_id' table = object() gc_rule = object() - column_family1 = self._makeOne(column_family_id, table, - gc_rule=gc_rule) - column_family2 = self._makeOne(column_family_id, table, - gc_rule=gc_rule) + column_family1 = self._make_one(column_family_id, table, + gc_rule=gc_rule) + column_family2 = self._make_one(column_family_id, table, + gc_rule=gc_rule) comparison_val = (column_family1 != column_family2) self.assertFalse(comparison_val) def test___ne__(self): - column_family1 = self._makeOne('column_family_id1', None) - column_family2 = self._makeOne('column_family_id2', None) + column_family1 = self._make_one('column_family_id1', None) + column_family2 = self._make_one('column_family_id2', None) self.assertNotEqual(column_family1, column_family2) def test_to_pb_no_rules(self): - column_family = self._makeOne('column_family_id', None) + column_family = self._make_one('column_family_id', None) pb_val = column_family.to_pb() expected = _ColumnFamilyPB() self.assertEqual(pb_val, expected) @@ -400,8 +405,8 @@ def test_to_pb_with_rule(self): from google.cloud.bigtable.column_family import MaxVersionsGCRule gc_rule = MaxVersionsGCRule(1) - column_family = self._makeOne('column_family_id', None, - gc_rule=gc_rule) + column_family = self._make_one('column_family_id', None, + gc_rule=gc_rule) pb_val = column_family.to_pb() expected = _ColumnFamilyPB(gc_rule=gc_rule.to_pb()) self.assertEqual(pb_val, expected) @@ -421,7 +426,7 @@ def _create_test_helper(self, gc_rule=None): client = _Client() table = _Table(table_name, client=client) - column_family = self._makeOne( + column_family = self._make_one( column_family_id, table, gc_rule=gc_rule) # Create request_pb @@ -479,7 +484,7 @@ def _update_test_helper(self, gc_rule=None): client = _Client() table = _Table(table_name, client=client) - column_family = self._makeOne( + column_family = self._make_one( column_family_id, table, gc_rule=gc_rule) # Create request_pb @@ -538,7 +543,7 @@ def test_delete(self): client = _Client() table = _Table(table_name, client=client) - column_family = self._makeOne(column_family_id, table) + column_family = self._make_one(column_family_id, table) # Create request_pb request_pb = table_admin_v2_pb2.ModifyColumnFamiliesRequest( @@ -570,21 +575,21 @@ def test_delete(self): class Test__gc_rule_from_pb(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + 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): gc_rule_pb = _GcRulePB() - self.assertIsNone(self._callFUT(gc_rule_pb)) + self.assertIsNone(self._call_fut(gc_rule_pb)) def test_max_num_versions(self): from google.cloud.bigtable.column_family import MaxVersionsGCRule orig_rule = MaxVersionsGCRule(1) gc_rule_pb = orig_rule.to_pb() - result = self._callFUT(gc_rule_pb) + result = self._call_fut(gc_rule_pb) self.assertIsInstance(result, MaxVersionsGCRule) self.assertEqual(result, orig_rule) @@ -594,7 +599,7 @@ def test_max_age(self): orig_rule = MaxAgeGCRule(datetime.timedelta(seconds=1)) gc_rule_pb = orig_rule.to_pb() - result = self._callFUT(gc_rule_pb) + result = self._call_fut(gc_rule_pb) self.assertIsInstance(result, MaxAgeGCRule) self.assertEqual(result, orig_rule) @@ -608,7 +613,7 @@ def test_union(self): rule2 = MaxAgeGCRule(datetime.timedelta(seconds=1)) orig_rule = GCRuleUnion([rule1, rule2]) gc_rule_pb = orig_rule.to_pb() - result = self._callFUT(gc_rule_pb) + result = self._call_fut(gc_rule_pb) self.assertIsInstance(result, GCRuleUnion) self.assertEqual(result, orig_rule) @@ -622,7 +627,7 @@ def test_intersection(self): rule2 = MaxAgeGCRule(datetime.timedelta(seconds=1)) orig_rule = GCRuleIntersection([rule1, rule2]) gc_rule_pb = orig_rule.to_pb() - result = self._callFUT(gc_rule_pb) + result = self._call_fut(gc_rule_pb) self.assertIsInstance(result, GCRuleIntersection) self.assertEqual(result, orig_rule) @@ -637,7 +642,7 @@ def WhichOneof(cls, name): return 'unknown' self.assertEqual(MockProto.names, []) - self.assertRaises(ValueError, self._callFUT, MockProto) + self.assertRaises(ValueError, self._call_fut, MockProto) self.assertEqual(MockProto.names, ['rule']) diff --git a/bigtable/unit_tests/test_instance.py b/bigtable/unit_tests/test_instance.py index 73d1cce7ff82..84bc0e6346ea 100644 --- a/bigtable/unit_tests/test_instance.py +++ b/bigtable/unit_tests/test_instance.py @@ -30,18 +30,19 @@ class TestInstance(unittest.TestCase): TABLE_ID = 'table_id' TABLE_NAME = INSTANCE_NAME + '/tables/' + TABLE_ID - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.instance import Instance return Instance - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor_defaults(self): from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES client = object() - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) self.assertEqual(instance.instance_id, self.INSTANCE_ID) self.assertEqual(instance.display_name, self.INSTANCE_ID) self.assertIs(instance._client, client) @@ -52,8 +53,8 @@ def test_constructor_non_default(self): display_name = 'display_name' client = object() - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID, - display_name=display_name) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID, + display_name=display_name) self.assertEqual(instance.instance_id, self.INSTANCE_ID) self.assertEqual(instance.display_name, display_name) self.assertIs(instance._client, client) @@ -62,8 +63,8 @@ def test_copy(self): display_name = 'display_name' client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID, - display_name=display_name) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID, + display_name=display_name) new_instance = instance.copy() # Make sure the client copy succeeded. @@ -76,7 +77,7 @@ def test_copy(self): def test_table_factory(self): from google.cloud.bigtable.table import Table - instance = self._makeOne(self.INSTANCE_ID, None, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, None, self.LOCATION_ID) table = instance.table(self.TABLE_ID) self.assertIsInstance(table, Table) @@ -92,7 +93,7 @@ def test__update_from_pb_success(self): display_name=display_name, ) - instance = self._makeOne(None, None, None, None) + instance = self._make_one(None, None, None, None) self.assertIsNone(instance.display_name) instance._update_from_pb(instance_pb) self.assertEqual(instance.display_name, display_name) @@ -102,7 +103,7 @@ def test__update_from_pb_no_display_name(self): instance_pb2 as data_v2_pb2) instance_pb = data_v2_pb2.Instance() - instance = self._makeOne(None, None, None, None) + instance = self._make_one(None, None, None, None) self.assertIsNone(instance.display_name) with self.assertRaises(ValueError): instance._update_from_pb(instance_pb) @@ -121,7 +122,7 @@ def test_from_pb_success(self): display_name=self.INSTANCE_ID, ) - klass = self._getTargetClass() + klass = self._get_target_class() instance = klass.from_pb(instance_pb, client) self.assertIsInstance(instance, klass) self.assertEqual(instance._client, client) @@ -136,7 +137,7 @@ def test_from_pb_bad_instance_name(self): instance_name = 'INCORRECT_FORMAT' instance_pb = data_v2_pb2.Instance(name=instance_name) - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_pb(instance_pb, None) @@ -151,38 +152,38 @@ def test_from_pb_project_mistmatch(self): instance_pb = data_v2_pb2.Instance(name=self.INSTANCE_NAME) - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_pb(instance_pb, client) def test_name_property(self): client = _Client(project=self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) self.assertEqual(instance.name, self.INSTANCE_NAME) def test___eq__(self): client = object() - instance1 = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) - instance2 = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance1 = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) + instance2 = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) self.assertEqual(instance1, instance2) def test___eq__type_differ(self): client = object() - instance1 = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance1 = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) instance2 = object() self.assertNotEqual(instance1, instance2) def test___ne__same_value(self): client = object() - instance1 = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) - instance2 = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance1 = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) + instance2 = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) comparison_val = (instance1 != instance2) self.assertFalse(comparison_val) def test___ne__(self): - instance1 = self._makeOne('instance_id1', 'client1', self.LOCATION_ID) - instance2 = self._makeOne('instance_id2', 'client2', self.LOCATION_ID) + instance1 = self._make_one('instance_id1', 'client1', self.LOCATION_ID) + instance2 = self._make_one('instance_id2', 'client2', self.LOCATION_ID) self.assertNotEqual(instance1, instance2) def test_reload(self): @@ -193,7 +194,7 @@ def test_reload(self): from unit_tests._testing import _FakeStub client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) # Create request_pb request_pb = messages_v2_pb.GetInstanceRequest( @@ -240,8 +241,8 @@ def test_create(self): NOW = datetime.datetime.utcnow() NOW_PB = _datetime_to_pb_timestamp(NOW) client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID, - display_name=self.DISPLAY_NAME) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID, + display_name=self.DISPLAY_NAME) # Create response_pb metadata = messages_v2_pb2.CreateInstanceMetadata(request_time=NOW_PB) @@ -294,8 +295,8 @@ def test_create_w_explicit_serve_nodes(self): SERVE_NODES = 5 client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID, - serve_nodes=SERVE_NODES) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID, + serve_nodes=SERVE_NODES) # Create response_pb response_pb = operations_pb2.Operation(name=self.OP_NAME) @@ -330,8 +331,8 @@ def test_update(self): from unit_tests._testing import _FakeStub client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID, - display_name=self.DISPLAY_NAME) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID, + display_name=self.DISPLAY_NAME) # Create request_pb request_pb = data_v2_pb2.Instance( @@ -365,7 +366,7 @@ def test_delete(self): from unit_tests._testing import _FakeStub client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) # Create request_pb request_pb = messages_v2_pb.DeleteInstanceRequest( @@ -404,7 +405,7 @@ def test_list_clusters(self): SERVE_NODES = 4 client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) CLUSTER_NAME1 = (instance.name + '/clusters/' + CLUSTER_ID1) CLUSTER_NAME2 = (instance.name + '/clusters/' + CLUSTER_ID2) @@ -455,7 +456,7 @@ def _list_tables_helper(self, table_name=None): from unit_tests._testing import _FakeStub client = _Client(self.PROJECT) - instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID) + instance = self._make_one(self.INSTANCE_ID, client, self.LOCATION_ID) # Create request_ request_pb = table_messages_v1_pb2.ListTablesRequest( @@ -513,7 +514,7 @@ class Test__prepare_create_request(unittest.TestCase): INSTANCE_NAME = PARENT + '/instances/' + INSTANCE_ID CLUSTER_NAME = INSTANCE_NAME + '/clusters/' + INSTANCE_ID - def _callFUT(self, instance, **kw): + def _call_fut(self, instance, **kw): from google.cloud.bigtable.instance import _prepare_create_request return _prepare_create_request(instance, **kw) @@ -528,7 +529,7 @@ def test_w_defaults(self): client = _Client(self.PROJECT) instance = Instance(self.INSTANCE_ID, client, self.LOCATION_ID) - request_pb = self._callFUT(instance) + request_pb = self._call_fut(instance) self.assertIsInstance(request_pb, messages_v2_pb.CreateInstanceRequest) self.assertEqual(request_pb.instance_id, self.INSTANCE_ID) @@ -557,7 +558,7 @@ def test_w_explicit_serve_nodes(self): display_name=DISPLAY_NAME, serve_nodes=SERVE_NODES) - request_pb = self._callFUT(instance) + request_pb = self._call_fut(instance) self.assertIsInstance(request_pb, messages_v2_pb.CreateInstanceRequest) diff --git a/bigtable/unit_tests/test_row.py b/bigtable/unit_tests/test_row.py index d40d6b64b720..c3321a12eec1 100644 --- a/bigtable/unit_tests/test_row.py +++ b/bigtable/unit_tests/test_row.py @@ -18,33 +18,35 @@ class Test_SetDeleteRow(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row import _SetDeleteRow return _SetDeleteRow - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test__get_mutations_virtual(self): - row = self._makeOne(b'row-key', None) + row = self._make_one(b'row-key', None) with self.assertRaises(NotImplementedError): row._get_mutations(None) class TestDirectRow(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row import DirectRow return DirectRow - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): row_key = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._row_key, row_key) self.assertIs(row._table, table) self.assertEqual(row._pb_mutations, []) @@ -54,18 +56,18 @@ def test_constructor_with_unicode(self): row_key_bytes = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._row_key, row_key_bytes) self.assertIs(row._table, table) def test_constructor_with_non_bytes(self): row_key = object() with self.assertRaises(TypeError): - self._makeOne(row_key, None) + self._make_one(row_key, None) def test__get_mutations(self): row_key = b'row_key' - row = self._makeOne(row_key, None) + row = self._make_one(row_key, None) row._pb_mutations = mutations = object() self.assertIs(mutations, row._get_mutations(None)) @@ -80,7 +82,7 @@ def _set_cell_helper(self, column=None, column_bytes=None, if column is None: column = b'column' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._pb_mutations, []) row.set_cell(column_family_id, column, value, timestamp=timestamp) @@ -116,7 +118,7 @@ def test_set_cell_with_non_bytes_value(self): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) value = object() # Not bytes with self.assertRaises(TypeError): row.set_cell(column_family_id, column, value) @@ -133,7 +135,7 @@ def test_set_cell_with_non_null_timestamp(self): def test_delete(self): row_key = b'row_key' - row = self._makeOne(row_key, object()) + row = self._make_one(row_key, object()) self.assertEqual(row._pb_mutations, []) row.delete() @@ -143,7 +145,7 @@ def test_delete(self): self.assertEqual(row._pb_mutations, [expected_pb]) def test_delete_cell(self): - klass = self._getTargetClass() + klass = self._get_target_class() class MockRow(klass): @@ -183,7 +185,7 @@ def test_delete_cells_non_iterable(self): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) columns = object() # Not iterable with self.assertRaises(TypeError): row.delete_cells(column_family_id, columns) @@ -193,8 +195,8 @@ def test_delete_cells_all_columns(self): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) - klass = self._getTargetClass() + row = self._make_one(row_key, table) + klass = self._get_target_class() self.assertEqual(row._pb_mutations, []) row.delete_cells(column_family_id, klass.ALL_COLUMNS) @@ -210,7 +212,7 @@ def test_delete_cells_no_columns(self): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) columns = [] self.assertEqual(row._pb_mutations, []) row.delete_cells(column_family_id, columns) @@ -222,7 +224,7 @@ def _delete_cells_helper(self, time_range=None): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) columns = [column] self.assertEqual(row._pb_mutations, []) row.delete_cells(column_family_id, columns, time_range=time_range) @@ -259,7 +261,7 @@ def test_delete_cells_with_bad_column(self): column_family_id = u'column_family_id' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) columns = [column, object()] self.assertEqual(row._pb_mutations, []) with self.assertRaises(TypeError): @@ -275,7 +277,7 @@ def test_delete_cells_with_string_columns(self): column2_bytes = b'column2' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) columns = [column1, column2] self.assertEqual(row._pb_mutations, []) row.delete_cells(column_family_id, columns) @@ -304,7 +306,7 @@ def test_commit(self): column = b'column' client = _Client() table = _Table(table_name, client=client) - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) # Create request_pb value = b'bytes-value' @@ -348,7 +350,7 @@ def test_commit_too_many_mutations(self): row_key = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) row._pb_mutations = [1, 2, 3] num_mutations = len(row._pb_mutations) with _Monkey(MUT, MAX_MUTATIONS=num_mutations - 1): @@ -361,7 +363,7 @@ def test_commit_no_mutations(self): row_key = b'row_key' client = _Client() table = _Table(None, client=client) - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._pb_mutations, []) # Patch the stub used by the API method. @@ -376,19 +378,20 @@ def test_commit_no_mutations(self): class TestConditionalRow(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row import ConditionalRow return ConditionalRow - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): row_key = b'row_key' table = object() filter_ = object() - row = self._makeOne(row_key, table, filter_=filter_) + row = self._make_one(row_key, table, filter_=filter_) self.assertEqual(row._row_key, row_key) self.assertIs(row._table, table) self.assertIs(row._filter, filter_) @@ -398,7 +401,7 @@ def test_constructor(self): def test__get_mutations(self): row_key = b'row_key' filter_ = object() - row = self._makeOne(row_key, None, filter_=filter_) + row = self._make_one(row_key, None, filter_=filter_) row._true_pb_mutations = true_mutations = object() row._false_pb_mutations = false_mutations = object() @@ -420,7 +423,7 @@ def test_commit(self): client = _Client() table = _Table(table_name, client=client) row_filter = RowSampleFilter(0.33) - row = self._makeOne(row_key, table, filter_=row_filter) + row = self._make_one(row_key, table, filter_=row_filter) # Create request_pb value1 = b'bytes-value' @@ -487,7 +490,7 @@ def test_commit_too_many_mutations(self): row_key = b'row_key' table = object() filter_ = object() - row = self._makeOne(row_key, table, filter_=filter_) + row = self._make_one(row_key, table, filter_=filter_) row._true_pb_mutations = [1, 2, 3] num_mutations = len(row._true_pb_mutations) with _Monkey(MUT, MAX_MUTATIONS=num_mutations - 1): @@ -501,7 +504,7 @@ def test_commit_no_mutations(self): client = _Client() table = _Table(None, client=client) filter_ = object() - row = self._makeOne(row_key, table, filter_=filter_) + row = self._make_one(row_key, table, filter_=filter_) self.assertEqual(row._true_pb_mutations, []) self.assertEqual(row._false_pb_mutations, []) @@ -517,18 +520,19 @@ def test_commit_no_mutations(self): class TestAppendRow(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row import AppendRow return AppendRow - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): row_key = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._row_key, row_key) self.assertIs(row._table, table) self.assertEqual(row._rule_pb_list, []) @@ -536,7 +540,7 @@ def test_constructor(self): def test_clear(self): row_key = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) row._rule_pb_list = [1, 2, 3] row.clear() self.assertEqual(row._rule_pb_list, []) @@ -544,7 +548,7 @@ def test_clear(self): def test_append_cell_value(self): table = object() row_key = b'row_key' - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._rule_pb_list, []) column = b'column' @@ -559,7 +563,7 @@ def test_append_cell_value(self): def test_increment_cell_value(self): table = object() row_key = b'row_key' - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._rule_pb_list, []) column = b'column' @@ -582,7 +586,7 @@ def test_commit(self): column = b'column' client = _Client() table = _Table(table_name, client=client) - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) # Create request_pb value = b'bytes-value' @@ -633,7 +637,7 @@ def test_commit_no_rules(self): row_key = b'row_key' client = _Client() table = _Table(None, client=client) - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) self.assertEqual(row._rule_pb_list, []) # Patch the stub used by the API method. @@ -651,7 +655,7 @@ def test_commit_too_many_mutations(self): row_key = b'row_key' table = object() - row = self._makeOne(row_key, table) + row = self._make_one(row_key, table) row._rule_pb_list = [1, 2, 3] num_mutations = len(row._rule_pb_list) with _Monkey(MUT, MAX_MUTATIONS=num_mutations - 1): @@ -661,7 +665,7 @@ def test_commit_too_many_mutations(self): class Test__parse_rmw_row_response(unittest.TestCase): - def _callFUT(self, row_response): + def _call_fut(self, row_response): from google.cloud.bigtable.row import _parse_rmw_row_response return _parse_rmw_row_response(row_response) @@ -741,12 +745,12 @@ def test_it(self): ], ) sample_input = _ReadModifyWriteRowResponsePB(row=response_row) - self.assertEqual(expected_output, self._callFUT(sample_input)) + self.assertEqual(expected_output, self._call_fut(sample_input)) class Test__parse_family_pb(unittest.TestCase): - def _callFUT(self, family_pb): + def _call_fut(self, family_pb): from google.cloud.bigtable.row import _parse_family_pb return _parse_family_pb(family_pb) @@ -798,7 +802,7 @@ def test_it(self): ), ], ) - self.assertEqual(expected_output, self._callFUT(sample_input)) + self.assertEqual(expected_output, self._call_fut(sample_input)) def _CheckAndMutateRowRequestPB(*args, **kw): diff --git a/bigtable/unit_tests/test_row_data.py b/bigtable/unit_tests/test_row_data.py index daa823aeee1b..8e5d72125f5d 100644 --- a/bigtable/unit_tests/test_row_data.py +++ b/bigtable/unit_tests/test_row_data.py @@ -18,12 +18,13 @@ class TestCell(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_data import Cell return Cell - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def _from_pb_test_helper(self, labels=None): import datetime @@ -38,13 +39,13 @@ def _from_pb_test_helper(self, labels=None): if labels is None: cell_pb = data_v2_pb2.Cell( value=value, timestamp_micros=timestamp_micros) - cell_expected = self._makeOne(value, timestamp) + cell_expected = self._make_one(value, timestamp) else: cell_pb = data_v2_pb2.Cell( value=value, timestamp_micros=timestamp_micros, labels=labels) - cell_expected = self._makeOne(value, timestamp, labels=labels) + cell_expected = self._make_one(value, timestamp, labels=labels) - klass = self._getTargetClass() + klass = self._get_target_class() result = klass.from_pb(cell_pb) self.assertEqual(result, cell_expected) @@ -58,27 +59,27 @@ def test_from_pb_with_labels(self): def test_constructor(self): value = object() timestamp = object() - cell = self._makeOne(value, timestamp) + cell = self._make_one(value, timestamp) self.assertEqual(cell.value, value) self.assertEqual(cell.timestamp, timestamp) def test___eq__(self): value = object() timestamp = object() - cell1 = self._makeOne(value, timestamp) - cell2 = self._makeOne(value, timestamp) + cell1 = self._make_one(value, timestamp) + cell2 = self._make_one(value, timestamp) self.assertEqual(cell1, cell2) def test___eq__type_differ(self): - cell1 = self._makeOne(None, None) + cell1 = self._make_one(None, None) cell2 = object() self.assertNotEqual(cell1, cell2) def test___ne__same_value(self): value = object() timestamp = object() - cell1 = self._makeOne(value, timestamp) - cell2 = self._makeOne(value, timestamp) + cell1 = self._make_one(value, timestamp) + cell2 = self._make_one(value, timestamp) comparison_val = (cell1 != cell2) self.assertFalse(comparison_val) @@ -86,56 +87,57 @@ def test___ne__(self): value1 = 'value1' value2 = 'value2' timestamp = object() - cell1 = self._makeOne(value1, timestamp) - cell2 = self._makeOne(value2, timestamp) + cell1 = self._make_one(value1, timestamp) + cell2 = self._make_one(value2, timestamp) self.assertNotEqual(cell1, cell2) class TestPartialRowData(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowData return PartialRowData - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): row_key = object() - partial_row_data = self._makeOne(row_key) + partial_row_data = self._make_one(row_key) self.assertIs(partial_row_data._row_key, row_key) self.assertEqual(partial_row_data._cells, {}) def test___eq__(self): row_key = object() - partial_row_data1 = self._makeOne(row_key) - partial_row_data2 = self._makeOne(row_key) + partial_row_data1 = self._make_one(row_key) + partial_row_data2 = self._make_one(row_key) self.assertEqual(partial_row_data1, partial_row_data2) def test___eq__type_differ(self): - partial_row_data1 = self._makeOne(None) + partial_row_data1 = self._make_one(None) partial_row_data2 = object() self.assertNotEqual(partial_row_data1, partial_row_data2) def test___ne__same_value(self): row_key = object() - partial_row_data1 = self._makeOne(row_key) - partial_row_data2 = self._makeOne(row_key) + partial_row_data1 = self._make_one(row_key) + partial_row_data2 = self._make_one(row_key) comparison_val = (partial_row_data1 != partial_row_data2) self.assertFalse(comparison_val) def test___ne__(self): row_key1 = object() - partial_row_data1 = self._makeOne(row_key1) + partial_row_data1 = self._make_one(row_key1) row_key2 = object() - partial_row_data2 = self._makeOne(row_key2) + partial_row_data2 = self._make_one(row_key2) self.assertNotEqual(partial_row_data1, partial_row_data2) def test___ne__cells(self): row_key = object() - partial_row_data1 = self._makeOne(row_key) + partial_row_data1 = self._make_one(row_key) partial_row_data1._cells = object() - partial_row_data2 = self._makeOne(row_key) + partial_row_data2 = self._make_one(row_key) self.assertNotEqual(partial_row_data1, partial_row_data2) def test_to_dict(self): @@ -149,7 +151,7 @@ def test_to_dict(self): qual2 = b'col2' qual3 = b'col3' - partial_row_data = self._makeOne(None) + partial_row_data = self._make_one(None) partial_row_data._cells = { family_name1: { qual1: cell1, @@ -169,7 +171,7 @@ def test_to_dict(self): self.assertEqual(result, expected_result) def test_cells_property(self): - partial_row_data = self._makeOne(None) + partial_row_data = self._make_one(None) cells = {1: 2} partial_row_data._cells = cells # Make sure we get a copy, not the original. @@ -178,18 +180,19 @@ def test_cells_property(self): def test_row_key_getter(self): row_key = object() - partial_row_data = self._makeOne(row_key) + partial_row_data = self._make_one(row_key) self.assertIs(partial_row_data.row_key, row_key) class TestPartialRowsData(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowsData return PartialRowsData def _getDoNothingClass(self): - klass = self._getTargetClass() + klass = self._get_target_class() class FakePartialRowsData(klass): @@ -204,59 +207,59 @@ def consume_next(self): return FakePartialRowsData - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): response_iterator = object() - partial_rows_data = self._makeOne(response_iterator) + partial_rows_data = self._make_one(response_iterator) self.assertIs(partial_rows_data._response_iterator, response_iterator) self.assertEqual(partial_rows_data._rows, {}) def test___eq__(self): response_iterator = object() - partial_rows_data1 = self._makeOne(response_iterator) - partial_rows_data2 = self._makeOne(response_iterator) + partial_rows_data1 = self._make_one(response_iterator) + partial_rows_data2 = self._make_one(response_iterator) self.assertEqual(partial_rows_data1, partial_rows_data2) def test___eq__type_differ(self): - partial_rows_data1 = self._makeOne(None) + partial_rows_data1 = self._make_one(None) partial_rows_data2 = object() self.assertNotEqual(partial_rows_data1, partial_rows_data2) def test___ne__same_value(self): response_iterator = object() - partial_rows_data1 = self._makeOne(response_iterator) - partial_rows_data2 = self._makeOne(response_iterator) + partial_rows_data1 = self._make_one(response_iterator) + partial_rows_data2 = self._make_one(response_iterator) comparison_val = (partial_rows_data1 != partial_rows_data2) self.assertFalse(comparison_val) def test___ne__(self): response_iterator1 = object() - partial_rows_data1 = self._makeOne(response_iterator1) + partial_rows_data1 = self._make_one(response_iterator1) response_iterator2 = object() - partial_rows_data2 = self._makeOne(response_iterator2) + partial_rows_data2 = self._make_one(response_iterator2) self.assertNotEqual(partial_rows_data1, partial_rows_data2) def test_state_start(self): - prd = self._makeOne([]) + prd = self._make_one([]) self.assertEqual(prd.state, prd.START) def test_state_new_row_w_row(self): - prd = self._makeOne([]) + prd = self._make_one([]) prd._last_scanned_row_key = '' prd._row = object() self.assertEqual(prd.state, prd.NEW_ROW) def test_rows_getter(self): - partial_rows_data = self._makeOne(None) + partial_rows_data = self._make_one(None) partial_rows_data._rows = value = object() self.assertIs(partial_rows_data.rows, value) def test_cancel(self): response_iterator = _MockCancellableIterator() - partial_rows_data = self._makeOne(response_iterator) + partial_rows_data = self._make_one(response_iterator) self.assertEqual(response_iterator.cancel_calls, 0) partial_rows_data.cancel() self.assertEqual(response_iterator.cancel_calls, 1) @@ -288,7 +291,7 @@ def test_consume_all_with_max_loops(self): list(response_iterator.iter_values), [value2, value3]) def test__copy_from_current_unset(self): - prd = self._makeOne([]) + prd = self._make_one([]) chunks = _generate_cell_chunks(['']) chunk = chunks[0] prd._copy_from_current(chunk) @@ -304,7 +307,7 @@ def test__copy_from_current_blank(self): QUALIFIER = b'C' TIMESTAMP_MICROS = 100 LABELS = ['L1', 'L2'] - prd = self._makeOne([]) + prd = self._make_one([]) prd._cell = _PartialCellData() chunks = _generate_cell_chunks(['']) chunk = chunks[0] @@ -321,7 +324,7 @@ def test__copy_from_current_blank(self): self.assertEqual(chunk.labels, LABELS) def test__copy_from_previous_unset(self): - prd = self._makeOne([]) + prd = self._make_one([]) cell = _PartialCellData() prd._copy_from_previous(cell) self.assertEqual(cell.row_key, '') @@ -336,7 +339,7 @@ def test__copy_from_previous_blank(self): QUALIFIER = b'C' TIMESTAMP_MICROS = 100 LABELS = ['L1', 'L2'] - prd = self._makeOne([]) + prd = self._make_one([]) cell = _PartialCellData( row_key=ROW_KEY, family_name=FAMILY_NAME, @@ -358,7 +361,7 @@ def test__copy_from_previous_filled(self): QUALIFIER = b'C' TIMESTAMP_MICROS = 100 LABELS = ['L1', 'L2'] - prd = self._makeOne([]) + prd = self._make_one([]) prd._previous_cell = _PartialCellData( row_key=ROW_KEY, family_name=FAMILY_NAME, @@ -376,7 +379,7 @@ def test__copy_from_previous_filled(self): def test__save_row_no_cell(self): ROW_KEY = 'RK' - prd = self._makeOne([]) + prd = self._make_one([]) row = prd._row = _Dummy(row_key=ROW_KEY) prd._cell = None prd._save_current_row() @@ -386,7 +389,7 @@ 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._makeOne(iterator) + prd = self._make_one(iterator) with self.assertRaises(InvalidReadRowsResponse): prd.consume_next() @@ -394,7 +397,7 @@ def test_valid_last_scanned_row_key_on_start(self): response = _ReadRowsResponseV2( chunks=(), last_scanned_row_key='AFTER') iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) prd._last_scanned_row_key = 'BEFORE' prd.consume_next() self.assertEqual(prd._last_scanned_row_key, 'AFTER') @@ -404,7 +407,7 @@ def test_invalid_empty_chunk(self): chunks = _generate_cell_chunks(['']) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) with self.assertRaises(InvalidChunk): prd.consume_next() @@ -417,7 +420,7 @@ def test_invalid_empty_second_chunk(self): first.qualifier.value = b'C' response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) with self.assertRaises(InvalidChunk): prd.consume_next() @@ -426,12 +429,13 @@ class TestPartialRowsData_JSON_acceptance_tests(unittest.TestCase): _json_tests = None - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_data import PartialRowsData return PartialRowsData - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def _load_json_test(self, test_name): import os @@ -451,7 +455,7 @@ def _fail_during_consume(self, testcase_name): chunks, results = self._load_json_test(testcase_name) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) with self.assertRaises(InvalidChunk): prd.consume_next() expected_result = self._sort_flattend_cells( @@ -507,7 +511,7 @@ def _incomplete_final_row(self, testcase_name): chunks, results = self._load_json_test(testcase_name) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) prd.consume_next() self.assertEqual(prd.state, prd.ROW_IN_PROGRESS) expected_result = self._sort_flattend_cells( @@ -529,7 +533,7 @@ def _match_results(self, testcase_name, expected_result=_marker): chunks, results = self._load_json_test(testcase_name) response = _ReadRowsResponseV2(chunks) iterator = _MockCancellableIterator(response) - prd = self._makeOne(iterator) + prd = self._make_one(iterator) prd.consume_next() flattened = self._sort_flattend_cells(_flatten_cells(prd)) if expected_result is self._marker: diff --git a/bigtable/unit_tests/test_row_filters.py b/bigtable/unit_tests/test_row_filters.py index cb63856ac981..a49911acc0c3 100644 --- a/bigtable/unit_tests/test_row_filters.py +++ b/bigtable/unit_tests/test_row_filters.py @@ -18,50 +18,52 @@ class Test_BoolFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import _BoolFilter return _BoolFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): flag = object() - row_filter = self._makeOne(flag) + row_filter = self._make_one(flag) self.assertIs(row_filter.flag, flag) def test___eq__type_differ(self): flag = object() - row_filter1 = self._makeOne(flag) + row_filter1 = self._make_one(flag) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): flag = object() - row_filter1 = self._makeOne(flag) - row_filter2 = self._makeOne(flag) + row_filter1 = self._make_one(flag) + row_filter2 = self._make_one(flag) self.assertEqual(row_filter1, row_filter2) def test___ne__same_value(self): flag = object() - row_filter1 = self._makeOne(flag) - row_filter2 = self._makeOne(flag) + row_filter1 = self._make_one(flag) + row_filter2 = self._make_one(flag) comparison_val = (row_filter1 != row_filter2) self.assertFalse(comparison_val) class TestSinkFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import SinkFilter return SinkFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): flag = True - row_filter = self._makeOne(flag) + row_filter = self._make_one(flag) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(sink=flag) self.assertEqual(pb_val, expected_pb) @@ -69,16 +71,17 @@ def test_to_pb(self): class TestPassAllFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import PassAllFilter return PassAllFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): flag = True - row_filter = self._makeOne(flag) + row_filter = self._make_one(flag) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(pass_all_filter=flag) self.assertEqual(pb_val, expected_pb) @@ -86,16 +89,17 @@ def test_to_pb(self): class TestBlockAllFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import BlockAllFilter return BlockAllFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): flag = True - row_filter = self._makeOne(flag) + row_filter = self._make_one(flag) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(block_all_filter=flag) self.assertEqual(pb_val, expected_pb) @@ -103,55 +107,57 @@ def test_to_pb(self): class Test_RegexFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import _RegexFilter return _RegexFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): regex = b'abc' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) self.assertIs(row_filter.regex, regex) def test_constructor_non_bytes(self): regex = u'abc' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) self.assertEqual(row_filter.regex, b'abc') def test___eq__type_differ(self): regex = b'def-rgx' - row_filter1 = self._makeOne(regex) + row_filter1 = self._make_one(regex) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): regex = b'trex-regex' - row_filter1 = self._makeOne(regex) - row_filter2 = self._makeOne(regex) + row_filter1 = self._make_one(regex) + row_filter2 = self._make_one(regex) self.assertEqual(row_filter1, row_filter2) def test___ne__same_value(self): regex = b'abc' - row_filter1 = self._makeOne(regex) - row_filter2 = self._makeOne(regex) + row_filter1 = self._make_one(regex) + row_filter2 = self._make_one(regex) comparison_val = (row_filter1 != row_filter2) self.assertFalse(comparison_val) class TestRowKeyRegexFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import RowKeyRegexFilter return RowKeyRegexFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): regex = b'row-key-regex' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(row_key_regex_filter=regex) self.assertEqual(pb_val, expected_pb) @@ -159,33 +165,34 @@ def test_to_pb(self): class TestRowSampleFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import RowSampleFilter return RowSampleFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): sample = object() - row_filter = self._makeOne(sample) + row_filter = self._make_one(sample) self.assertIs(row_filter.sample, sample) def test___eq__type_differ(self): sample = object() - row_filter1 = self._makeOne(sample) + row_filter1 = self._make_one(sample) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): sample = object() - row_filter1 = self._makeOne(sample) - row_filter2 = self._makeOne(sample) + row_filter1 = self._make_one(sample) + row_filter2 = self._make_one(sample) self.assertEqual(row_filter1, row_filter2) def test_to_pb(self): sample = 0.25 - row_filter = self._makeOne(sample) + row_filter = self._make_one(sample) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(row_sample_filter=sample) self.assertEqual(pb_val, expected_pb) @@ -193,16 +200,17 @@ def test_to_pb(self): class TestFamilyNameRegexFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import FamilyNameRegexFilter return FamilyNameRegexFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): regex = u'family-regex' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(family_name_regex_filter=regex) self.assertEqual(pb_val, expected_pb) @@ -210,17 +218,18 @@ def test_to_pb(self): class TestColumnQualifierRegexFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ( ColumnQualifierRegexFilter) return ColumnQualifierRegexFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): regex = b'column-regex' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB( column_qualifier_regex_filter=regex) @@ -229,39 +238,40 @@ def test_to_pb(self): class TestTimestampRange(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import TimestampRange return TimestampRange - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): start = object() end = object() - time_range = self._makeOne(start=start, end=end) + time_range = self._make_one(start=start, end=end) self.assertIs(time_range.start, start) self.assertIs(time_range.end, end) def test___eq__(self): start = object() end = object() - time_range1 = self._makeOne(start=start, end=end) - time_range2 = self._makeOne(start=start, end=end) + time_range1 = self._make_one(start=start, end=end) + time_range2 = self._make_one(start=start, end=end) self.assertEqual(time_range1, time_range2) def test___eq__type_differ(self): start = object() end = object() - time_range1 = self._makeOne(start=start, end=end) + time_range1 = self._make_one(start=start, end=end) time_range2 = object() self.assertNotEqual(time_range1, time_range2) def test___ne__same_value(self): start = object() end = object() - time_range1 = self._makeOne(start=start, end=end) - time_range2 = self._makeOne(start=start, end=end) + time_range1 = self._make_one(start=start, end=end) + time_range2 = self._make_one(start=start, end=end) comparison_val = (time_range1 != time_range2) self.assertFalse(comparison_val) @@ -278,7 +288,7 @@ def _to_pb_helper(self, start_micros=None, end_micros=None): if end_micros is not None: end = _EPOCH + datetime.timedelta(microseconds=end_micros) pb_kwargs['end_timestamp_micros'] = end_micros - time_range = self._makeOne(start=start, end=end) + time_range = self._make_one(start=start, end=end) expected_pb = _TimestampRangePB(**pb_kwargs) self.assertEqual(time_range.to_pb(), expected_pb) @@ -303,35 +313,36 @@ def test_to_pb_end_only(self): class TestTimestampRangeFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import TimestampRangeFilter return TimestampRangeFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): range_ = object() - row_filter = self._makeOne(range_) + row_filter = self._make_one(range_) self.assertIs(row_filter.range_, range_) def test___eq__type_differ(self): range_ = object() - row_filter1 = self._makeOne(range_) + row_filter1 = self._make_one(range_) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): range_ = object() - row_filter1 = self._makeOne(range_) - row_filter2 = self._makeOne(range_) + row_filter1 = self._make_one(range_) + row_filter2 = self._make_one(range_) self.assertEqual(row_filter1, row_filter2) def test_to_pb(self): from google.cloud.bigtable.row_filters import TimestampRange range_ = TimestampRange() - row_filter = self._makeOne(range_) + row_filter = self._make_one(range_) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB( timestamp_range_filter=_TimestampRangePB()) @@ -340,16 +351,17 @@ def test_to_pb(self): class TestColumnRangeFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ColumnRangeFilter return ColumnRangeFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor_defaults(self): column_family_id = object() - row_filter = self._makeOne(column_family_id) + row_filter = self._make_one(column_family_id) self.assertIs(row_filter.column_family_id, column_family_id) self.assertIsNone(row_filter.start_column) self.assertIsNone(row_filter.end_column) @@ -362,7 +374,7 @@ def test_constructor_explicit(self): end_column = object() inclusive_start = object() inclusive_end = object() - row_filter = self._makeOne( + row_filter = self._make_one( column_family_id, start_column=start_column, end_column=end_column, @@ -376,12 +388,12 @@ def test_constructor_explicit(self): def test_constructor_bad_start(self): column_family_id = object() - self.assertRaises(ValueError, self._makeOne, + self.assertRaises(ValueError, self._make_one, column_family_id, inclusive_start=True) def test_constructor_bad_end(self): column_family_id = object() - self.assertRaises(ValueError, self._makeOne, + self.assertRaises(ValueError, self._make_one, column_family_id, inclusive_end=True) def test___eq__(self): @@ -390,27 +402,27 @@ def test___eq__(self): end_column = object() inclusive_start = object() inclusive_end = object() - row_filter1 = self._makeOne(column_family_id, - start_column=start_column, - end_column=end_column, - inclusive_start=inclusive_start, - inclusive_end=inclusive_end) - row_filter2 = self._makeOne(column_family_id, - start_column=start_column, - end_column=end_column, - inclusive_start=inclusive_start, - inclusive_end=inclusive_end) + row_filter1 = self._make_one(column_family_id, + start_column=start_column, + end_column=end_column, + inclusive_start=inclusive_start, + inclusive_end=inclusive_end) + row_filter2 = self._make_one(column_family_id, + start_column=start_column, + end_column=end_column, + inclusive_start=inclusive_start, + inclusive_end=inclusive_end) self.assertEqual(row_filter1, row_filter2) def test___eq__type_differ(self): column_family_id = object() - row_filter1 = self._makeOne(column_family_id) + row_filter1 = self._make_one(column_family_id) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test_to_pb(self): column_family_id = u'column-family-id' - row_filter = self._makeOne(column_family_id) + row_filter = self._make_one(column_family_id) col_range_pb = _ColumnRangePB(family_name=column_family_id) expected_pb = _RowFilterPB(column_range_filter=col_range_pb) self.assertEqual(row_filter.to_pb(), expected_pb) @@ -418,7 +430,7 @@ def test_to_pb(self): def test_to_pb_inclusive_start(self): column_family_id = u'column-family-id' column = b'column' - row_filter = self._makeOne(column_family_id, start_column=column) + row_filter = self._make_one(column_family_id, start_column=column) col_range_pb = _ColumnRangePB( family_name=column_family_id, start_qualifier_closed=column, @@ -429,8 +441,8 @@ def test_to_pb_inclusive_start(self): def test_to_pb_exclusive_start(self): column_family_id = u'column-family-id' column = b'column' - row_filter = self._makeOne(column_family_id, start_column=column, - inclusive_start=False) + row_filter = self._make_one(column_family_id, start_column=column, + inclusive_start=False) col_range_pb = _ColumnRangePB( family_name=column_family_id, start_qualifier_open=column, @@ -441,7 +453,7 @@ def test_to_pb_exclusive_start(self): def test_to_pb_inclusive_end(self): column_family_id = u'column-family-id' column = b'column' - row_filter = self._makeOne(column_family_id, end_column=column) + row_filter = self._make_one(column_family_id, end_column=column) col_range_pb = _ColumnRangePB( family_name=column_family_id, end_qualifier_closed=column, @@ -452,8 +464,8 @@ def test_to_pb_inclusive_end(self): def test_to_pb_exclusive_end(self): column_family_id = u'column-family-id' column = b'column' - row_filter = self._makeOne(column_family_id, end_column=column, - inclusive_end=False) + row_filter = self._make_one(column_family_id, end_column=column, + inclusive_end=False) col_range_pb = _ColumnRangePB( family_name=column_family_id, end_qualifier_open=column, @@ -464,16 +476,17 @@ def test_to_pb_exclusive_end(self): class TestValueRegexFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ValueRegexFilter return ValueRegexFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): regex = b'value-regex' - row_filter = self._makeOne(regex) + row_filter = self._make_one(regex) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(value_regex_filter=regex) self.assertEqual(pb_val, expected_pb) @@ -481,15 +494,16 @@ def test_to_pb(self): class TestValueRangeFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ValueRangeFilter return ValueRangeFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor_defaults(self): - row_filter = self._makeOne() + row_filter = self._make_one() self.assertIsNone(row_filter.start_value) self.assertIsNone(row_filter.end_value) self.assertTrue(row_filter.inclusive_start) @@ -500,71 +514,71 @@ def test_constructor_explicit(self): end_value = object() inclusive_start = object() inclusive_end = object() - row_filter = self._makeOne(start_value=start_value, - end_value=end_value, - inclusive_start=inclusive_start, - inclusive_end=inclusive_end) + row_filter = self._make_one(start_value=start_value, + end_value=end_value, + inclusive_start=inclusive_start, + inclusive_end=inclusive_end) self.assertIs(row_filter.start_value, start_value) self.assertIs(row_filter.end_value, end_value) self.assertIs(row_filter.inclusive_start, inclusive_start) self.assertIs(row_filter.inclusive_end, inclusive_end) def test_constructor_bad_start(self): - self.assertRaises(ValueError, self._makeOne, inclusive_start=True) + self.assertRaises(ValueError, self._make_one, inclusive_start=True) def test_constructor_bad_end(self): - self.assertRaises(ValueError, self._makeOne, inclusive_end=True) + self.assertRaises(ValueError, self._make_one, inclusive_end=True) def test___eq__(self): start_value = object() end_value = object() inclusive_start = object() inclusive_end = object() - row_filter1 = self._makeOne(start_value=start_value, - end_value=end_value, - inclusive_start=inclusive_start, - inclusive_end=inclusive_end) - row_filter2 = self._makeOne(start_value=start_value, - end_value=end_value, - inclusive_start=inclusive_start, - inclusive_end=inclusive_end) + row_filter1 = self._make_one(start_value=start_value, + end_value=end_value, + inclusive_start=inclusive_start, + inclusive_end=inclusive_end) + row_filter2 = self._make_one(start_value=start_value, + end_value=end_value, + inclusive_start=inclusive_start, + inclusive_end=inclusive_end) self.assertEqual(row_filter1, row_filter2) def test___eq__type_differ(self): - row_filter1 = self._makeOne() + row_filter1 = self._make_one() row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test_to_pb(self): - row_filter = self._makeOne() + row_filter = self._make_one() expected_pb = _RowFilterPB( value_range_filter=_ValueRangePB()) self.assertEqual(row_filter.to_pb(), expected_pb) def test_to_pb_inclusive_start(self): value = b'some-value' - row_filter = self._makeOne(start_value=value) + row_filter = self._make_one(start_value=value) val_range_pb = _ValueRangePB(start_value_closed=value) expected_pb = _RowFilterPB(value_range_filter=val_range_pb) self.assertEqual(row_filter.to_pb(), expected_pb) def test_to_pb_exclusive_start(self): value = b'some-value' - row_filter = self._makeOne(start_value=value, inclusive_start=False) + row_filter = self._make_one(start_value=value, inclusive_start=False) val_range_pb = _ValueRangePB(start_value_open=value) expected_pb = _RowFilterPB(value_range_filter=val_range_pb) self.assertEqual(row_filter.to_pb(), expected_pb) def test_to_pb_inclusive_end(self): value = b'some-value' - row_filter = self._makeOne(end_value=value) + row_filter = self._make_one(end_value=value) val_range_pb = _ValueRangePB(end_value_closed=value) expected_pb = _RowFilterPB(value_range_filter=val_range_pb) self.assertEqual(row_filter.to_pb(), expected_pb) def test_to_pb_exclusive_end(self): value = b'some-value' - row_filter = self._makeOne(end_value=value, inclusive_end=False) + row_filter = self._make_one(end_value=value, inclusive_end=False) val_range_pb = _ValueRangePB(end_value_open=value) expected_pb = _RowFilterPB(value_range_filter=val_range_pb) self.assertEqual(row_filter.to_pb(), expected_pb) @@ -572,50 +586,52 @@ def test_to_pb_exclusive_end(self): class Test_CellCountFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import _CellCountFilter return _CellCountFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): num_cells = object() - row_filter = self._makeOne(num_cells) + row_filter = self._make_one(num_cells) self.assertIs(row_filter.num_cells, num_cells) def test___eq__type_differ(self): num_cells = object() - row_filter1 = self._makeOne(num_cells) + row_filter1 = self._make_one(num_cells) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): num_cells = object() - row_filter1 = self._makeOne(num_cells) - row_filter2 = self._makeOne(num_cells) + row_filter1 = self._make_one(num_cells) + row_filter2 = self._make_one(num_cells) self.assertEqual(row_filter1, row_filter2) def test___ne__same_value(self): num_cells = object() - row_filter1 = self._makeOne(num_cells) - row_filter2 = self._makeOne(num_cells) + row_filter1 = self._make_one(num_cells) + row_filter2 = self._make_one(num_cells) comparison_val = (row_filter1 != row_filter2) self.assertFalse(comparison_val) class TestCellsRowOffsetFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import CellsRowOffsetFilter return CellsRowOffsetFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): num_cells = 76 - row_filter = self._makeOne(num_cells) + row_filter = self._make_one(num_cells) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB( cells_per_row_offset_filter=num_cells) @@ -624,16 +640,17 @@ def test_to_pb(self): class TestCellsRowLimitFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import CellsRowLimitFilter return CellsRowLimitFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): num_cells = 189 - row_filter = self._makeOne(num_cells) + row_filter = self._make_one(num_cells) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB( cells_per_row_limit_filter=num_cells) @@ -642,16 +659,17 @@ def test_to_pb(self): class TestCellsColumnLimitFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import CellsColumnLimitFilter return CellsColumnLimitFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): num_cells = 10 - row_filter = self._makeOne(num_cells) + row_filter = self._make_one(num_cells) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB( cells_per_column_limit_filter=num_cells) @@ -660,17 +678,18 @@ def test_to_pb(self): class TestStripValueTransformerFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ( StripValueTransformerFilter) return StripValueTransformerFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): flag = True - row_filter = self._makeOne(flag) + row_filter = self._make_one(flag) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(strip_value_transformer=flag) self.assertEqual(pb_val, expected_pb) @@ -678,33 +697,34 @@ def test_to_pb(self): class TestApplyLabelFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ApplyLabelFilter return ApplyLabelFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): label = object() - row_filter = self._makeOne(label) + row_filter = self._make_one(label) self.assertIs(row_filter.label, label) def test___eq__type_differ(self): label = object() - row_filter1 = self._makeOne(label) + row_filter1 = self._make_one(label) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) def test___eq__same_value(self): label = object() - row_filter1 = self._makeOne(label) - row_filter2 = self._makeOne(label) + row_filter1 = self._make_one(label) + row_filter2 = self._make_one(label) self.assertEqual(row_filter1, row_filter2) def test_to_pb(self): label = u'label' - row_filter = self._makeOne(label) + row_filter = self._make_one(label) pb_val = row_filter.to_pb() expected_pb = _RowFilterPB(apply_label_transformer=label) self.assertEqual(pb_val, expected_pb) @@ -712,43 +732,45 @@ def test_to_pb(self): class Test_FilterCombination(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import _FilterCombination return _FilterCombination - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor_defaults(self): - row_filter = self._makeOne() + row_filter = self._make_one() self.assertEqual(row_filter.filters, []) def test_constructor_explicit(self): filters = object() - row_filter = self._makeOne(filters=filters) + row_filter = self._make_one(filters=filters) self.assertIs(row_filter.filters, filters) def test___eq__(self): filters = object() - row_filter1 = self._makeOne(filters=filters) - row_filter2 = self._makeOne(filters=filters) + row_filter1 = self._make_one(filters=filters) + row_filter2 = self._make_one(filters=filters) self.assertEqual(row_filter1, row_filter2) def test___eq__type_differ(self): filters = object() - row_filter1 = self._makeOne(filters=filters) + row_filter1 = self._make_one(filters=filters) row_filter2 = object() self.assertNotEqual(row_filter1, row_filter2) class TestRowFilterChain(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import RowFilterChain return RowFilterChain - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): from google.cloud.bigtable.row_filters import RowSampleFilter @@ -761,7 +783,7 @@ def test_to_pb(self): row_filter2 = RowSampleFilter(0.25) row_filter2_pb = row_filter2.to_pb() - row_filter3 = self._makeOne(filters=[row_filter1, row_filter2]) + row_filter3 = self._make_one(filters=[row_filter1, row_filter2]) filter_pb = row_filter3.to_pb() expected_pb = _RowFilterPB( @@ -780,13 +802,13 @@ def test_to_pb_nested(self): row_filter1 = StripValueTransformerFilter(True) row_filter2 = RowSampleFilter(0.25) - row_filter3 = self._makeOne(filters=[row_filter1, row_filter2]) + row_filter3 = self._make_one(filters=[row_filter1, row_filter2]) row_filter3_pb = row_filter3.to_pb() row_filter4 = CellsRowLimitFilter(11) row_filter4_pb = row_filter4.to_pb() - row_filter5 = self._makeOne(filters=[row_filter3, row_filter4]) + row_filter5 = self._make_one(filters=[row_filter3, row_filter4]) filter_pb = row_filter5.to_pb() expected_pb = _RowFilterPB( @@ -799,12 +821,13 @@ def test_to_pb_nested(self): class TestRowFilterUnion(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import RowFilterUnion return RowFilterUnion - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_to_pb(self): from google.cloud.bigtable.row_filters import RowSampleFilter @@ -817,7 +840,7 @@ def test_to_pb(self): row_filter2 = RowSampleFilter(0.25) row_filter2_pb = row_filter2.to_pb() - row_filter3 = self._makeOne(filters=[row_filter1, row_filter2]) + row_filter3 = self._make_one(filters=[row_filter1, row_filter2]) filter_pb = row_filter3.to_pb() expected_pb = _RowFilterPB( @@ -836,13 +859,13 @@ def test_to_pb_nested(self): row_filter1 = StripValueTransformerFilter(True) row_filter2 = RowSampleFilter(0.25) - row_filter3 = self._makeOne(filters=[row_filter1, row_filter2]) + row_filter3 = self._make_one(filters=[row_filter1, row_filter2]) row_filter3_pb = row_filter3.to_pb() row_filter4 = CellsRowLimitFilter(11) row_filter4_pb = row_filter4.to_pb() - row_filter5 = self._makeOne(filters=[row_filter3, row_filter4]) + row_filter5 = self._make_one(filters=[row_filter3, row_filter4]) filter_pb = row_filter5.to_pb() expected_pb = _RowFilterPB( @@ -855,20 +878,21 @@ def test_to_pb_nested(self): class TestConditionalRowFilter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.row_filters import ConditionalRowFilter return ConditionalRowFilter - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): base_filter = object() true_filter = object() false_filter = object() - cond_filter = self._makeOne(base_filter, - true_filter=true_filter, - false_filter=false_filter) + cond_filter = self._make_one(base_filter, + true_filter=true_filter, + false_filter=false_filter) self.assertIs(cond_filter.base_filter, base_filter) self.assertIs(cond_filter.true_filter, true_filter) self.assertIs(cond_filter.false_filter, false_filter) @@ -877,21 +901,21 @@ def test___eq__(self): base_filter = object() true_filter = object() false_filter = object() - cond_filter1 = self._makeOne(base_filter, - true_filter=true_filter, - false_filter=false_filter) - cond_filter2 = self._makeOne(base_filter, - true_filter=true_filter, - false_filter=false_filter) + cond_filter1 = self._make_one(base_filter, + true_filter=true_filter, + false_filter=false_filter) + cond_filter2 = self._make_one(base_filter, + true_filter=true_filter, + false_filter=false_filter) self.assertEqual(cond_filter1, cond_filter2) def test___eq__type_differ(self): base_filter = object() true_filter = object() false_filter = object() - cond_filter1 = self._makeOne(base_filter, - true_filter=true_filter, - false_filter=false_filter) + cond_filter1 = self._make_one(base_filter, + true_filter=true_filter, + false_filter=false_filter) cond_filter2 = object() self.assertNotEqual(cond_filter1, cond_filter2) @@ -910,8 +934,8 @@ def test_to_pb(self): row_filter3 = CellsRowOffsetFilter(11) row_filter3_pb = row_filter3.to_pb() - row_filter4 = self._makeOne(row_filter1, true_filter=row_filter2, - false_filter=row_filter3) + row_filter4 = self._make_one(row_filter1, true_filter=row_filter2, + false_filter=row_filter3) filter_pb = row_filter4.to_pb() expected_pb = _RowFilterPB( @@ -934,7 +958,7 @@ def test_to_pb_true_only(self): row_filter2 = RowSampleFilter(0.25) row_filter2_pb = row_filter2.to_pb() - row_filter3 = self._makeOne(row_filter1, true_filter=row_filter2) + row_filter3 = self._make_one(row_filter1, true_filter=row_filter2) filter_pb = row_filter3.to_pb() expected_pb = _RowFilterPB( @@ -956,7 +980,7 @@ def test_to_pb_false_only(self): row_filter2 = RowSampleFilter(0.25) row_filter2_pb = row_filter2.to_pb() - row_filter3 = self._makeOne(row_filter1, false_filter=row_filter2) + row_filter3 = self._make_one(row_filter1, false_filter=row_filter2) filter_pb = row_filter3.to_pb() expected_pb = _RowFilterPB( diff --git a/bigtable/unit_tests/test_table.py b/bigtable/unit_tests/test_table.py index 7dca91768861..f96ddcc8e704 100644 --- a/bigtable/unit_tests/test_table.py +++ b/bigtable/unit_tests/test_table.py @@ -29,18 +29,19 @@ class TestTable(unittest.TestCase): TIMESTAMP_MICROS = 100 VALUE = b'value' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.bigtable.table import Table return Table - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): table_id = 'table-id' instance = object() - table = self._makeOne(table_id, instance) + table = self._make_one(table_id, instance) self.assertEqual(table.table_id, table_id) self.assertIs(table._instance, instance) @@ -49,7 +50,7 @@ def test_name_property(self): instance_name = 'instance_name' instance = _Instance(instance_name) - table = self._makeOne(table_id, instance) + table = self._make_one(table_id, instance) expected_name = instance_name + '/tables/' + table_id self.assertEqual(table.name, expected_name) @@ -58,7 +59,7 @@ def test_column_family_factory(self): table_id = 'table-id' gc_rule = object() - table = self._makeOne(table_id, None) + table = self._make_one(table_id, None) column_family_id = 'column_family_id' column_family = table.column_family(column_family_id, gc_rule=gc_rule) @@ -71,7 +72,7 @@ def test_row_factory_direct(self): from google.cloud.bigtable.row import DirectRow table_id = 'table-id' - table = self._makeOne(table_id, None) + table = self._make_one(table_id, None) row_key = b'row_key' row = table.row(row_key) @@ -83,7 +84,7 @@ def test_row_factory_conditional(self): from google.cloud.bigtable.row import ConditionalRow table_id = 'table-id' - table = self._makeOne(table_id, None) + table = self._make_one(table_id, None) row_key = b'row_key' filter_ = object() row = table.row(row_key, filter_=filter_) @@ -96,7 +97,7 @@ def test_row_factory_append(self): from google.cloud.bigtable.row import AppendRow table_id = 'table-id' - table = self._makeOne(table_id, None) + table = self._make_one(table_id, None) row_key = b'row_key' row = table.row(row_key, append=True) @@ -105,31 +106,31 @@ def test_row_factory_append(self): self.assertEqual(row._table, table) def test_row_factory_failure(self): - table = self._makeOne(self.TABLE_ID, None) + table = self._make_one(self.TABLE_ID, None) with self.assertRaises(ValueError): table.row(b'row_key', filter_=object(), append=True) def test___eq__(self): instance = object() - table1 = self._makeOne(self.TABLE_ID, instance) - table2 = self._makeOne(self.TABLE_ID, instance) + table1 = self._make_one(self.TABLE_ID, instance) + table2 = self._make_one(self.TABLE_ID, instance) self.assertEqual(table1, table2) def test___eq__type_differ(self): - table1 = self._makeOne(self.TABLE_ID, None) + table1 = self._make_one(self.TABLE_ID, None) table2 = object() self.assertNotEqual(table1, table2) def test___ne__same_value(self): instance = object() - table1 = self._makeOne(self.TABLE_ID, instance) - table2 = self._makeOne(self.TABLE_ID, instance) + table1 = self._make_one(self.TABLE_ID, instance) + table2 = self._make_one(self.TABLE_ID, instance) comparison_val = (table1 != table2) self.assertFalse(comparison_val) def test___ne__(self): - table1 = self._makeOne('table_id1', 'instance1') - table2 = self._makeOne('table_id2', 'instance2') + table1 = self._make_one('table_id1', 'instance1') + table2 = self._make_one('table_id2', 'instance2') self.assertNotEqual(table1, table2) def _create_test_helper(self, initial_split_keys, column_families=()): @@ -138,7 +139,7 @@ def _create_test_helper(self, initial_split_keys, column_families=()): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb splits_pb = [ @@ -205,7 +206,7 @@ def _list_column_families_helper(self): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb request_pb = _GetTableRequestPB(name=self.TABLE_NAME) @@ -243,7 +244,7 @@ def test_delete(self): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb request_pb = _DeleteTableRequestPB(name=self.TABLE_NAME) @@ -273,7 +274,7 @@ def _read_row_helper(self, chunks, expected_result): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb request_pb = object() # Returned by our mock. @@ -354,7 +355,7 @@ def test_read_rows(self): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb request_pb = object() # Returned by our mock. @@ -402,7 +403,7 @@ def test_sample_row_keys(self): client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) - table = self._makeOne(self.TABLE_ID, instance) + table = self._make_one(self.TABLE_ID, instance) # Create request_pb request_pb = _SampleRowKeysRequestPB(table_name=self.TABLE_NAME) @@ -428,8 +429,8 @@ def test_sample_row_keys(self): class Test__create_row_request(unittest.TestCase): - def _callFUT(self, table_name, row_key=None, start_key=None, end_key=None, - filter_=None, limit=None): + 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, @@ -437,19 +438,19 @@ def _callFUT(self, table_name, row_key=None, start_key=None, end_key=None, def test_table_name_only(self): table_name = 'table_name' - result = self._callFUT(table_name) + result = self._call_fut(table_name) expected_result = _ReadRowsRequestPB( table_name=table_name) self.assertEqual(result, expected_result) def test_row_key_row_range_conflict(self): with self.assertRaises(ValueError): - self._callFUT(None, row_key=object(), end_key=object()) + self._call_fut(None, row_key=object(), end_key=object()) def test_row_key(self): table_name = 'table_name' row_key = b'row_key' - result = self._callFUT(table_name, row_key=row_key) + result = self._call_fut(table_name, row_key=row_key) expected_result = _ReadRowsRequestPB( table_name=table_name, ) @@ -459,7 +460,7 @@ def test_row_key(self): def test_row_range_start_key(self): table_name = 'table_name' start_key = b'start_key' - result = self._callFUT(table_name, start_key=start_key) + result = self._call_fut(table_name, start_key=start_key) expected_result = _ReadRowsRequestPB(table_name=table_name) expected_result.rows.row_ranges.add(start_key_closed=start_key) self.assertEqual(result, expected_result) @@ -467,7 +468,7 @@ def test_row_range_start_key(self): def test_row_range_end_key(self): table_name = 'table_name' end_key = b'end_key' - result = self._callFUT(table_name, end_key=end_key) + result = self._call_fut(table_name, end_key=end_key) expected_result = _ReadRowsRequestPB(table_name=table_name) expected_result.rows.row_ranges.add(end_key_open=end_key) self.assertEqual(result, expected_result) @@ -476,8 +477,8 @@ def test_row_range_both_keys(self): table_name = 'table_name' start_key = b'start_key' end_key = b'end_key' - result = self._callFUT(table_name, start_key=start_key, - end_key=end_key) + result = self._call_fut(table_name, start_key=start_key, + end_key=end_key) expected_result = _ReadRowsRequestPB(table_name=table_name) expected_result.rows.row_ranges.add( start_key_closed=start_key, end_key_open=end_key) @@ -487,7 +488,7 @@ def test_with_filter(self): from google.cloud.bigtable.row_filters import RowSampleFilter table_name = 'table_name' row_filter = RowSampleFilter(0.33) - result = self._callFUT(table_name, filter_=row_filter) + result = self._call_fut(table_name, filter_=row_filter) expected_result = _ReadRowsRequestPB( table_name=table_name, filter=row_filter.to_pb(), @@ -497,7 +498,7 @@ def test_with_filter(self): def test_with_limit(self): table_name = 'table_name' limit = 1337 - result = self._callFUT(table_name, limit=limit) + result = self._call_fut(table_name, limit=limit) expected_result = _ReadRowsRequestPB( table_name=table_name, rows_limit=limit, diff --git a/core/unit_tests/streaming/test_buffered_stream.py b/core/unit_tests/streaming/test_buffered_stream.py index b6f4066b11c2..8a8793b0c49c 100644 --- a/core/unit_tests/streaming/test_buffered_stream.py +++ b/core/unit_tests/streaming/test_buffered_stream.py @@ -17,12 +17,13 @@ class Test_BufferedStream(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.buffered_stream import BufferedStream return BufferedStream - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_closed_stream(self): class _Stream(object): @@ -30,7 +31,7 @@ class _Stream(object): start = 0 bufsize = 4 - bufstream = self._makeOne(_Stream, start, bufsize) + bufstream = self._make_one(_Stream, start, bufsize) self.assertIs(bufstream._stream, _Stream) self.assertEqual(bufstream._start_pos, start) self.assertEqual(bufstream._buffer_pos, 0) @@ -44,7 +45,7 @@ def test_ctor_start_zero_longer_than_buffer(self): START = 0 BUFSIZE = 4 stream = BytesIO(CONTENT) - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertIs(bufstream._stream, stream) self.assertEqual(bufstream._start_pos, START) self.assertEqual(bufstream._buffer_pos, 0) @@ -60,7 +61,7 @@ def test_ctor_start_nonzero_shorter_than_buffer(self): BUFSIZE = 10 stream = BytesIO(CONTENT) stream.read(START) # already consumed - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertIs(bufstream._stream, stream) self.assertEqual(bufstream._start_pos, START) self.assertEqual(bufstream._buffer_pos, 0) @@ -75,7 +76,7 @@ def test__bytes_remaining_start_zero_longer_than_buffer(self): START = 0 BUFSIZE = 4 stream = BytesIO(CONTENT) - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertEqual(bufstream._bytes_remaining, BUFSIZE) def test__bytes_remaining_start_zero_shorter_than_buffer(self): @@ -85,7 +86,7 @@ def test__bytes_remaining_start_zero_shorter_than_buffer(self): BUFSIZE = 10 stream = BytesIO(CONTENT) stream.read(START) # already consumed - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertEqual(bufstream._bytes_remaining, len(CONTENT) - START) def test_read_w_none(self): @@ -94,7 +95,7 @@ def test_read_w_none(self): START = 0 BUFSIZE = 4 stream = BytesIO(CONTENT) - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) with self.assertRaises(ValueError): bufstream.read(None) @@ -104,7 +105,7 @@ def test_read_w_negative_size(self): START = 0 BUFSIZE = 4 stream = BytesIO(CONTENT) - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) with self.assertRaises(ValueError): bufstream.read(-2) @@ -114,7 +115,7 @@ def test_read_from_start(self): START = 0 BUFSIZE = 4 stream = BytesIO(CONTENT) - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertEqual(bufstream.read(4), CONTENT[:4]) def test_read_exhausted(self): @@ -124,7 +125,7 @@ def test_read_exhausted(self): BUFSIZE = 10 stream = BytesIO(CONTENT) stream.read(START) # already consumed - bufstream = self._makeOne(stream, START, BUFSIZE) + bufstream = self._make_one(stream, START, BUFSIZE) self.assertTrue(bufstream.stream_exhausted) self.assertEqual(bufstream.stream_end_position, len(CONTENT)) self.assertEqual(bufstream._bytes_remaining, 0) diff --git a/core/unit_tests/streaming/test_exceptions.py b/core/unit_tests/streaming/test_exceptions.py index b72dfabac38b..0cb1c724bf99 100644 --- a/core/unit_tests/streaming/test_exceptions.py +++ b/core/unit_tests/streaming/test_exceptions.py @@ -17,18 +17,19 @@ class Test_HttpError(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.exceptions import HttpError return HttpError - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): RESPONSE = {'status': '404'} CONTENT = b'CONTENT' URL = 'http://www.example.com' - exception = self._makeOne(RESPONSE, CONTENT, URL) + exception = self._make_one(RESPONSE, CONTENT, URL) self.assertEqual(exception.response, RESPONSE) self.assertEqual(exception.content, CONTENT) self.assertEqual(exception.url, URL) @@ -48,7 +49,7 @@ class _Response(object): content = CONTENT request_url = URL - klass = self._getTargetClass() + klass = self._get_target_class() exception = klass.from_response(_Response()) self.assertIsInstance(exception, klass) self.assertEqual(exception.response, RESPONSE) @@ -58,19 +59,20 @@ class _Response(object): class Test_RetryAfterError(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.exceptions import RetryAfterError return RetryAfterError - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): RESPONSE = {'status': '404'} CONTENT = b'CONTENT' URL = 'http://www.example.com' RETRY_AFTER = 60 - exception = self._makeOne(RESPONSE, CONTENT, URL, RETRY_AFTER) + exception = self._make_one(RESPONSE, CONTENT, URL, RETRY_AFTER) self.assertEqual(exception.response, RESPONSE) self.assertEqual(exception.content, CONTENT) self.assertEqual(exception.url, URL) @@ -92,7 +94,7 @@ class _Response(object): request_url = URL retry_after = RETRY_AFTER - klass = self._getTargetClass() + klass = self._get_target_class() exception = klass.from_response(_Response()) self.assertIsInstance(exception, klass) self.assertEqual(exception.response, RESPONSE) diff --git a/core/unit_tests/streaming/test_http_wrapper.py b/core/unit_tests/streaming/test_http_wrapper.py index 8aad20cfb2f1..f05e1b0a6f9f 100644 --- a/core/unit_tests/streaming/test_http_wrapper.py +++ b/core/unit_tests/streaming/test_http_wrapper.py @@ -17,12 +17,13 @@ class Test__httplib2_debug_level(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.http_wrapper import _httplib2_debug_level return _httplib2_debug_level - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_wo_loggable_body_wo_http(self): from google.cloud._testing import _Monkey @@ -32,7 +33,7 @@ def test_wo_loggable_body_wo_http(self): LEVEL = 1 _httplib2 = _Dummy(debuglevel=0) with _Monkey(MUT, httplib2=_httplib2): - with self._makeOne(request, LEVEL): + with self._make_one(request, LEVEL): self.assertEqual(_httplib2.debuglevel, 0) def test_w_loggable_body_wo_http(self): @@ -43,7 +44,7 @@ def test_w_loggable_body_wo_http(self): LEVEL = 1 _httplib2 = _Dummy(debuglevel=0) with _Monkey(MUT, httplib2=_httplib2): - with self._makeOne(request, LEVEL): + with self._make_one(request, LEVEL): self.assertEqual(_httplib2.debuglevel, LEVEL) self.assertEqual(_httplib2.debuglevel, 0) @@ -65,7 +66,7 @@ def set_debuglevel(self, value): connections = {'update:me': update_me, 'skip_me': skip_me} _http = _Dummy(connections=connections) with _Monkey(MUT, httplib2=_httplib2): - with self._makeOne(request, LEVEL, _http): + with self._make_one(request, LEVEL, _http): self.assertEqual(_httplib2.debuglevel, LEVEL) self.assertEqual(update_me.debuglevel, LEVEL) self.assertEqual(skip_me.debuglevel, 0) @@ -76,15 +77,16 @@ def set_debuglevel(self, value): class Test_Request(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.http_wrapper import Request return Request - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): - request = self._makeOne() + request = self._make_one() self.assertEqual(request.url, '') self.assertEqual(request.http_method, 'GET') self.assertEqual(request.headers, {'content-length': '0'}) @@ -93,12 +95,12 @@ def test_ctor_defaults(self): def test_loggable_body_setter_w_body_None(self): from google.cloud.streaming.exceptions import RequestError - request = self._makeOne(body=None) + request = self._make_one(body=None) with self.assertRaises(RequestError): request.loggable_body = 'abc' def test_body_setter_w_None(self): - request = self._makeOne() + request = self._make_one() request.loggable_body = 'abc' request.body = None self.assertEqual(request.headers, {}) @@ -106,7 +108,7 @@ def test_body_setter_w_None(self): self.assertEqual(request.loggable_body, 'abc') def test_body_setter_w_non_string(self): - request = self._makeOne() + request = self._make_one() request.loggable_body = 'abc' request.body = body = _Dummy(length=123) self.assertEqual(request.headers, {'content-length': '123'}) @@ -116,18 +118,19 @@ def test_body_setter_w_non_string(self): class Test_Response(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.http_wrapper import Response return Response - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): CONTENT = 'CONTENT' URL = 'http://example.com/api' info = {'status': '200'} - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(len(response), len(CONTENT)) self.assertEqual(response.status_code, 200) self.assertIsNone(response.retry_after) @@ -143,7 +146,7 @@ def test_length_w_content_encoding_w_content_range(self): 'content-encoding': 'testing', 'content-range': RANGE, } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(len(response), 123) def test_length_w_content_encoding_wo_content_range(self): @@ -154,7 +157,7 @@ def test_length_w_content_encoding_wo_content_range(self): 'content-length': len(CONTENT), 'content-encoding': 'testing', } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(len(response), len(CONTENT)) def test_length_w_content_length_w_content_range(self): @@ -166,7 +169,7 @@ def test_length_w_content_length_w_content_range(self): 'content-length': len(CONTENT) * 2, 'content-range': RANGE, } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(len(response), len(CONTENT) * 2) def test_length_wo_content_length_w_content_range(self): @@ -177,7 +180,7 @@ def test_length_wo_content_length_w_content_range(self): 'status': '200', 'content-range': RANGE, } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(len(response), 123) def test_retry_after_w_header(self): @@ -187,7 +190,7 @@ def test_retry_after_w_header(self): 'status': '200', 'retry-after': '123', } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertEqual(response.retry_after, 123) def test_is_redirect_w_code_wo_location(self): @@ -196,7 +199,7 @@ def test_is_redirect_w_code_wo_location(self): info = { 'status': '301', } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertFalse(response.is_redirect) def test_is_redirect_w_code_w_location(self): @@ -206,68 +209,68 @@ def test_is_redirect_w_code_w_location(self): 'status': '301', 'location': 'http://example.com/other', } - response = self._makeOne(info, CONTENT, URL) + response = self._make_one(info, CONTENT, URL) self.assertTrue(response.is_redirect) class Test__check_response(unittest.TestCase): - def _callFUT(self, *args, **kw): + 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._callFUT(None) + self._call_fut(None) def test_w_TOO_MANY_REQUESTS(self): from google.cloud.streaming.exceptions import BadStatusCodeError from google.cloud.streaming.http_wrapper import TOO_MANY_REQUESTS with self.assertRaises(BadStatusCodeError): - self._callFUT(_Response(TOO_MANY_REQUESTS)) + self._call_fut(_Response(TOO_MANY_REQUESTS)) def test_w_50x(self): from google.cloud.streaming.exceptions import BadStatusCodeError with self.assertRaises(BadStatusCodeError): - self._callFUT(_Response(500)) + self._call_fut(_Response(500)) with self.assertRaises(BadStatusCodeError): - self._callFUT(_Response(503)) + self._call_fut(_Response(503)) def test_w_retry_after(self): from google.cloud.streaming.exceptions import RetryAfterError with self.assertRaises(RetryAfterError): - self._callFUT(_Response(200, 20)) + self._call_fut(_Response(200, 20)) def test_pass(self): - self._callFUT(_Response(200)) + self._call_fut(_Response(200)) class Test__reset_http_connections(unittest.TestCase): - def _callFUT(self, *args, **kw): + 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): http = object() - self._callFUT(http) + self._call_fut(http) def test_w_connections(self): connections = {'delete:me': object(), 'skip_me': object()} http = _Dummy(connections=connections) - self._callFUT(http) + self._call_fut(http) self.assertFalse('delete:me' in connections) self.assertTrue('skip_me' in connections) class Test___make_api_request_no_retry(unittest.TestCase): - def _callFUT(self, *args, **kw): + def _call_fut(self, *args, **kw): from google.cloud.streaming.http_wrapper import ( _make_api_request_no_retry) return _make_api_request_no_retry(*args, **kw) @@ -294,7 +297,7 @@ def test_defaults_wo_connections(self): _checked = [] with _Monkey(MUT, httplib2=_httplib2, _check_response=_checked.append): - response = self._callFUT(_http, _request) + response = self._call_fut(_http, _request) self.assertIsInstance(response, MUT.Response) self.assertEqual(response.info, INFO) @@ -316,7 +319,7 @@ def test_w_http_connections_miss(self): _checked = [] with _Monkey(MUT, httplib2=_httplib2, _check_response=_checked.append): - response = self._callFUT(_http, _request) + response = self._call_fut(_http, _request) self.assertIsInstance(response, MUT.Response) self.assertEqual(response.info, INFO) @@ -338,7 +341,7 @@ def test_w_http_connections_hit(self): _checked = [] with _Monkey(MUT, httplib2=_httplib2, _check_response=_checked.append): - response = self._callFUT(_http, _request) + response = self._call_fut(_http, _request) self.assertIsInstance(response, MUT.Response) self.assertEqual(response.info, INFO) @@ -360,13 +363,13 @@ def test_w_request_returning_None(self): _request = _Request() with _Monkey(MUT, httplib2=_httplib2): with self.assertRaises(RequestError): - self._callFUT(_http, _request) + self._call_fut(_http, _request) self._verify_requested(_http, _request, connection_type=CONN_TYPE) class Test_make_api_request(unittest.TestCase): - def _callFUT(self, *args, **kw): + def _call_fut(self, *args, **kw): from google.cloud.streaming.http_wrapper import make_api_request return make_api_request(*args, **kw) @@ -383,7 +386,7 @@ def _wo_exception(*args, **kw): with _Monkey(MUT, _make_api_request_no_retry=_wo_exception, _check_response=_checked.append): - response = self._callFUT(HTTP, REQUEST) + response = self._call_fut(HTTP, REQUEST) self.assertIs(response, RESPONSE) expected_kw = {'redirections': MUT._REDIRECTIONS} @@ -409,7 +412,7 @@ def _wo_exception(*args, **kw): with _Monkey(MUT, _make_api_request_no_retry=_wo_exception, _check_response=_checked.append): - response = self._callFUT(HTTP, REQUEST, retries=5) + response = self._call_fut(HTTP, REQUEST, retries=5) self.assertIs(response, RESPONSE) self.assertEqual(len(_created), 5) @@ -433,7 +436,7 @@ def _wo_exception(*args, **kw): _make_api_request_no_retry=_wo_exception, _check_response=_checked.append): with self.assertRaises(ValueError): - self._callFUT(HTTP, REQUEST, retries=3) + self._call_fut(HTTP, REQUEST, retries=3) self.assertEqual(len(_created), 3) expected_kw = {'redirections': MUT._REDIRECTIONS} diff --git a/core/unit_tests/streaming/test_stream_slice.py b/core/unit_tests/streaming/test_stream_slice.py index 10e9d9bbf25b..c0c5ff375a96 100644 --- a/core/unit_tests/streaming/test_stream_slice.py +++ b/core/unit_tests/streaming/test_stream_slice.py @@ -17,19 +17,20 @@ class Test_StreamSlice(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.stream_slice import StreamSlice return StreamSlice - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from io import BytesIO CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) self.assertIs(stream_slice._stream, stream) self.assertEqual(stream_slice._remaining_bytes, MAXSIZE) self.assertEqual(stream_slice._max_bytes, MAXSIZE) @@ -41,7 +42,7 @@ def test___nonzero___empty(self): CONTENT = b'' MAXSIZE = 0 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) self.assertFalse(stream_slice) def test___nonzero___nonempty(self): @@ -49,7 +50,7 @@ def test___nonzero___nonempty(self): CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) self.assertTrue(stream_slice) def test_read_exhausted(self): @@ -58,7 +59,7 @@ def test_read_exhausted(self): CONTENT = b'' MAXSIZE = 4 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) with self.assertRaises(http_client.IncompleteRead): stream_slice.read() @@ -67,7 +68,7 @@ def test_read_implicit_size(self): CONTENT = b'CONTENT GOES HERE' MAXSIZE = 4 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) self.assertEqual(stream_slice.read(), CONTENT[:MAXSIZE]) self.assertEqual(stream_slice._remaining_bytes, 0) @@ -77,6 +78,6 @@ def test_read_explicit_size(self): MAXSIZE = 4 SIZE = 3 stream = BytesIO(CONTENT) - stream_slice = self._makeOne(stream, MAXSIZE) + stream_slice = self._make_one(stream, MAXSIZE) self.assertEqual(stream_slice.read(SIZE), CONTENT[:SIZE]) self.assertEqual(stream_slice._remaining_bytes, MAXSIZE - SIZE) diff --git a/core/unit_tests/streaming/test_transfer.py b/core/unit_tests/streaming/test_transfer.py index 828e0351f418..d3074f728e24 100644 --- a/core/unit_tests/streaming/test_transfer.py +++ b/core/unit_tests/streaming/test_transfer.py @@ -18,17 +18,18 @@ class Test__Transfer(unittest.TestCase): URL = 'http://example.com/api' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.transfer import _Transfer return _Transfer - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) self.assertIs(xfer.stream, stream) self.assertFalse(xfer.close_stream) self.assertEqual(xfer.chunksize, _DEFAULT_CHUNKSIZE) @@ -44,12 +45,12 @@ def test_ctor_explicit(self): HTTP = object() CHUNK_SIZE = 1 << 18 NUM_RETRIES = 8 - xfer = self._makeOne(stream, - close_stream=True, - chunksize=CHUNK_SIZE, - auto_transfer=False, - http=HTTP, - num_retries=NUM_RETRIES) + xfer = self._make_one(stream, + close_stream=True, + chunksize=CHUNK_SIZE, + auto_transfer=False, + http=HTTP, + num_retries=NUM_RETRIES) self.assertIs(xfer.stream, stream) self.assertTrue(xfer.close_stream) self.assertEqual(xfer.chunksize, CHUNK_SIZE) @@ -61,33 +62,33 @@ def test_ctor_explicit(self): def test_bytes_http_fallback_to_http(self): stream = _Stream() HTTP = object() - xfer = self._makeOne(stream, http=HTTP) + xfer = self._make_one(stream, http=HTTP) self.assertIs(xfer.bytes_http, HTTP) def test_bytes_http_setter(self): stream = _Stream() HTTP = object() BYTES_HTTP = object() - xfer = self._makeOne(stream, http=HTTP) + xfer = self._make_one(stream, http=HTTP) xfer.bytes_http = BYTES_HTTP self.assertIs(xfer.bytes_http, BYTES_HTTP) def test_num_retries_setter_invalid(self): stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) with self.assertRaises(ValueError): xfer.num_retries = object() def test_num_retries_setter_negative(self): stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) with self.assertRaises(ValueError): xfer.num_retries = -1 def test__initialize_not_already_initialized_w_http(self): HTTP = object() stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) xfer._initialize(HTTP, self.URL) self.assertTrue(xfer.initialized) self.assertIs(xfer.http, HTTP) @@ -96,7 +97,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._makeOne(stream) + xfer = self._make_one(stream) xfer._initialize(None, self.URL) self.assertTrue(xfer.initialized) self.assertIsInstance(xfer.http, Http) @@ -105,7 +106,7 @@ def test__initialize_not_already_initialized_wo_http(self): def test__initialize_w_existing_http(self): HTTP_1, HTTP_2 = object(), object() stream = _Stream() - xfer = self._makeOne(stream, http=HTTP_1) + xfer = self._make_one(stream, http=HTTP_1) xfer._initialize(HTTP_2, self.URL) self.assertTrue(xfer.initialized) self.assertIs(xfer.http, HTTP_1) @@ -116,7 +117,7 @@ def test__initialize_already_initialized(self): URL_2 = 'http://example.com/other' HTTP_1, HTTP_2 = object(), object() stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) xfer._initialize(HTTP_1, self.URL) with self.assertRaises(TransferInvalidError): xfer._initialize(HTTP_2, URL_2) @@ -124,27 +125,27 @@ def test__initialize_already_initialized(self): def test__ensure_initialized_hit(self): HTTP = object() stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) xfer._initialize(HTTP, self.URL) xfer._ensure_initialized() # no raise def test__ensure_initialized_miss(self): from google.cloud.streaming.exceptions import TransferInvalidError stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) with self.assertRaises(TransferInvalidError): xfer._ensure_initialized() def test__ensure_uninitialized_hit(self): stream = _Stream() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) xfer._ensure_uninitialized() # no raise def test__ensure_uninitialized_miss(self): from google.cloud.streaming.exceptions import TransferInvalidError stream = _Stream() HTTP = object() - xfer = self._makeOne(stream) + xfer = self._make_one(stream) xfer._initialize(HTTP, self.URL) with self.assertRaises(TransferInvalidError): xfer._ensure_uninitialized() @@ -152,7 +153,7 @@ def test__ensure_uninitialized_miss(self): def test___del___closes_stream(self): stream = _Stream() - xfer = self._makeOne(stream, close_stream=True) + xfer = self._make_one(stream, close_stream=True) self.assertFalse(stream._closed) del xfer @@ -162,16 +163,17 @@ def test___del___closes_stream(self): class Test_Download(unittest.TestCase): URL = "http://example.com/api" - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.transfer import Download return Download - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): stream = _Stream() - download = self._makeOne(stream) + download = self._make_one(stream) self.assertIs(download.stream, stream) self.assertIsNone(download._initial_response) self.assertEqual(download.progress, 0) @@ -181,20 +183,20 @@ def test_ctor_defaults(self): def test_ctor_w_kwds(self): stream = _Stream() CHUNK_SIZE = 123 - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) self.assertIs(download.stream, stream) self.assertEqual(download.chunksize, CHUNK_SIZE) def test_ctor_w_total_size(self): stream = _Stream() SIZE = 123 - download = self._makeOne(stream, total_size=SIZE) + download = self._make_one(stream, total_size=SIZE) self.assertIs(download.stream, stream) self.assertEqual(download.total_size, SIZE) def test_from_file_w_existing_file_no_override(self): import os - klass = self._getTargetClass() + klass = self._get_target_class() with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.out') with open(filename, 'w') as fileobj: @@ -204,7 +206,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 - klass = self._getTargetClass() + klass = self._get_target_class() with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.out') with open(filename, 'w') as fileobj: @@ -218,7 +220,7 @@ def test_from_file_w_existing_file_w_override_wo_auto_transfer(self): def test_from_stream_defaults(self): stream = _Stream() - klass = self._getTargetClass() + klass = self._get_target_class() download = klass.from_stream(stream) self.assertIs(download.stream, stream) self.assertTrue(download.auto_transfer) @@ -228,7 +230,7 @@ def test_from_stream_explicit(self): CHUNK_SIZE = 1 << 18 SIZE = 123 stream = _Stream() - klass = self._getTargetClass() + klass = self._get_target_class() download = klass.from_stream(stream, auto_transfer=False, total_size=SIZE, chunksize=CHUNK_SIZE) self.assertIs(download.stream, stream) @@ -238,7 +240,7 @@ def test_from_stream_explicit(self): def test_configure_request(self): CHUNK_SIZE = 100 - download = self._makeOne(_Stream(), chunksize=CHUNK_SIZE) + download = self._make_one(_Stream(), chunksize=CHUNK_SIZE) request = _Dummy(headers={}) url_builder = _Dummy(query_params={}) download.configure_request(request, url_builder) @@ -247,34 +249,34 @@ def test_configure_request(self): def test__set_total_wo_content_range_wo_existing_total(self): info = {} - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total(info) self.assertEqual(download.total_size, 0) def test__set_total_wo_content_range_w_existing_total(self): SIZE = 123 info = {} - download = self._makeOne(_Stream(), total_size=SIZE) + download = self._make_one(_Stream(), total_size=SIZE) download._set_total(info) self.assertEqual(download.total_size, SIZE) def test__set_total_w_content_range_w_existing_total(self): SIZE = 123 info = {'content-range': 'bytes 123-234/4567'} - download = self._makeOne(_Stream(), total_size=SIZE) + download = self._make_one(_Stream(), total_size=SIZE) download._set_total(info) self.assertEqual(download.total_size, 4567) def test__set_total_w_content_range_w_asterisk_total(self): info = {'content-range': 'bytes 123-234/*'} - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total(info) self.assertEqual(download.total_size, 0) def test_initialize_download_already_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError request = _Request() - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._initialize(None, self.URL) with self.assertRaises(TransferInvalidError): download.initialize_download(request, http=object()) @@ -282,7 +284,7 @@ def test_initialize_download_already_initialized(self): def test_initialize_download_wo_autotransfer(self): request = _Request() http = object() - download = self._makeOne(_Stream(), auto_transfer=False) + download = self._make_one(_Stream(), auto_transfer=False) download.initialize_download(request, http) self.assertIs(download.http, http) self.assertEqual(download.url, request.url) @@ -294,7 +296,7 @@ def test_initialize_download_w_autotransfer_failing(self): from google.cloud.streaming.exceptions import HttpError request = _Request() http = object() - download = self._makeOne(_Stream(), auto_transfer=True) + download = self._make_one(_Stream(), auto_transfer=True) response = _makeResponse(http_client.BAD_REQUEST) requester = _MakeRequest(response) @@ -314,7 +316,7 @@ def test_initialize_download_w_autotransfer_w_content_location(self): request = _Request() http = object() info = {'content-location': REDIRECT_URL} - download = self._makeOne(_Stream(), auto_transfer=True) + download = self._make_one(_Stream(), auto_transfer=True) response = _makeResponse(http_client.NO_CONTENT, info) requester = _MakeRequest(response) @@ -331,14 +333,14 @@ 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._makeOne(_Stream()) + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): download._normalize_start_end(-1, 0) def test__normalize_start_end_w_end_w_start_gt_total(self): from google.cloud.streaming.exceptions import TransferInvalidError - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) with self.assertRaises(TransferInvalidError): @@ -346,65 +348,65 @@ 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._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) with self.assertRaises(TransferInvalidError): download._normalize_start_end(1, 0) def test__normalize_start_end_w_end_gt_start(self): - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) self.assertEqual(download._normalize_start_end(1, 2), (1, 1)) def test__normalize_start_end_wo_end_w_start_lt_0(self): - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/2'}) self.assertEqual(download._normalize_start_end(-2), (0, 1)) self.assertEqual(download._normalize_start_end(-1), (1, 1)) def test__normalize_start_end_wo_end_w_start_ge_0(self): - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_total({'content-range': 'bytes 0-1/100'}) self.assertEqual(download._normalize_start_end(0), (0, 99)) self.assertEqual(download._normalize_start_end(1), (1, 99)) def test__set_range_header_w_start_lt_0(self): request = _Request() - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_range_header(request, -1) self.assertEqual(request.headers['range'], 'bytes=-1') def test__set_range_header_w_start_ge_0_wo_end(self): request = _Request() - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_range_header(request, 0) self.assertEqual(request.headers['range'], 'bytes=0-') def test__set_range_header_w_start_ge_0_w_end(self): request = _Request() - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._set_range_header(request, 0, 1) self.assertEqual(request.headers['range'], 'bytes=0-1') def test__compute_end_byte_w_start_lt_0_w_end(self): - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) self.assertEqual(download._compute_end_byte(-1, 1), 1) def test__compute_end_byte_w_start_ge_0_wo_end_w_use_chunks(self): CHUNK_SIZE = 5 - download = self._makeOne(_Stream(), chunksize=CHUNK_SIZE) + download = self._make_one(_Stream(), chunksize=CHUNK_SIZE) self.assertEqual(download._compute_end_byte(0, use_chunks=True), 4) def test__compute_end_byte_w_start_ge_0_w_end_w_use_chunks(self): CHUNK_SIZE = 5 - download = self._makeOne(_Stream(), chunksize=CHUNK_SIZE) + download = self._make_one(_Stream(), chunksize=CHUNK_SIZE) self.assertEqual(download._compute_end_byte(0, 3, use_chunks=True), 3) self.assertEqual(download._compute_end_byte(0, 5, use_chunks=True), 4) def test__compute_end_byte_w_start_ge_0_w_end_w_total_size(self): CHUNK_SIZE = 50 - download = self._makeOne(_Stream(), chunksize=CHUNK_SIZE) + download = self._make_one(_Stream(), chunksize=CHUNK_SIZE) download._set_total({'content-range': 'bytes 0-1/10'}) self.assertEqual(download._compute_end_byte(0, 100, use_chunks=False), 9) @@ -412,13 +414,13 @@ def test__compute_end_byte_w_start_ge_0_w_end_w_total_size(self): def test__compute_end_byte_w_start_ge_0_wo_end_w_total_size(self): CHUNK_SIZE = 50 - download = self._makeOne(_Stream(), chunksize=CHUNK_SIZE) + download = self._make_one(_Stream(), chunksize=CHUNK_SIZE) download._set_total({'content-range': 'bytes 0-1/10'}) self.assertEqual(download._compute_end_byte(0, use_chunks=False), 9) def test__get_chunk_not_initialized(self): from google.cloud.streaming.exceptions import TransferInvalidError - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): download._get_chunk(0, 10) @@ -428,7 +430,7 @@ def test__get_chunk(self): from google.cloud._testing import _Monkey from google.cloud.streaming import transfer as MUT http = object() - download = self._makeOne(_Stream()) + download = self._make_one(_Stream()) download._initialize(http, self.URL) response = _makeResponse(http_client.OK) requester = _MakeRequest(response) @@ -446,7 +448,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._makeOne(_Stream()) + download = self._make_one(_Stream()) response = _makeResponse(http_client.FORBIDDEN) with self.assertRaises(HttpError): download._process_response(response) @@ -454,7 +456,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._makeOne(_Stream()) + download = self._make_one(_Stream()) response = _makeResponse(http_client.NOT_FOUND) with self.assertRaises(HttpError): download._process_response(response) @@ -462,7 +464,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._makeOne(_Stream()) + download = self._make_one(_Stream()) response = _makeResponse(http_client.BAD_REQUEST) with self.assertRaises(TransferRetryError): download._process_response(response) @@ -470,7 +472,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._makeOne(stream) + download = self._make_one(stream) response = _makeResponse(http_client.OK, content='OK') found = download._process_response(response) self.assertIs(found, response) @@ -481,7 +483,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._makeOne(stream) + download = self._make_one(stream) info = {'content-encoding': 'blah'} response = _makeResponse(http_client.OK, info, 'PARTIAL') found = download._process_response(response) @@ -493,7 +495,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._makeOne(stream) + download = self._make_one(stream) response = _makeResponse( http_client.REQUESTED_RANGE_NOT_SATISFIABLE) found = download._process_response(response) @@ -505,7 +507,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._makeOne(stream) + download = self._make_one(stream) response = _makeResponse(status_code=http_client.NO_CONTENT) found = download._process_response(response) self.assertIs(found, response) @@ -515,7 +517,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._makeOne(_Stream()) + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): download.get_range(0, 10) @@ -529,7 +531,7 @@ def test_get_range_wo_total_size_complete(self): RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN) http = object() stream = _Stream() - download = self._makeOne(stream) + download = self._make_one(stream) download._initialize(http, self.URL) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info, CONTENT) @@ -558,7 +560,7 @@ def test_get_range_wo_total_size_wo_end(self): RESP_RANGE = 'bytes %d-%d/%d' % (START, LEN - 1, LEN) http = object() stream = _Stream() - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) download._initialize(http, self.URL) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info, CONTENT[START:]) @@ -586,7 +588,7 @@ def test_get_range_w_total_size_partial(self): RESP_RANGE = 'bytes 0-%d/%d' % (PARTIAL_LEN, LEN,) http = object() stream = _Stream() - download = self._makeOne(stream, total_size=LEN) + download = self._make_one(stream, total_size=LEN) download._initialize(http, self.URL) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info, CONTENT[:PARTIAL_LEN]) @@ -617,7 +619,7 @@ def test_get_range_w_empty_chunk(self): RESP_RANGE = 'bytes %d-%d/%d' % (START, LEN - 1, LEN) http = object() stream = _Stream() - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) download._initialize(http, self.URL) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info) @@ -646,7 +648,7 @@ def test_get_range_w_total_size_wo_use_chunks(self): RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) http = object() stream = _Stream() - download = self._makeOne(stream, total_size=LEN, chunksize=CHUNK_SIZE) + download = self._make_one(stream, total_size=LEN, chunksize=CHUNK_SIZE) download._initialize(http, self.URL) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info, CONTENT) @@ -676,7 +678,7 @@ def test_get_range_w_multiple_chunks(self): RESP_RANGE_2 = 'bytes %d-%d/%d' % (CHUNK_SIZE, LEN - 1, LEN) http = object() stream = _Stream() - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) download._initialize(http, self.URL) info_1 = {'content-range': RESP_RANGE_1} response_1 = _makeResponse(http_client.PARTIAL_CONTENT, info_1, @@ -701,7 +703,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._makeOne(_Stream()) + download = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): download.stream_file() @@ -712,7 +714,7 @@ def test_stream_file_w_initial_response_complete(self): LEN = len(CONTENT) RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) stream = _Stream() - download = self._makeOne(stream, total_size=LEN) + download = self._make_one(stream, total_size=LEN) info = {'content-range': RESP_RANGE} download._initial_response = _makeResponse( http_client.OK, info, CONTENT) @@ -736,7 +738,7 @@ def test_stream_file_w_initial_response_incomplete(self): RESP_RANGE_2 = 'bytes %d-%d/%d' % (CHUNK_SIZE, LEN - 1, LEN,) stream = _Stream() http = object() - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) info_1 = {'content-range': RESP_RANGE_1} download._initial_response = _makeResponse( http_client.PARTIAL_CONTENT, info_1, CONTENT[:CHUNK_SIZE]) @@ -772,7 +774,7 @@ def test_stream_file_wo_initial_response_wo_total_size(self): RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) stream = _Stream() http = object() - download = self._makeOne(stream, chunksize=CHUNK_SIZE) + download = self._make_one(stream, chunksize=CHUNK_SIZE) info = {'content-range': RESP_RANGE} response = _makeResponse(http_client.OK, info, CONTENT) requester = _MakeRequest(response) @@ -797,17 +799,18 @@ class Test_Upload(unittest.TestCase): MIME_TYPE = 'application/octet-stream' UPLOAD_URL = 'http://example.com/upload/id=foobar' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.streaming.transfer import Upload return Upload - def _makeOne(self, stream, mime_type=MIME_TYPE, *args, **kw): - return self._getTargetClass()(stream, mime_type, *args, **kw) + def _make_one(self, stream, mime_type=MIME_TYPE, *args, **kw): + return self._get_target_class()(stream, mime_type, *args, **kw) def test_ctor_defaults(self): from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE stream = _Stream() - upload = self._makeOne(stream) + upload = self._make_one(stream) self.assertIs(upload.stream, stream) self.assertIsNone(upload._final_response) self.assertIsNone(upload._server_chunk_granularity) @@ -821,20 +824,20 @@ def test_ctor_defaults(self): def test_ctor_w_kwds(self): stream = _Stream() CHUNK_SIZE = 123 - upload = self._makeOne(stream, chunksize=CHUNK_SIZE) + upload = self._make_one(stream, chunksize=CHUNK_SIZE) self.assertIs(upload.stream, stream) self.assertEqual(upload.mime_type, self.MIME_TYPE) self.assertEqual(upload.chunksize, CHUNK_SIZE) def test_from_file_w_nonesuch_file(self): - klass = self._getTargetClass() + klass = self._get_target_class() filename = '~nosuchuser/file.txt' with self.assertRaises(OSError): klass.from_file(filename) def test_from_file_wo_mimetype_w_unguessable_filename(self): import os - klass = self._getTargetClass() + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ UNGUESSABLE MIMETYPE' with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.unguessable') @@ -845,7 +848,7 @@ def test_from_file_wo_mimetype_w_unguessable_filename(self): def test_from_file_wo_mimetype_w_guessable_filename(self): import os - klass = self._getTargetClass() + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ GUESSABLE MIMETYPE' with _tempdir() as tempdir: filename = os.path.join(tempdir, 'file.txt') @@ -859,7 +862,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 - klass = self._getTargetClass() + klass = self._get_target_class() CONTENT = b'EXISTING FILE W/ GUESSABLE MIMETYPE' CHUNK_SIZE = 3 with _tempdir() as tempdir: @@ -878,13 +881,13 @@ def test_from_file_w_mimetype_w_auto_transfer_w_kwds(self): upload._stream.close() def test_from_stream_wo_mimetype(self): - klass = self._getTargetClass() + klass = self._get_target_class() stream = _Stream() with self.assertRaises(ValueError): klass.from_stream(stream, mime_type=None) def test_from_stream_defaults(self): - klass = self._getTargetClass() + klass = self._get_target_class() stream = _Stream() upload = klass.from_stream(stream, mime_type=self.MIME_TYPE) self.assertEqual(upload.mime_type, self.MIME_TYPE) @@ -892,7 +895,7 @@ def test_from_stream_defaults(self): self.assertIsNone(upload.total_size) def test_from_stream_explicit(self): - klass = self._getTargetClass() + klass = self._get_target_class() stream = _Stream() SIZE = 10 CHUNK_SIZE = 3 @@ -908,7 +911,7 @@ def test_from_stream_explicit(self): self.assertEqual(upload.chunksize, CHUNK_SIZE) def test_strategy_setter_invalid(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) with self.assertRaises(ValueError): upload.strategy = object() with self.assertRaises(ValueError): @@ -916,20 +919,20 @@ def test_strategy_setter_invalid(self): def test_strategy_setter_SIMPLE_UPLOAD(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD - upload = self._makeOne(_Stream()) + 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._makeOne(_Stream()) + 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._makeOne(_Stream) + upload = self._make_one(_Stream) http = object() upload._initialize(http, _Request.URL) with self.assertRaises(TransferInvalidError): @@ -937,7 +940,7 @@ def test_total_size_setter_initialized(self): def test_total_size_setter_not_initialized(self): SIZE = 123 - upload = self._makeOne(_Stream) + upload = self._make_one(_Stream) upload.total_size = SIZE self.assertEqual(upload.total_size, SIZE) @@ -949,7 +952,7 @@ def test__set_default_strategy_w_existing_strategy(self): simple_path='/upload/endpoint', ) request = _Request() - upload = self._makeOne(_Stream) + upload = self._make_one(_Stream) upload.strategy = RESUMABLE_UPLOAD upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, RESUMABLE_UPLOAD) @@ -962,7 +965,7 @@ def test__set_default_strategy_wo_resumable_path(self): simple_path='/upload/endpoint', ) request = _Request() - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, SIMPLE_UPLOAD) @@ -971,7 +974,7 @@ def test__set_default_strategy_w_total_size_gt_threshhold(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD config = _UploadConfig() request = _Request() - upload = self._makeOne( + upload = self._make_one( _Stream(), total_size=RESUMABLE_UPLOAD_THRESHOLD + 1) upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, RESUMABLE_UPLOAD) @@ -982,7 +985,7 @@ def test__set_default_strategy_w_body_wo_multipart(self): config = _UploadConfig() config.simple_multipart = False request = _Request(body=CONTENT) - upload = self._makeOne(_Stream(), total_size=len(CONTENT)) + upload = self._make_one(_Stream(), total_size=len(CONTENT)) upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, RESUMABLE_UPLOAD) @@ -992,7 +995,7 @@ def test__set_default_strategy_w_body_w_multipart_wo_simple_path(self): config = _UploadConfig() config.simple_path = None request = _Request(body=CONTENT) - upload = self._makeOne(_Stream(), total_size=len(CONTENT)) + upload = self._make_one(_Stream(), total_size=len(CONTENT)) upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, RESUMABLE_UPLOAD) @@ -1001,7 +1004,7 @@ def test__set_default_strategy_w_body_w_multipart_w_simple_path(self): CONTENT = b'ABCDEFGHIJ' config = _UploadConfig() request = _Request(body=CONTENT) - upload = self._makeOne(_Stream(), total_size=len(CONTENT)) + upload = self._make_one(_Stream(), total_size=len(CONTENT)) upload._set_default_strategy(config, request) self.assertEqual(upload.strategy, SIMPLE_UPLOAD) @@ -1011,7 +1014,7 @@ def test_configure_request_w_total_size_gt_max_size(self): config.max_size = MAX_SIZE request = _Request() url_builder = _Dummy() - upload = self._makeOne(_Stream(), total_size=MAX_SIZE + 1) + upload = self._make_one(_Stream(), total_size=MAX_SIZE + 1) with self.assertRaises(ValueError): upload.configure_request(config, request, url_builder) @@ -1020,7 +1023,7 @@ def test_configure_request_w_invalid_mimetype(self): config.accept = ('text/*',) request = _Request() url_builder = _Dummy() - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) with self.assertRaises(ValueError): upload.configure_request(config, request, url_builder) @@ -1030,7 +1033,7 @@ def test_configure_request_w_simple_wo_body(self): config = _UploadConfig() request = _Request() url_builder = _Dummy(query_params={}) - upload = self._makeOne(_Stream(CONTENT)) + upload = self._make_one(_Stream(CONTENT)) upload.strategy = SIMPLE_UPLOAD upload.configure_request(config, request, url_builder) @@ -1051,7 +1054,7 @@ def test_configure_request_w_simple_w_body(self): request = _Request(body=BODY) request.headers['content-type'] = 'text/plain' url_builder = _Dummy(query_params={}) - upload = self._makeOne(_Stream(CONTENT)) + upload = self._make_one(_Stream(CONTENT)) upload.strategy = SIMPLE_UPLOAD upload.configure_request(config, request, url_builder) @@ -1091,7 +1094,7 @@ def test_configure_request_w_resumable_wo_total_size(self): config = _UploadConfig() request = _Request() url_builder = _Dummy(query_params={}) - upload = self._makeOne(_Stream(CONTENT)) + upload = self._make_one(_Stream(CONTENT)) upload.strategy = RESUMABLE_UPLOAD upload.configure_request(config, request, url_builder) @@ -1109,7 +1112,7 @@ def test_configure_request_w_resumable_w_total_size(self): config = _UploadConfig() request = _Request() url_builder = _Dummy(query_params={}) - upload = self._makeOne(_Stream(CONTENT)) + upload = self._make_one(_Stream(CONTENT)) upload.total_size = LEN upload.strategy = RESUMABLE_UPLOAD @@ -1124,14 +1127,14 @@ 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._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD upload.refresh_upload_state() # no-op 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._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD with self.assertRaises(TransferInvalidError): upload.refresh_upload_state() @@ -1146,7 +1149,7 @@ def test_refresh_upload_state_w_OK(self): RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=LEN) + upload = self._make_one(stream, total_size=LEN) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, _Request.URL) info = {'content-range': RESP_RANGE} @@ -1173,7 +1176,7 @@ def test_refresh_upload_state_w_CREATED(self): RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,) http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=LEN) + upload = self._make_one(stream, total_size=LEN) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, _Request.URL) info = {'content-range': RESP_RANGE} @@ -1200,7 +1203,7 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_w_range(self): LAST = 5 http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=LEN) + upload = self._make_one(stream, total_size=LEN) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, _Request.URL) info = {'range': '0-%d' % (LAST - 1,)} @@ -1226,7 +1229,7 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_wo_range(self): LEN = len(CONTENT) http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=LEN) + upload = self._make_one(stream, total_size=LEN) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, _Request.URL) response = _makeResponse(RESUME_INCOMPLETE, content=CONTENT) @@ -1252,7 +1255,7 @@ def test_refresh_upload_state_w_error(self): LEN = len(CONTENT) http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=LEN) + upload = self._make_one(stream, total_size=LEN) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, _Request.URL) response = _makeResponse(http_client.FORBIDDEN) @@ -1265,30 +1268,30 @@ def test_refresh_upload_state_w_error(self): upload.refresh_upload_state() def test__get_range_header_miss(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) response = _makeResponse(None) self.assertIsNone(upload._get_range_header(response)) def test__get_range_header_w_Range(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) response = _makeResponse(None, {'Range': '123'}) self.assertEqual(upload._get_range_header(response), '123') def test__get_range_header_w_range(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) response = _makeResponse(None, {'range': '123'}) self.assertEqual(upload._get_range_header(response), '123') def test_initialize_upload_no_strategy(self): request = _Request() - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) with self.assertRaises(ValueError): upload.initialize_upload(request, http=object()) def test_initialize_upload_simple_w_http(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD request = _Request() - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD upload.initialize_upload(request, http=object()) # no-op @@ -1296,7 +1299,7 @@ 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._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD upload._initialize(None, self.URL) with self.assertRaises(TransferInvalidError): @@ -1309,7 +1312,7 @@ def test_initialize_upload_w_http_resumable_not_initialized_w_error(self): from google.cloud.streaming.exceptions import HttpError from google.cloud.streaming.transfer import RESUMABLE_UPLOAD request = _Request() - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = RESUMABLE_UPLOAD response = _makeResponse(http_client.FORBIDDEN) requester = _MakeRequest(response) @@ -1324,7 +1327,7 @@ def test_initialize_upload_w_http_wo_auto_transfer_w_OK(self): from google.cloud.streaming import transfer as MUT from google.cloud.streaming.transfer import RESUMABLE_UPLOAD request = _Request() - upload = self._makeOne(_Stream(), auto_transfer=False) + upload = self._make_one(_Stream(), auto_transfer=False) upload.strategy = RESUMABLE_UPLOAD info = {'location': self.UPLOAD_URL} response = _makeResponse(http_client.OK, info) @@ -1347,7 +1350,7 @@ def test_initialize_upload_w_granularity_w_auto_transfer_w_OK(self): CONTENT = b'ABCDEFGHIJ' http = object() request = _Request() - upload = self._makeOne(_Stream(CONTENT), chunksize=1000) + upload = self._make_one(_Stream(CONTENT), chunksize=1000) upload.strategy = RESUMABLE_UPLOAD info = {'X-Goog-Upload-Chunk-Granularity': '100', 'location': self.UPLOAD_URL} @@ -1372,34 +1375,34 @@ def test_initialize_upload_w_granularity_w_auto_transfer_w_OK(self): self.assertEqual(chunk_request.body, CONTENT) def test__last_byte(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) self.assertEqual(upload._last_byte('123-456'), 456) def test__validate_chunksize_wo__server_chunk_granularity(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload._validate_chunksize(123) # no-op def test__validate_chunksize_w__server_chunk_granularity_miss(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload._server_chunk_granularity = 100 with self.assertRaises(ValueError): upload._validate_chunksize(123) def test__validate_chunksize_w__server_chunk_granularity_hit(self): - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload._server_chunk_granularity = 100 upload._validate_chunksize(400) def test_stream_file_w_simple_strategy(self): from google.cloud.streaming.transfer import SIMPLE_UPLOAD - upload = self._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload.strategy = SIMPLE_UPLOAD with self.assertRaises(ValueError): upload.stream_file() def test_stream_file_w_use_chunks_invalid_chunk_size(self): from google.cloud.streaming.transfer import RESUMABLE_UPLOAD - upload = self._makeOne(_Stream(), chunksize=1024) + upload = self._make_one(_Stream(), chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 100 with self.assertRaises(ValueError): @@ -1408,7 +1411,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._makeOne(_Stream(), chunksize=1024) + upload = self._make_one(_Stream(), chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 with self.assertRaises(TransferInvalidError): @@ -1419,7 +1422,7 @@ def test_stream_file_already_complete_w_unseekable_stream(self): http = object() stream = object() response = object() - upload = self._makeOne(stream, chunksize=1024) + upload = self._make_one(stream, chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 upload._initialize(http, _Request.URL) @@ -1434,7 +1437,7 @@ def test_stream_file_already_complete_w_seekable_stream_unsynced(self): http = object() stream = _Stream(CONTENT) response = object() - upload = self._makeOne(stream, chunksize=1024) + upload = self._make_one(stream, chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 upload._initialize(http, _Request.URL) @@ -1451,7 +1454,7 @@ def test_stream_file_already_complete_wo_seekable_method_synced(self): stream = _Stream(CONTENT) stream.seek(0, os.SEEK_END) response = object() - upload = self._makeOne(stream, chunksize=1024) + upload = self._make_one(stream, chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 upload._initialize(http, _Request.URL) @@ -1467,7 +1470,7 @@ def test_stream_file_already_complete_w_seekable_method_true_synced(self): stream = _StreamWithSeekableMethod(CONTENT, True) stream.seek(0, os.SEEK_END) response = object() - upload = self._makeOne(stream, chunksize=1024) + upload = self._make_one(stream, chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 upload._initialize(http, _Request.URL) @@ -1483,7 +1486,7 @@ def test_stream_file_already_complete_w_seekable_method_false(self): stream = _StreamWithSeekableMethod(CONTENT, False) stream.seek(0, os.SEEK_END) response = object() - upload = self._makeOne(stream, chunksize=1024) + upload = self._make_one(stream, chunksize=1024) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 128 upload._initialize(http, _Request.URL) @@ -1500,7 +1503,7 @@ def test_stream_file_incomplete(self): CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream, chunksize=6) + upload = self._make_one(stream, chunksize=6) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 6 upload._initialize(http, self.UPLOAD_URL) @@ -1545,7 +1548,7 @@ def test_stream_file_incomplete_w_transfer_error(self): CONTENT = b'ABCDEFGHIJ' http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream, chunksize=6) + upload = self._make_one(stream, chunksize=6) upload.strategy = RESUMABLE_UPLOAD upload._server_chunk_granularity = 6 upload._initialize(http, self.UPLOAD_URL) @@ -1581,7 +1584,7 @@ def test__send_media_request_wo_error(self): CONTENT = b'ABCDEFGHIJ' bytes_http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream) + upload = self._make_one(stream) upload.bytes_http = bytes_http headers = {'Content-Range': 'bytes 0-9/10', @@ -1612,7 +1615,7 @@ def test__send_media_request_w_error(self): bytes_http = object() http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream) + upload = self._make_one(stream) upload.strategy = RESUMABLE_UPLOAD upload._initialize(http, self.UPLOAD_URL) upload.bytes_http = bytes_http @@ -1644,14 +1647,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._makeOne(_Stream()) + 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._makeOne(_Stream()) + upload = self._make_one(_Stream()) upload._initialize(http, _Request.URL) with self.assertRaises(TransferInvalidError): upload._send_media_body(0) @@ -1661,7 +1664,7 @@ def test__send_media_body_start_lt_total_size(self): SIZE = 1234 http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=SIZE) + upload = self._make_one(stream, total_size=SIZE) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) @@ -1688,7 +1691,7 @@ def test__send_media_body_start_eq_total_size(self): SIZE = 1234 http = object() stream = _Stream() - upload = self._makeOne(stream, total_size=SIZE) + upload = self._make_one(stream, total_size=SIZE) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) @@ -1712,7 +1715,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._makeOne(_Stream()) + upload = self._make_one(_Stream()) with self.assertRaises(TransferInvalidError): upload._send_chunk(0) @@ -1720,7 +1723,7 @@ def test__send_chunk_wo_total_size_stream_exhausted(self): CONTENT = b'ABCDEFGHIJ' SIZE = len(CONTENT) http = object() - upload = self._makeOne(_Stream(CONTENT), chunksize=1000) + upload = self._make_one(_Stream(CONTENT), chunksize=1000) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) @@ -1746,7 +1749,7 @@ def test__send_chunk_wo_total_size_stream_not_exhausted(self): SIZE = len(CONTENT) CHUNK_SIZE = SIZE - 5 http = object() - upload = self._makeOne(_Stream(CONTENT), chunksize=CHUNK_SIZE) + upload = self._make_one(_Stream(CONTENT), chunksize=CHUNK_SIZE) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) @@ -1776,7 +1779,7 @@ def test__send_chunk_w_total_size_stream_not_exhausted(self): CHUNK_SIZE = SIZE - 5 http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream, total_size=SIZE, chunksize=CHUNK_SIZE) + upload = self._make_one(stream, total_size=SIZE, chunksize=CHUNK_SIZE) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) @@ -1807,7 +1810,7 @@ def test__send_chunk_w_total_size_stream_exhausted(self): CHUNK_SIZE = 1000 http = object() stream = _Stream(CONTENT) - upload = self._makeOne(stream, total_size=SIZE, chunksize=CHUNK_SIZE) + upload = self._make_one(stream, total_size=SIZE, chunksize=CHUNK_SIZE) upload._initialize(http, self.UPLOAD_URL) response = object() streamer = _MediaStreamer(response) diff --git a/core/unit_tests/streaming/test_util.py b/core/unit_tests/streaming/test_util.py index c760a1955610..1ee1c03d073f 100644 --- a/core/unit_tests/streaming/test_util.py +++ b/core/unit_tests/streaming/test_util.py @@ -17,7 +17,7 @@ class Test_calculate_wait_for_retry(unittest.TestCase): - def _callFUT(self, *args, **kw): + def _call_fut(self, *args, **kw): from google.cloud.streaming.util import calculate_wait_for_retry return calculate_wait_for_retry(*args, **kw) @@ -25,38 +25,38 @@ 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._callFUT(1), 1.5) + 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._callFUT(4), 20) + self.assertEqual(self._call_fut(4), 20) class Test_acceptable_mime_type(unittest.TestCase): - def _callFUT(self, *args, **kw): + 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): with self.assertRaises(ValueError) as err: - self._callFUT(['text/*'], 'BOGUS') + self._call_fut(['text/*'], 'BOGUS') self.assertEqual( err.exception.args, ('Invalid MIME type: "BOGUS"',)) def test_accept_pattern_w_semicolon(self): with self.assertRaises(ValueError) as err: - self._callFUT(['text/*;charset=utf-8'], 'text/plain') + self._call_fut(['text/*;charset=utf-8'], 'text/plain') self.assertEqual( err.exception.args, ('MIME patterns with parameter unsupported: ' '"text/*;charset=utf-8"',)) def test_miss(self): - self.assertFalse(self._callFUT(['image/*'], 'text/plain')) + self.assertFalse(self._call_fut(['image/*'], 'text/plain')) def test_hit(self): - self.assertTrue(self._callFUT(['text/*'], 'text/plain')) + self.assertTrue(self._call_fut(['text/*'], 'text/plain')) diff --git a/core/unit_tests/test__helpers.py b/core/unit_tests/test__helpers.py index f939d34ee74e..9430caf19967 100644 --- a/core/unit_tests/test__helpers.py +++ b/core/unit_tests/test__helpers.py @@ -18,17 +18,18 @@ class Test__LocalStack(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud._helpers import _LocalStack return _LocalStack - def _makeOne(self): - return self._getTargetClass()() + def _make_one(self): + return self._get_target_class()() def test_it(self): batch1, batch2 = object(), object() - batches = self._makeOne() + batches = self._make_one() self.assertEqual(list(batches), []) self.assertIsNone(batches.top) batches.push(batch1) @@ -46,16 +47,17 @@ def test_it(self): class Test__UTC(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud._helpers import _UTC return _UTC - def _makeOne(self): - return self._getTargetClass()() + def _make_one(self): + return self._get_target_class()() def test_module_property(self): from google.cloud import _helpers as MUT - klass = self._getTargetClass() + klass = self._get_target_class() try: import pytz except ImportError: @@ -66,7 +68,7 @@ def test_module_property(self): def test_dst(self): import datetime - tz = self._makeOne() + tz = self._make_one() self.assertEqual(tz.dst(None), datetime.timedelta(0)) def test_fromutc(self): @@ -74,59 +76,59 @@ def test_fromutc(self): naive_epoch = datetime.datetime.utcfromtimestamp(0) self.assertIsNone(naive_epoch.tzinfo) - tz = self._makeOne() + tz = self._make_one() epoch = tz.fromutc(naive_epoch) self.assertEqual(epoch.tzinfo, tz) def test_tzname(self): - tz = self._makeOne() + tz = self._make_one() self.assertEqual(tz.tzname(None), 'UTC') def test_utcoffset(self): import datetime - tz = self._makeOne() + tz = self._make_one() self.assertEqual(tz.utcoffset(None), datetime.timedelta(0)) def test___repr__(self): - tz = self._makeOne() + tz = self._make_one() self.assertEqual(repr(tz), '') def test___str__(self): - tz = self._makeOne() + tz = self._make_one() self.assertEqual(str(tz), 'UTC') class Test__ensure_tuple_or_list(unittest.TestCase): - def _callFUT(self, arg_name, tuple_or_list): + 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): valid_tuple_or_list = ('a', 'b', 'c', 'd') - result = self._callFUT('ARGNAME', valid_tuple_or_list) + result = self._call_fut('ARGNAME', valid_tuple_or_list) self.assertEqual(result, ['a', 'b', 'c', 'd']) def test_valid_list(self): valid_tuple_or_list = ['a', 'b', 'c', 'd'] - result = self._callFUT('ARGNAME', valid_tuple_or_list) + result = self._call_fut('ARGNAME', valid_tuple_or_list) self.assertEqual(result, valid_tuple_or_list) def test_invalid(self): invalid_tuple_or_list = object() with self.assertRaises(TypeError): - self._callFUT('ARGNAME', invalid_tuple_or_list) + self._call_fut('ARGNAME', invalid_tuple_or_list) def test_invalid_iterable(self): invalid_tuple_or_list = 'FOO' with self.assertRaises(TypeError): - self._callFUT('ARGNAME', invalid_tuple_or_list) + self._call_fut('ARGNAME', invalid_tuple_or_list) class Test__app_engine_id(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _app_engine_id return _app_engine_id() @@ -135,7 +137,7 @@ def test_no_value(self): from google.cloud import _helpers with _Monkey(_helpers, app_identity=None): - dataset_id = self._callFUT() + dataset_id = self._call_fut() self.assertIsNone(dataset_id) def test_value_set(self): @@ -145,13 +147,13 @@ def test_value_set(self): APP_ENGINE_ID = object() APP_IDENTITY = _AppIdentity(APP_ENGINE_ID) with _Monkey(_helpers, app_identity=APP_IDENTITY): - dataset_id = self._callFUT() + dataset_id = self._call_fut() self.assertEqual(dataset_id, APP_ENGINE_ID) class Test__file_project_id(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _file_project_id return _file_project_id() @@ -168,7 +170,7 @@ def test_success(self): environ = {CREDENTIALS: temp.name} with _Monkey(os, getenv=environ.get): - result = self._callFUT() + result = self._call_fut() self.assertEqual(result, project_id) @@ -177,14 +179,14 @@ def test_no_environment_variable_set(self): environ = {} with _Monkey(os, getenv=environ.get): - result = self._callFUT() + result = self._call_fut() self.assertIsNone(result) class Test__get_nix_config_path(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _get_nix_config_path return _get_nix_config_path() @@ -196,7 +198,7 @@ def test_it(self): config_file = 'b' with _Monkey(MUT, _USER_ROOT=user_root, _GCLOUD_CONFIG_FILE=config_file): - result = self._callFUT() + result = self._call_fut() expected = os.path.join(user_root, '.config', config_file) self.assertEqual(result, expected) @@ -204,7 +206,7 @@ def test_it(self): class Test__get_windows_config_path(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _get_windows_config_path return _get_windows_config_path() @@ -217,7 +219,7 @@ def test_it(self): config_file = 'b' with _Monkey(os, getenv=environ.get): with _Monkey(MUT, _GCLOUD_CONFIG_FILE=config_file): - result = self._callFUT() + result = self._call_fut() expected = os.path.join(appdata_dir, config_file) self.assertEqual(result, expected) @@ -227,7 +229,7 @@ class Test__default_service_project_id(unittest.TestCase): CONFIG_TEMPLATE = '[%s]\n%s = %s\n' - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _default_service_project_id return _default_service_project_id() @@ -250,7 +252,7 @@ def mock_get_path(): with _Monkey(os, name='not-nt'): with _Monkey(MUT, _get_nix_config_path=mock_get_path, _USER_ROOT='not-None'): - result = self._callFUT() + result = self._call_fut() self.assertEqual(result, project_id) @@ -270,7 +272,7 @@ def mock_get_path(): with _Monkey(os, name='not-nt'): with _Monkey(MUT, _get_nix_config_path=mock_get_path, _USER_ROOT='not-None'): - result = self._callFUT() + result = self._call_fut() self.assertEqual(result, None) @@ -293,7 +295,7 @@ def mock_get_path(): with _Monkey(os, name='nt'): with _Monkey(MUT, _get_windows_config_path=mock_get_path, _USER_ROOT=None): - result = self._callFUT() + result = self._call_fut() self.assertEqual(result, project_id) @@ -303,14 +305,14 @@ def test_gae(self): with _Monkey(os, name='not-nt'): with _Monkey(MUT, _USER_ROOT=None): - result = self._callFUT() + result = self._call_fut() self.assertIsNone(result) class Test__compute_engine_id(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _compute_engine_id return _compute_engine_id() @@ -328,26 +330,26 @@ def _connection_factory(host, timeout): def test_bad_status(self): connection = _HTTPConnection(404, None) with self._monkeyConnection(connection): - dataset_id = self._callFUT() + dataset_id = self._call_fut() self.assertIsNone(dataset_id) def test_success(self): COMPUTE_ENGINE_ID = object() connection = _HTTPConnection(200, COMPUTE_ENGINE_ID) with self._monkeyConnection(connection): - dataset_id = self._callFUT() + dataset_id = self._call_fut() self.assertEqual(dataset_id, COMPUTE_ENGINE_ID) def test_socket_raises(self): connection = _TimeoutHTTPConnection() with self._monkeyConnection(connection): - dataset_id = self._callFUT() + dataset_id = self._call_fut() self.assertIsNone(dataset_id) class Test__get_production_project(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud._helpers import _get_production_project return _get_production_project() @@ -356,7 +358,7 @@ def test_no_value(self): environ = {} with _Monkey(os, getenv=environ.get): - project = self._callFUT() + project = self._call_fut() self.assertIsNone(project) def test_value_set(self): @@ -366,13 +368,13 @@ def test_value_set(self): MOCK_PROJECT = object() environ = {PROJECT: MOCK_PROJECT} with _Monkey(os, getenv=environ.get): - project = self._callFUT() + project = self._call_fut() self.assertEqual(project, MOCK_PROJECT) class Test__determine_default_project(unittest.TestCase): - def _callFUT(self, project=None): + def _call_fut(self, project=None): from google.cloud._helpers import _determine_default_project return _determine_default_project(project=project) @@ -412,7 +414,7 @@ def gce_mock(): } with _Monkey(_helpers, **patched_methods): - returned_project = self._callFUT(project) + returned_project = self._call_fut(project) return returned_project, _callers @@ -451,7 +453,7 @@ def test_gce(self): class Test__millis(unittest.TestCase): - def _callFUT(self, value): + def _call_fut(self, value): from google.cloud._helpers import _millis return _millis(value) @@ -460,12 +462,12 @@ def test_one_second_from_epoch(self): from google.cloud._helpers import UTC WHEN = datetime.datetime(1970, 1, 1, 0, 0, 1, tzinfo=UTC) - self.assertEqual(self._callFUT(WHEN), 1000) + self.assertEqual(self._call_fut(WHEN), 1000) class Test__microseconds_from_datetime(unittest.TestCase): - def _callFUT(self, value): + def _call_fut(self, value): from google.cloud._helpers import _microseconds_from_datetime return _microseconds_from_datetime(value) @@ -476,18 +478,18 @@ def test_it(self): timestamp = datetime.datetime(1970, 1, 1, hour=0, minute=0, second=0, microsecond=microseconds) - result = self._callFUT(timestamp) + result = self._call_fut(timestamp) self.assertEqual(result, microseconds) class Test__millis_from_datetime(unittest.TestCase): - def _callFUT(self, value): + def _call_fut(self, value): from google.cloud._helpers import _millis_from_datetime return _millis_from_datetime(value) def test_w_none(self): - self.assertIsNone(self._callFUT(None)) + self.assertIsNone(self._call_fut(None)) def test_w_utc_datetime(self): import datetime @@ -498,7 +500,7 @@ def test_w_utc_datetime(self): NOW = datetime.datetime.utcnow().replace(tzinfo=UTC) NOW_MICROS = _microseconds_from_datetime(NOW) MILLIS = NOW_MICROS // 1000 - result = self._callFUT(NOW) + result = self._call_fut(NOW) self.assertIsInstance(result, six.integer_types) self.assertEqual(result, MILLIS) @@ -516,7 +518,7 @@ class CET(_UTC): NOW = datetime.datetime(2015, 7, 28, 16, 34, 47, tzinfo=zone) NOW_MICROS = _microseconds_from_datetime(NOW) MILLIS = NOW_MICROS // 1000 - result = self._callFUT(NOW) + result = self._call_fut(NOW) self.assertIsInstance(result, six.integer_types) self.assertEqual(result, MILLIS) @@ -530,14 +532,14 @@ def test_w_naive_datetime(self): UTC_NOW = NOW.replace(tzinfo=UTC) UTC_NOW_MICROS = _microseconds_from_datetime(UTC_NOW) MILLIS = UTC_NOW_MICROS // 1000 - result = self._callFUT(NOW) + result = self._call_fut(NOW) self.assertIsInstance(result, six.integer_types) self.assertEqual(result, MILLIS) class Test__datetime_from_microseconds(unittest.TestCase): - def _callFUT(self, value): + def _call_fut(self, value): from google.cloud._helpers import _datetime_from_microseconds return _datetime_from_microseconds(value) @@ -549,24 +551,24 @@ def test_it(self): NOW = datetime.datetime(2015, 7, 29, 17, 45, 21, 123456, tzinfo=UTC) NOW_MICROS = _microseconds_from_datetime(NOW) - self.assertEqual(self._callFUT(NOW_MICROS), NOW) + self.assertEqual(self._call_fut(NOW_MICROS), NOW) class Test___date_from_iso8601_date(unittest.TestCase): - def _callFUT(self, value): + 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._callFUT(TODAY.strftime("%Y-%m-%d")), TODAY) + self.assertEqual(self._call_fut(TODAY.strftime("%Y-%m-%d")), TODAY) class Test__rfc3339_to_datetime(unittest.TestCase): - def _callFUT(self, dt_str): + def _call_fut(self, dt_str): from google.cloud._helpers import _rfc3339_to_datetime return _rfc3339_to_datetime(dt_str) @@ -582,7 +584,7 @@ def test_w_bogus_zone(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%06dBOGUS' % ( year, month, day, hour, minute, seconds, micros) with self.assertRaises(ValueError): - self._callFUT(dt_str) + self._call_fut(dt_str) def test_w_microseconds(self): import datetime @@ -598,7 +600,7 @@ def test_w_microseconds(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%06dZ' % ( year, month, day, hour, minute, seconds, micros) - result = self._callFUT(dt_str) + result = self._call_fut(dt_str) expected_result = datetime.datetime( year, month, day, hour, minute, seconds, micros, UTC) self.assertEqual(result, expected_result) @@ -615,12 +617,12 @@ def test_w_naonseconds(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%09dZ' % ( year, month, day, hour, minute, seconds, nanos) with self.assertRaises(ValueError): - self._callFUT(dt_str) + self._call_fut(dt_str) class Test__rfc3339_nanos_to_datetime(unittest.TestCase): - def _callFUT(self, dt_str): + def _call_fut(self, dt_str): from google.cloud._helpers import _rfc3339_nanos_to_datetime return _rfc3339_nanos_to_datetime(dt_str) @@ -636,7 +638,7 @@ def test_w_bogus_zone(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%06dBOGUS' % ( year, month, day, hour, minute, seconds, micros) with self.assertRaises(ValueError): - self._callFUT(dt_str) + self._call_fut(dt_str) def test_w_truncated_nanos(self): import datetime @@ -662,7 +664,7 @@ def test_w_truncated_nanos(self): for truncated, micros in truncateds_and_micros: dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%sZ' % ( year, month, day, hour, minute, seconds, truncated) - result = self._callFUT(dt_str) + result = self._call_fut(dt_str) expected_result = datetime.datetime( year, month, day, hour, minute, seconds, micros, UTC) self.assertEqual(result, expected_result) @@ -680,7 +682,7 @@ def test_without_nanos(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02dZ' % ( year, month, day, hour, minute, seconds) - result = self._callFUT(dt_str) + result = self._call_fut(dt_str) expected_result = datetime.datetime( year, month, day, hour, minute, seconds, 0, UTC) self.assertEqual(result, expected_result) @@ -700,7 +702,7 @@ def test_w_naonseconds(self): dt_str = '%d-%02d-%02dT%02d:%02d:%02d.%09dZ' % ( year, month, day, hour, minute, seconds, nanos) - result = self._callFUT(dt_str) + result = self._call_fut(dt_str) expected_result = datetime.datetime( year, month, day, hour, minute, seconds, micros, UTC) self.assertEqual(result, expected_result) @@ -708,7 +710,7 @@ def test_w_naonseconds(self): class Test__datetime_to_rfc3339(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud._helpers import _datetime_to_rfc3339 return _datetime_to_rfc3339(*args, **kwargs) @@ -727,7 +729,7 @@ def test_w_utc_datetime(self): from google.cloud._helpers import UTC TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=UTC) - result = self._callFUT(TIMESTAMP, ignore_zone=False) + result = self._call_fut(TIMESTAMP, ignore_zone=False) self.assertEqual(result, '2016-04-05T13:30:00.000000Z') def test_w_non_utc_datetime(self): @@ -735,7 +737,7 @@ def test_w_non_utc_datetime(self): zone = self._make_timezone(offset=datetime.timedelta(hours=-1)) TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=zone) - result = self._callFUT(TIMESTAMP, ignore_zone=False) + result = self._call_fut(TIMESTAMP, ignore_zone=False) self.assertEqual(result, '2016-04-05T14:30:00.000000Z') def test_w_non_utc_datetime_and_ignore_zone(self): @@ -743,68 +745,68 @@ def test_w_non_utc_datetime_and_ignore_zone(self): zone = self._make_timezone(offset=datetime.timedelta(hours=-1)) TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=zone) - result = self._callFUT(TIMESTAMP) + result = self._call_fut(TIMESTAMP) self.assertEqual(result, '2016-04-05T13:30:00.000000Z') def test_w_naive_datetime(self): import datetime TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0) - result = self._callFUT(TIMESTAMP) + result = self._call_fut(TIMESTAMP) self.assertEqual(result, '2016-04-05T13:30:00.000000Z') class Test__to_bytes(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud._helpers import _to_bytes return _to_bytes(*args, **kwargs) def test_with_bytes(self): value = b'bytes-val' - self.assertEqual(self._callFUT(value), value) + self.assertEqual(self._call_fut(value), value) def test_with_unicode(self): value = u'string-val' encoded_value = b'string-val' - self.assertEqual(self._callFUT(value), encoded_value) + self.assertEqual(self._call_fut(value), encoded_value) def test_unicode_non_ascii(self): value = u'\u2013' # Long hyphen encoded_value = b'\xe2\x80\x93' - self.assertRaises(UnicodeEncodeError, self._callFUT, value) - self.assertEqual(self._callFUT(value, encoding='utf-8'), + self.assertRaises(UnicodeEncodeError, self._call_fut, value) + self.assertEqual(self._call_fut(value, encoding='utf-8'), encoded_value) def test_with_nonstring_type(self): value = object() - self.assertRaises(TypeError, self._callFUT, value) + self.assertRaises(TypeError, self._call_fut, value) class Test__bytes_to_unicode(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + 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): value = b'bytes-val' encoded_value = 'bytes-val' - self.assertEqual(self._callFUT(value), encoded_value) + self.assertEqual(self._call_fut(value), encoded_value) def test_with_unicode(self): value = u'string-val' encoded_value = 'string-val' - self.assertEqual(self._callFUT(value), encoded_value) + self.assertEqual(self._call_fut(value), encoded_value) def test_with_nonstring_type(self): value = object() - self.assertRaises(ValueError, self._callFUT, value) + self.assertRaises(ValueError, self._call_fut, value) class Test__pb_timestamp_to_datetime(unittest.TestCase): - def _callFUT(self, timestamp): + def _call_fut(self, timestamp): from google.cloud._helpers import _pb_timestamp_to_datetime return _pb_timestamp_to_datetime(timestamp) @@ -820,12 +822,12 @@ def test_it(self): # ... so 1 minute and 1 second after is 61 seconds and 1234 # microseconds is 1234000 nanoseconds. timestamp = Timestamp(seconds=61, nanos=1234000) - self.assertEqual(self._callFUT(timestamp), dt_stamp) + self.assertEqual(self._call_fut(timestamp), dt_stamp) class Test__pb_timestamp_to_rfc3339(unittest.TestCase): - def _callFUT(self, timestamp): + def _call_fut(self, timestamp): from google.cloud._helpers import _pb_timestamp_to_rfc3339 return _pb_timestamp_to_rfc3339(timestamp) @@ -836,13 +838,13 @@ def test_it(self): # ... so 1 minute and 1 second after is 61 seconds and 1234 # microseconds is 1234000 nanoseconds. timestamp = Timestamp(seconds=61, nanos=1234000) - self.assertEqual(self._callFUT(timestamp), + self.assertEqual(self._call_fut(timestamp), '1970-01-01T00:01:01.001234Z') class Test__datetime_to_pb_timestamp(unittest.TestCase): - def _callFUT(self, when): + def _call_fut(self, when): from google.cloud._helpers import _datetime_to_pb_timestamp return _datetime_to_pb_timestamp(when) @@ -858,7 +860,7 @@ def test_it(self): # ... so 1 minute and 1 second after is 61 seconds and 1234 # microseconds is 1234000 nanoseconds. timestamp = Timestamp(seconds=61, nanos=1234000) - self.assertEqual(self._callFUT(dt_stamp), timestamp) + self.assertEqual(self._call_fut(dt_stamp), timestamp) class Test__name_from_project_path(unittest.TestCase): @@ -867,54 +869,55 @@ class Test__name_from_project_path(unittest.TestCase): THING_NAME = 'THING_NAME' TEMPLATE = r'projects/(?P\w+)/things/(?P\w+)' - def _callFUT(self, path, project, template): + def _call_fut(self, path, project, template): from google.cloud._helpers import _name_from_project_path return _name_from_project_path(path, project, template) def test_w_invalid_path_length(self): PATH = 'projects/foo' with self.assertRaises(ValueError): - self._callFUT(PATH, None, self.TEMPLATE) + self._call_fut(PATH, None, self.TEMPLATE) def test_w_invalid_path_segments(self): PATH = 'foo/%s/bar/%s' % (self.PROJECT, self.THING_NAME) with self.assertRaises(ValueError): - self._callFUT(PATH, self.PROJECT, self.TEMPLATE) + self._call_fut(PATH, self.PROJECT, self.TEMPLATE) def test_w_mismatched_project(self): PROJECT1 = 'PROJECT1' PROJECT2 = 'PROJECT2' PATH = 'projects/%s/things/%s' % (PROJECT1, self.THING_NAME) with self.assertRaises(ValueError): - self._callFUT(PATH, PROJECT2, self.TEMPLATE) + self._call_fut(PATH, PROJECT2, self.TEMPLATE) 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._callFUT(PATH, self.PROJECT, template) + name = self._call_fut(PATH, self.PROJECT, template) self.assertEqual(name, self.THING_NAME) def test_w_project_passed_as_none(self): PROJECT1 = 'PROJECT1' PATH = 'projects/%s/things/%s' % (PROJECT1, self.THING_NAME) - self._callFUT(PATH, None, self.TEMPLATE) - name = self._callFUT(PATH, None, self.TEMPLATE) + self._call_fut(PATH, None, self.TEMPLATE) + name = self._call_fut(PATH, None, self.TEMPLATE) self.assertEqual(name, self.THING_NAME) class TestMetadataPlugin(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud._helpers import MetadataPlugin return MetadataPlugin - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): credentials = object() - plugin = self._makeOne(credentials) + plugin = self._make_one(credentials) self.assertIs(plugin._credentials, credentials) def test___call__(self): @@ -925,7 +928,7 @@ def test___call__(self): def callback(*args): callback_args.append(args) - transformer = self._makeOne(credentials) + transformer = self._make_one(credentials) result = transformer(None, callback) cb_headers = [ ('authorization', 'Bearer ' + access_token_expected), @@ -937,7 +940,7 @@ def callback(*args): class Test_make_secure_channel(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_secure_channel return make_secure_channel(*args, **kwargs) @@ -988,7 +991,7 @@ def mock_plugin(*args): user_agent = 'USER_AGENT' with _Monkey(MUT, grpc=grpc_mod, MetadataPlugin=mock_plugin): - result = self._callFUT(credentials, user_agent, host) + result = self._call_fut(credentials, user_agent, host) self.assertIs(result, CHANNEL) self.assertEqual(plugin_args, [(credentials,)]) @@ -1009,7 +1012,7 @@ def mock_plugin(*args): class Test_make_secure_stub(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_secure_stub return make_secure_stub(*args, **kwargs) @@ -1034,8 +1037,8 @@ def mock_channel(*args): user_agent = 'you-sir-age-int' host = 'localhost' with _Monkey(MUT, make_secure_channel=mock_channel): - stub = self._callFUT(credentials, user_agent, - stub_class, host) + stub = self._call_fut(credentials, user_agent, + stub_class, host) self.assertIs(stub, result) self.assertEqual(channels, [channel_obj]) @@ -1045,7 +1048,7 @@ def mock_channel(*args): class Test_make_insecure_stub(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud._helpers import make_insecure_stub return make_insecure_stub(*args, **kwargs) @@ -1070,7 +1073,7 @@ def mock_stub_class(channel): return mock_result with _Monkey(MUT, grpc=grpc_mod): - result = self._callFUT(mock_stub_class, host, port=port) + result = self._call_fut(mock_stub_class, host, port=port) self.assertIs(result, mock_result) self.assertEqual(stub_inputs, [CHANNEL]) diff --git a/core/unit_tests/test_client.py b/core/unit_tests/test_client.py index c7e4c6536e1b..3ae51b9e82cd 100644 --- a/core/unit_tests/test_client.py +++ b/core/unit_tests/test_client.py @@ -17,32 +17,34 @@ class Test_ClientFactoryMixin(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.client import _ClientFactoryMixin return _ClientFactoryMixin def test_virtual(self): - klass = self._getTargetClass() + klass = self._get_target_class() self.assertFalse('__init__' in klass.__dict__) class TestClient(unittest.TestCase): def setUp(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() self.original_cnxn_class = KLASS._connection_class KLASS._connection_class = _MockConnection def tearDown(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() KLASS._connection_class = self.original_cnxn_class - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): from google.cloud._testing import _Monkey @@ -56,7 +58,7 @@ def mock_get_credentials(): return CREDENTIALS with _Monkey(client, get_credentials=mock_get_credentials): - client_obj = self._makeOne() + client_obj = self._make_one() self.assertIsInstance(client_obj.connection, _MockConnection) self.assertIs(client_obj.connection.credentials, CREDENTIALS) @@ -65,7 +67,7 @@ def mock_get_credentials(): def test_ctor_explicit(self): CREDENTIALS = object() HTTP = object() - client_obj = self._makeOne(credentials=CREDENTIALS, http=HTTP) + client_obj = self._make_one(credentials=CREDENTIALS, http=HTTP) self.assertIsInstance(client_obj.connection, _MockConnection) self.assertIs(client_obj.connection.credentials, CREDENTIALS) @@ -75,7 +77,7 @@ def test_from_service_account_json(self): from google.cloud._testing import _Monkey from google.cloud import client - KLASS = self._getTargetClass() + KLASS = self._get_target_class() MOCK_FILENAME = 'foo.path' mock_creds = _MockServiceAccountCredentials() with _Monkey(client, ServiceAccountCredentials=mock_creds): @@ -85,7 +87,7 @@ def test_from_service_account_json(self): self.assertEqual(mock_creds.json_called, [MOCK_FILENAME]) def test_from_service_account_json_fail(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() CREDENTIALS = object() self.assertRaises(TypeError, KLASS.from_service_account_json, None, credentials=CREDENTIALS) @@ -94,7 +96,7 @@ def test_from_service_account_p12(self): from google.cloud._testing import _Monkey from google.cloud import client - KLASS = self._getTargetClass() + KLASS = self._get_target_class() CLIENT_EMAIL = 'phred@example.com' MOCK_FILENAME = 'foo.path' mock_creds = _MockServiceAccountCredentials() @@ -107,7 +109,7 @@ def test_from_service_account_p12(self): [(CLIENT_EMAIL, MOCK_FILENAME)]) def test_from_service_account_p12_fail(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() CREDENTIALS = object() self.assertRaises(TypeError, KLASS.from_service_account_p12, None, None, credentials=CREDENTIALS) @@ -116,20 +118,21 @@ def test_from_service_account_p12_fail(self): class TestJSONClient(unittest.TestCase): def setUp(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() self.original_cnxn_class = KLASS._connection_class KLASS._connection_class = _MockConnection def tearDown(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() KLASS._connection_class = self.original_cnxn_class - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.client import JSONClient return JSONClient - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): from google.cloud._testing import _Monkey @@ -149,7 +152,7 @@ def mock_get_credentials(): with _Monkey(client, get_credentials=mock_get_credentials, _determine_default_project=mock_determine_proj): - client_obj = self._makeOne() + client_obj = self._make_one() self.assertEqual(client_obj.project, PROJECT) self.assertIsInstance(client_obj.connection, _MockConnection) @@ -169,7 +172,7 @@ def mock_determine_proj(project): return None with _Monkey(client, _determine_default_project=mock_determine_proj): - self.assertRaises(EnvironmentError, self._makeOne) + self.assertRaises(EnvironmentError, self._make_one) self.assertEqual(FUNC_CALLS, [(None, '_determine_default_project')]) @@ -177,7 +180,8 @@ def test_ctor_w_invalid_project(self): CREDENTIALS = object() HTTP = object() with self.assertRaises(ValueError): - self._makeOne(project=object(), credentials=CREDENTIALS, http=HTTP) + self._make_one(project=object(), credentials=CREDENTIALS, + http=HTTP) def _explicit_ctor_helper(self, project): import six @@ -185,8 +189,8 @@ def _explicit_ctor_helper(self, project): CREDENTIALS = object() HTTP = object() - client_obj = self._makeOne(project=project, credentials=CREDENTIALS, - http=HTTP) + client_obj = self._make_one(project=project, credentials=CREDENTIALS, + http=HTTP) if isinstance(project, six.binary_type): self.assertEqual(client_obj.project, project.decode('utf-8')) diff --git a/core/unit_tests/test_connection.py b/core/unit_tests/test_connection.py index e2a02e83bdf7..e2eaa7e267aa 100644 --- a/core/unit_tests/test_connection.py +++ b/core/unit_tests/test_connection.py @@ -17,45 +17,46 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): - conn = self._makeOne() + conn = self._make_one() self.assertIsNone(conn.credentials) def test_ctor_explicit(self): credentials = _Credentials() self.assertEqual(credentials._create_scoped_calls, 0) - conn = self._makeOne(credentials) + conn = self._make_one(credentials) self.assertEqual(credentials._create_scoped_calls, 1) self.assertIs(conn.credentials, credentials) self.assertIsNone(conn._http) def test_ctor_explicit_http(self): http = object() - conn = self._makeOne(http=http) + conn = self._make_one(http=http) self.assertIsNone(conn.credentials) self.assertIs(conn.http, http) def test_ctor_credentials_wo_create_scoped(self): credentials = object() - conn = self._makeOne(credentials) + conn = self._make_one(credentials) self.assertIs(conn.credentials, credentials) self.assertIsNone(conn._http) def test_http_w_existing(self): - conn = self._makeOne() + conn = self._make_one() conn._http = http = object() self.assertIs(conn.http, http) def test_http_wo_creds(self): import httplib2 - conn = self._makeOne() + conn = self._make_one() self.assertIsInstance(conn.http, httplib2.Http) def test_http_w_creds(self): @@ -63,7 +64,7 @@ def test_http_w_creds(self): authorized = object() credentials = _Credentials(authorized) - conn = self._makeOne(credentials) + conn = self._make_one(credentials) self.assertIs(conn.http, authorized) self.assertIsInstance(credentials._called_with, httplib2.Http) @@ -71,11 +72,11 @@ 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._makeOne() + conn = self._make_one() self.assertEqual(conn.USER_AGENT, expected_ua) def test__create_scoped_credentials_with_scoped_credentials(self): - klass = self._getTargetClass() + klass = self._get_target_class() scoped_creds = object() scope = 'google-specific-scope' credentials = _Credentials(scoped=scoped_creds) @@ -86,7 +87,7 @@ def test__create_scoped_credentials_with_scoped_credentials(self): self.assertEqual(credentials._scopes, [scope]) def test__create_scoped_credentials_without_scope_required(self): - klass = self._getTargetClass() + klass = self._get_target_class() credentials = _Credentials() result = klass._create_scoped_credentials(credentials, None) @@ -95,56 +96,57 @@ def test__create_scoped_credentials_without_scope_required(self): self.assertEqual(credentials._scopes, []) def test__create_scoped_credentials_non_scoped_credentials(self): - klass = self._getTargetClass() + klass = self._get_target_class() credentials = object() result = klass._create_scoped_credentials(credentials, None) self.assertIs(result, credentials) def test__create_scoped_credentials_no_credentials(self): - klass = self._getTargetClass() + klass = self._get_target_class() result = klass._create_scoped_credentials(None, None) self.assertIsNone(result) class TestJSONConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.connection import JSONConnection return JSONConnection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _makeMockOne(self, *args, **kw): - class MockConnection(self._getTargetClass()): + class MockConnection(self._get_target_class()): API_URL_TEMPLATE = '{api_base_url}/mock/{api_version}{path}' API_BASE_URL = 'http://mock' API_VERSION = 'vMOCK' return MockConnection(*args, **kw) def test_class_defaults(self): - klass = self._getTargetClass() + klass = self._get_target_class() self.assertIsNone(klass.API_URL_TEMPLATE) self.assertIsNone(klass.API_BASE_URL) self.assertIsNone(klass.API_VERSION) def test_ctor_defaults(self): - conn = self._makeOne() + conn = self._make_one() self.assertIsNone(conn.credentials) def test_ctor_explicit(self): credentials = _Credentials() - conn = self._makeOne(credentials) + conn = self._make_one(credentials) self.assertIs(conn.credentials, credentials) def test_http_w_existing(self): - conn = self._makeOne() + conn = self._make_one() conn._http = http = object() self.assertIs(conn.http, http) def test_http_wo_creds(self): import httplib2 - conn = self._makeOne() + conn = self._make_one() self.assertIsInstance(conn.http, httplib2.Http) def test_http_w_creds(self): @@ -152,7 +154,7 @@ def test_http_w_creds(self): authorized = object() credentials = _Credentials(authorized) - conn = self._makeOne(credentials) + conn = self._make_one(credentials) self.assertIs(conn.http, authorized) self.assertIsInstance(credentials._called_with, httplib2.Http) @@ -187,7 +189,7 @@ def test_build_api_url_w_extra_query_params(self): self.assertEqual(parms['bar'], 'baz') def test__make_request_no_data_no_content_type_no_headers(self): - conn = self._makeOne() + conn = self._make_one() URI = 'http://example.com/test' http = conn._http = _Http( {'status': '200', 'content-type': 'text/plain'}, @@ -208,7 +210,7 @@ def test__make_request_no_data_no_content_type_no_headers(self): self.assertEqual(http._called_with['headers'], expected_headers) def test__make_request_w_data_no_extra_headers(self): - conn = self._makeOne() + conn = self._make_one() URI = 'http://example.com/test' http = conn._http = _Http( {'status': '200', 'content-type': 'text/plain'}, @@ -227,7 +229,7 @@ def test__make_request_w_data_no_extra_headers(self): self.assertEqual(http._called_with['headers'], expected_headers) def test__make_request_w_extra_headers(self): - conn = self._makeOne() + conn = self._make_one() URI = 'http://example.com/test' http = conn._http = _Http( {'status': '200', 'content-type': 'text/plain'}, diff --git a/core/unit_tests/test_credentials.py b/core/unit_tests/test_credentials.py index 9fc10dcca4e8..ef583b35d98a 100644 --- a/core/unit_tests/test_credentials.py +++ b/core/unit_tests/test_credentials.py @@ -17,7 +17,7 @@ class Test_get_credentials(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud import credentials return credentials.get_credentials() @@ -27,7 +27,7 @@ def test_it(self): client = _Client() with _Monkey(MUT, client=client): - found = self._callFUT() + found = self._call_fut() self.assertIsInstance(found, _Credentials) self.assertIs(found, client._signed) self.assertTrue(client._get_app_default_called) @@ -35,7 +35,7 @@ def test_it(self): class Test_generate_signed_url(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.credentials import generate_signed_url return generate_signed_url(*args, **kwargs) @@ -61,11 +61,11 @@ def _get_signed_query_params(*args): } with _Monkey(MUT, _get_signed_query_params=_get_signed_query_params): - url = self._callFUT(CREDENTIALS, RESOURCE, 1000, - api_access_endpoint=ENDPOINT, - response_type=response_type, - response_disposition=response_disposition, - generation=generation) + url = self._call_fut(CREDENTIALS, RESOURCE, 1000, + api_access_endpoint=ENDPOINT, + response_type=response_type, + response_disposition=response_disposition, + generation=generation) scheme, netloc, path, qs, frag = urlsplit(url) self.assertEqual(scheme, 'http') @@ -115,7 +115,7 @@ def test_with_google_credentials(self): class Test__get_signed_query_params(unittest.TestCase): - def _callFUT(self, credentials, expiration, string_to_sign): + 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) @@ -129,8 +129,8 @@ def test_it(self): service_account_email=ACCOUNT_NAME) EXPIRATION = 100 STRING_TO_SIGN = 'dummy_signature' - result = self._callFUT(CREDENTIALS, EXPIRATION, - STRING_TO_SIGN) + result = self._call_fut(CREDENTIALS, EXPIRATION, + STRING_TO_SIGN) self.assertEqual(result, { 'GoogleAccessId': ACCOUNT_NAME, @@ -142,7 +142,7 @@ def test_it(self): class Test__get_expiration_seconds(unittest.TestCase): - def _callFUT(self, expiration): + def _call_fut(self, expiration): from google.cloud.credentials import _get_expiration_seconds return _get_expiration_seconds(expiration) @@ -151,11 +151,11 @@ def _utc_seconds(self, when): return int(calendar.timegm(when.timetuple())) def test_w_invalid(self): - self.assertRaises(TypeError, self._callFUT, object()) - self.assertRaises(TypeError, self._callFUT, None) + self.assertRaises(TypeError, self._call_fut, object()) + self.assertRaises(TypeError, self._call_fut, None) def test_w_int(self): - self.assertEqual(self._callFUT(123), 123) + self.assertEqual(self._call_fut(123), 123) def test_w_long(self): try: @@ -163,14 +163,14 @@ def test_w_long(self): except NameError: # pragma: NO COVER Py3K pass else: - self.assertEqual(self._callFUT(long(123)), 123) + self.assertEqual(self._call_fut(long(123)), 123) def test_w_naive_datetime(self): import datetime expiration_no_tz = datetime.datetime(2004, 8, 19, 0, 0, 0, 0) utc_seconds = self._utc_seconds(expiration_no_tz) - self.assertEqual(self._callFUT(expiration_no_tz), utc_seconds) + self.assertEqual(self._call_fut(expiration_no_tz), utc_seconds) def test_w_utc_datetime(self): import datetime @@ -178,7 +178,7 @@ def test_w_utc_datetime(self): expiration_utc = datetime.datetime(2004, 8, 19, 0, 0, 0, 0, UTC) utc_seconds = self._utc_seconds(expiration_utc) - self.assertEqual(self._callFUT(expiration_utc), utc_seconds) + self.assertEqual(self._call_fut(expiration_utc), utc_seconds) def test_w_other_zone_datetime(self): import datetime @@ -192,7 +192,7 @@ class CET(_UTC): expiration_other = datetime.datetime(2004, 8, 19, 0, 0, 0, 0, zone) utc_seconds = self._utc_seconds(expiration_other) cet_seconds = utc_seconds - (60 * 60) # CET one hour earlier than UTC - self.assertEqual(self._callFUT(expiration_other), cet_seconds) + self.assertEqual(self._call_fut(expiration_other), cet_seconds) def test_w_timedelta_seconds(self): import datetime @@ -204,7 +204,7 @@ def test_w_timedelta_seconds(self): expiration_as_delta = datetime.timedelta(seconds=10) with _Monkey(MUT, _NOW=lambda: dummy_utcnow): - result = self._callFUT(expiration_as_delta) + result = self._call_fut(expiration_as_delta) self.assertEqual(result, utc_seconds + 10) @@ -218,7 +218,7 @@ def test_w_timedelta_days(self): expiration_as_delta = datetime.timedelta(days=1) with _Monkey(MUT, _NOW=lambda: dummy_utcnow): - result = self._callFUT(expiration_as_delta) + result = self._call_fut(expiration_as_delta) self.assertEqual(result, utc_seconds + 86400) diff --git a/core/unit_tests/test_exceptions.py b/core/unit_tests/test_exceptions.py index 8460d6d8f1c4..36cdc3f3e360 100644 --- a/core/unit_tests/test_exceptions.py +++ b/core/unit_tests/test_exceptions.py @@ -17,15 +17,16 @@ class Test_GoogleCloudError(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.exceptions import GoogleCloudError return GoogleCloudError - def _makeOne(self, message, errors=()): - return self._getTargetClass()(message, errors=errors) + def _make_one(self, message, errors=()): + return self._get_target_class()(message, errors=errors) def test_ctor_defaults(self): - e = self._makeOne('Testing') + e = self._make_one('Testing') e.code = 600 self.assertEqual(str(e), '600 Testing') self.assertEqual(e.message, 'Testing') @@ -39,7 +40,7 @@ def test_ctor_explicit(self): 'message': 'Testing', 'reason': 'test', } - e = self._makeOne('Testing', [ERROR]) + e = self._make_one('Testing', [ERROR]) e.code = 600 self.assertEqual(str(e), '600 Testing') self.assertEqual(e.message, 'Testing') @@ -48,7 +49,7 @@ def test_ctor_explicit(self): class Test_make_exception(unittest.TestCase): - def _callFUT(self, response, content, error_info=None, use_json=True): + 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) @@ -57,7 +58,7 @@ 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._callFUT(response, content) + exception = self._call_fut(response, content) self.assertIsInstance(exception, NotFound) self.assertEqual(exception.message, 'Not Found') self.assertEqual(list(exception.errors), []) @@ -72,7 +73,7 @@ def test_hit_w_content_as_unicode(self): response = _Response(404) content = u'{"error": {"message": "%s" }}' % (error_message,) - exception = self._callFUT(response, content) + exception = self._call_fut(response, content) if six.PY2: self.assertEqual(str(exception), _to_bytes(expected, encoding='utf-8')) @@ -93,7 +94,7 @@ def test_hit_w_content_as_unicode_as_py3(self): with _Monkey(six, PY2=False): response = _Response(404) content = u'{"error": {"message": "%s" }}' % (error_message,) - exception = self._callFUT(response, content) + exception = self._call_fut(response, content) self.assertIsInstance(exception, NotFound) self.assertEqual(exception.message, error_message) @@ -111,7 +112,7 @@ def test_miss_w_content_as_dict(self): } response = _Response(600) content = {"error": {"message": "Unknown Error", "errors": [ERROR]}} - exception = self._callFUT(response, content) + exception = self._call_fut(response, content) self.assertIsInstance(exception, GoogleCloudError) self.assertEqual(exception.message, 'Unknown Error') self.assertEqual(list(exception.errors), [ERROR]) @@ -120,7 +121,7 @@ def test_html_when_json_expected(self): from google.cloud.exceptions import NotFound response = _Response(NotFound.code) content = '404 Not Found' - exception = self._callFUT(response, content, use_json=True) + exception = self._call_fut(response, content, use_json=True) self.assertIsInstance(exception, NotFound) self.assertEqual(exception.message, content) self.assertEqual(list(exception.errors), []) @@ -130,7 +131,7 @@ def test_without_use_json(self): content = u'error-content' response = _Response(TooManyRequests.code) - exception = self._callFUT(response, content, use_json=False) + exception = self._call_fut(response, content, use_json=False) self.assertIsInstance(exception, TooManyRequests) self.assertEqual(exception.message, content) diff --git a/core/unit_tests/test_iterator.py b/core/unit_tests/test_iterator.py index 68b2f65aadc0..b66deae9fdc8 100644 --- a/core/unit_tests/test_iterator.py +++ b/core/unit_tests/test_iterator.py @@ -17,47 +17,48 @@ class Test__do_nothing_page_start(unittest.TestCase): - def _callFUT(self, iterator, page, response): + 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): - result = self._callFUT(None, None, None) + result = self._call_fut(None, None, None) self.assertIsNone(result) class TestPage(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.iterator import Page return Page - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): parent = object() item_to_value = object() - page = self._makeOne(parent, (1, 2, 3), item_to_value) + page = self._make_one(parent, (1, 2, 3), item_to_value) self.assertIs(page._parent, parent) self.assertEqual(page._num_items, 3) self.assertEqual(page._remaining, 3) self.assertIs(page._item_to_value, item_to_value) def test_num_items_property(self): - page = self._makeOne(None, (), None) + page = self._make_one(None, (), None) num_items = 42 page._num_items = num_items self.assertEqual(page.num_items, num_items) def test_remaining_property(self): - page = self._makeOne(None, (), None) + page = self._make_one(None, (), None) remaining = 1337 page._remaining = remaining self.assertEqual(page.remaining, remaining) def test___iter__(self): - page = self._makeOne(None, (), None) + page = self._make_one(None, (), None) self.assertIs(iter(page), page) def test_iterator_calls__item_to_value(self): @@ -72,8 +73,8 @@ def item_to_value(self, item): return item parent = Parent() - page = self._makeOne(parent, (10, 11, 12), - Parent.item_to_value) + page = self._make_one(parent, (10, 11, 12), + Parent.item_to_value) page._remaining = 100 self.assertEqual(parent.calls, 0) @@ -91,12 +92,13 @@ def item_to_value(self, item): class TestIterator(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.iterator import Iterator return Iterator - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): connection = _Connection() @@ -104,8 +106,8 @@ def test_constructor(self): item_to_value = object() token = 'ab13nceor03' max_results = 1337 - iterator = self._makeOne(client, item_to_value, page_token=token, - max_results=max_results) + iterator = self._make_one(client, item_to_value, page_token=token, + max_results=max_results) self.assertFalse(iterator._started) self.assertIs(iterator.client, client) @@ -117,7 +119,7 @@ def test_constructor(self): self.assertEqual(iterator.num_results, 0) def test_pages_property(self): - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertFalse(iterator._started) mock_iter = object() incremented = [] @@ -135,7 +137,7 @@ def page_iter(increment): def test_pages_property_started(self): import types - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertIsInstance(iterator.pages, types.GeneratorType) # Make sure we cannot restart. with self.assertRaises(ValueError): @@ -144,7 +146,7 @@ def test_pages_property_started(self): def test_pages_property_items_started(self): import types - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertIsInstance(iter(iterator), types.GeneratorType) with self.assertRaises(ValueError): getattr(iterator, 'pages') @@ -168,7 +170,7 @@ def test__items_iter(self): page1 = Page(parent, (item1, item2), self._do_nothing) page2 = Page(parent, (item3,), self._do_nothing) - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) # Fake the page iterator on the object. incremented = [] @@ -196,7 +198,7 @@ def page_iter(increment): self.assertEqual(incremented, [False]) def test___iter__(self): - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertFalse(iterator._started) incremented = [] @@ -212,7 +214,7 @@ def page_iter(increment): def test___iter___started(self): import types - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertIsInstance(iter(iterator), types.GeneratorType) with self.assertRaises(ValueError): iter(iterator) @@ -220,25 +222,26 @@ def test___iter___started(self): def test___iter___pages_started(self): import types - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) self.assertIsInstance(iterator.pages, types.GeneratorType) with self.assertRaises(ValueError): iter(iterator) def test__next_page_virtual(self): - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) with self.assertRaises(NotImplementedError): iterator._next_page() class TestHTTPIterator(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.iterator import HTTPIterator return HTTPIterator - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): from google.cloud.iterator import _do_nothing_page_start @@ -246,7 +249,7 @@ def test_constructor(self): connection = _Connection() client = _Client(connection) path = '/foo' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) self.assertFalse(iterator._started) self.assertIs(iterator.client, client) self.assertEqual(iterator.path, path) @@ -266,7 +269,7 @@ def test_constructor_w_extra_param_collision(self): path = '/foo' extra_params = {'pageToken': 'val'} with self.assertRaises(ValueError): - self._makeOne(client, path, None, extra_params=extra_params) + self._make_one(client, path, None, extra_params=extra_params) def test_pages_iter_empty_then_another(self): import six @@ -274,7 +277,7 @@ def test_pages_iter_empty_then_another(self): from google.cloud import iterator as MUT items_key = 'its-key' - iterator = self._makeOne(None, None, None, items_key=items_key) + iterator = self._make_one(None, None, None, items_key=items_key) # Fake the next page class. fake_page = MUT.Page(None, (), None) page_args = [] @@ -309,8 +312,8 @@ def item_to_value(iterator, item): # pylint: disable=unused-argument connection = _Connection( {'items': [{'name': key1}, {'name': key2}]}) client = _Client(connection) - iterator = self._makeOne(client, path=path, - item_to_value=item_to_value) + iterator = self._make_one(client, path=path, + item_to_value=item_to_value) self.assertEqual(iterator.num_results, 0) items_iter = iter(iterator) @@ -334,14 +337,14 @@ def test__has_next_page_new(self): connection = _Connection() client = _Client(connection) path = '/foo' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) self.assertTrue(iterator._has_next_page()) def test__has_next_page_w_number_no_token(self): connection = _Connection() client = _Client(connection) path = '/foo' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) iterator.page_number = 1 self.assertFalse(iterator._has_next_page()) @@ -350,20 +353,20 @@ def test__has_next_page_w_number_w_token(self): client = _Client(connection) path = '/foo' token = 'token' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) iterator.page_number = 1 iterator.next_page_token = token self.assertTrue(iterator._has_next_page()) def test__has_next_page_w_max_results_not_done(self): - iterator = self._makeOne(None, None, None, max_results=3, - page_token='definitely-not-none') + iterator = self._make_one(None, None, None, max_results=3, + page_token='definitely-not-none') iterator.page_number = 1 self.assertLess(iterator.num_results, iterator.max_results) self.assertTrue(iterator._has_next_page()) def test__has_next_page_w_max_results_done(self): - iterator = self._makeOne(None, None, None, max_results=3) + iterator = self._make_one(None, None, None, max_results=3) iterator.page_number = 1 iterator.num_results = iterator.max_results self.assertFalse(iterator._has_next_page()) @@ -372,7 +375,7 @@ def test__get_query_params_no_token(self): connection = _Connection() client = _Client(connection) path = '/foo' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) self.assertEqual(iterator._get_query_params(), {}) def test__get_query_params_w_token(self): @@ -380,7 +383,7 @@ def test__get_query_params_w_token(self): client = _Client(connection) path = '/foo' token = 'token' - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) iterator.next_page_token = token self.assertEqual(iterator._get_query_params(), {'pageToken': token}) @@ -390,8 +393,8 @@ def test__get_query_params_w_max_results(self): client = _Client(connection) path = '/foo' max_results = 3 - iterator = self._makeOne(client, path, None, - max_results=max_results) + iterator = self._make_one(client, path, None, + max_results=max_results) iterator.num_results = 1 local_max = max_results - iterator.num_results self.assertEqual(iterator._get_query_params(), @@ -402,8 +405,8 @@ def test__get_query_params_extra_params(self): client = _Client(connection) path = '/foo' extra_params = {'key': 'val'} - iterator = self._makeOne(client, path, None, - extra_params=extra_params) + iterator = self._make_one(client, path, None, + extra_params=extra_params) self.assertEqual(iterator._get_query_params(), extra_params) def test__get_query_params_w_token_and_extra_params(self): @@ -412,8 +415,8 @@ def test__get_query_params_w_token_and_extra_params(self): path = '/foo' token = 'token' extra_params = {'key': 'val'} - iterator = self._makeOne(client, path, None, - extra_params=extra_params) + iterator = self._make_one(client, path, None, + extra_params=extra_params) iterator.next_page_token = token expected_query = extra_params.copy() @@ -428,7 +431,7 @@ def test__get_next_page_response_new_no_token_in_response(self): connection = _Connection({'items': [{'name': key1}, {'name': key2}], 'nextPageToken': token}) client = _Client(connection) - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) response = iterator._get_next_page_response() self.assertEqual(response['items'], [{'name': key1}, {'name': key2}]) kw, = connection._requested @@ -441,7 +444,7 @@ def test__get_next_page_response_with_post(self): returned = {'green': 'eggs', 'ham': 55} connection = _Connection(returned) client = _Client(connection) - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) iterator._HTTP_METHOD = 'POST' response = iterator._get_next_page_response() self.assertEqual(response, returned) @@ -457,7 +460,7 @@ def test__get_next_page_response_with_post(self): def test__get_next_page_bad_http_method(self): path = '/foo' client = _Client(None) - iterator = self._makeOne(client, path, None) + iterator = self._make_one(client, path, None) iterator._HTTP_METHOD = 'NOT-A-VERB' with self.assertRaises(ValueError): iterator._get_next_page_response() @@ -465,12 +468,13 @@ def test__get_next_page_bad_http_method(self): class TestGAXIterator(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.iterator import GAXIterator return GAXIterator - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): client = _Client(None) @@ -478,8 +482,8 @@ def test_constructor(self): page_iter = SimpleIter(token) item_to_value = object() max_results = 1337 - iterator = self._makeOne(client, page_iter, item_to_value, - max_results=max_results) + iterator = self._make_one(client, page_iter, item_to_value, + max_results=max_results) self.assertFalse(iterator._started) self.assertIs(iterator.client, client) @@ -504,7 +508,7 @@ def test__next_page(self): page_token = '2sde98ds2s0hh' page_iter = _GAXPageIterator(page_items, page_token=page_token) # Wrap the GAX iterator. - iterator = self._makeOne(None, page_iter, self._do_nothing) + iterator = self._make_one(None, page_iter, self._do_nothing) page = iterator._next_page() # First check the page token. @@ -521,7 +525,7 @@ def test__next_page_empty(self): # Make a mock ``google.gax.PageIterator`` page_iter = _GAXPageIterator() # Wrap the GAX iterator. - iterator = self._makeOne(None, page_iter, self._do_nothing) + iterator = self._make_one(None, page_iter, self._do_nothing) page = iterator._next_page() self.assertIsNone(page) @@ -541,7 +545,7 @@ def test_iterate(self): page1 = (item1,) page2 = (item2, item3) page_iter = _GAXPageIterator(page1, page2, page_token=token1) - iterator = self._makeOne(None, page_iter, self._do_nothing) + iterator = self._make_one(None, page_iter, self._do_nothing) self.assertEqual(iterator.num_results, 0) diff --git a/core/unit_tests/test_operation.py b/core/unit_tests/test_operation.py index 7c204278e6b3..2f59f4a5729b 100644 --- a/core/unit_tests/test_operation.py +++ b/core/unit_tests/test_operation.py @@ -17,7 +17,7 @@ class Test__compute_type_url(unittest.TestCase): - def _callFUT(self, klass, prefix=None): + def _call_fut(self, klass, prefix=None): from google.cloud.operation import _compute_type_url if prefix is None: return _compute_type_url(klass) @@ -27,7 +27,7 @@ def test_wo_prefix(self): from google.protobuf.struct_pb2 import Struct from google.cloud.operation import _GOOGLE_APIS_PREFIX - type_url = self._callFUT(Struct) + type_url = self._call_fut(Struct) self.assertEqual( type_url, @@ -37,7 +37,7 @@ def test_w_prefix(self): from google.protobuf.struct_pb2 import Struct PREFIX = 'test.google-cloud-python.com' - type_url = self._callFUT(Struct, PREFIX) + type_url = self._call_fut(Struct, PREFIX) self.assertEqual( type_url, @@ -46,7 +46,7 @@ def test_w_prefix(self): class Test_register_type(unittest.TestCase): - def _callFUT(self, klass, type_url=None): + def _call_fut(self, klass, type_url=None): from google.cloud.operation import register_type register_type(klass, type_url=type_url) @@ -59,7 +59,7 @@ def test_explicit(self): type_url_map = {} with _Monkey(MUT, _TYPE_URL_MAP=type_url_map): - self._callFUT(klass, type_url) + self._call_fut(klass, type_url) self.assertEqual(type_url_map, {type_url: klass}) @@ -70,7 +70,7 @@ def test_default(self): type_url_map = {} with _Monkey(MUT, _TYPE_URL_MAP=type_url_map): - self._callFUT(Struct) + self._call_fut(Struct) type_url = MUT._compute_type_url(Struct) self.assertEqual(type_url_map, {type_url: Struct}) @@ -84,7 +84,7 @@ def test_w_same_class(self): type_url_map = {type_url: klass} with _Monkey(MUT, _TYPE_URL_MAP=type_url_map): - self._callFUT(klass, type_url) + self._call_fut(klass, type_url) self.assertEqual(type_url_map, {type_url: klass}) @@ -98,7 +98,7 @@ def test_w_conflict(self): with _Monkey(MUT, _TYPE_URL_MAP=type_url_map): with self.assertRaises(ValueError): - self._callFUT(klass, type_url) + self._call_fut(klass, type_url) self.assertEqual(type_url_map, {type_url: other}) @@ -107,16 +107,17 @@ class TestOperation(unittest.TestCase): OPERATION_NAME = 'operations/projects/foo/instances/bar/operations/123' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.operation import Operation return Operation - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): client = _Client() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client) self.assertEqual(operation.name, self.OPERATION_NAME) self.assertIs(operation.client, client) @@ -129,7 +130,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): client = _Client() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client, foo='bar') self.assertEqual(operation.name, self.OPERATION_NAME) @@ -145,7 +146,7 @@ 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._getTargetClass() + klass = self._get_target_class() operation = klass.from_pb(operation_pb, client) @@ -168,7 +169,7 @@ def test_from_pb_w_unknown_metadata(self): metadata_pb = Any(type_url=type_url, value=meta.SerializeToString()) operation_pb = operations_pb2.Operation( name=self.OPERATION_NAME, metadata=metadata_pb) - klass = self._getTargetClass() + klass = self._get_target_class() with _Monkey(MUT, _TYPE_URL_MAP={type_url: Struct}): operation = klass.from_pb(operation_pb, client) @@ -194,7 +195,7 @@ def test_from_pb_w_metadata_and_kwargs(self): metadata_pb = Any(type_url=type_url, value=meta.SerializeToString()) operation_pb = operations_pb2.Operation( name=self.OPERATION_NAME, metadata=metadata_pb) - klass = self._getTargetClass() + klass = self._get_target_class() with _Monkey(MUT, _TYPE_URL_MAP=type_url_map): operation = klass.from_pb(operation_pb, client, baz='qux') @@ -219,7 +220,7 @@ def test_from_dict(self): } client = _Client() - klass = self._getTargetClass() + klass = self._get_target_class() with _Monkey(MUT, _TYPE_URL_MAP={type_url: Struct}): operation = klass.from_dict(api_response, client) @@ -238,7 +239,7 @@ def test_from_dict(self): def test_complete_property(self): client = _Client() - operation = self._makeOne(self.OPERATION_NAME, client) + operation = self._make_one(self.OPERATION_NAME, client) self.assertFalse(operation.complete) operation._complete = True self.assertTrue(operation.complete) @@ -247,7 +248,7 @@ def test_complete_property(self): def test_poll_already_complete(self): client = _Client() - operation = self._makeOne(self.OPERATION_NAME, client) + operation = self._make_one(self.OPERATION_NAME, client) operation._complete = True with self.assertRaises(ValueError): @@ -260,7 +261,7 @@ def test_poll_false(self): client = _Client() stub = client._operations_stub stub._get_operation_response = response_pb - operation = self._makeOne(self.OPERATION_NAME, client) + operation = self._make_one(self.OPERATION_NAME, client) self.assertFalse(operation.poll()) @@ -275,7 +276,7 @@ def test_poll_true(self): client = _Client() stub = client._operations_stub stub._get_operation_response = response_pb - operation = self._makeOne(self.OPERATION_NAME, client) + operation = self._make_one(self.OPERATION_NAME, client) self.assertTrue(operation.poll()) @@ -300,7 +301,7 @@ def test_poll_http(self): } connection = _Connection(api_response) client = _Client(connection) - operation = self._makeOne(name, client) + operation = self._make_one(name, client) operation._from_grpc = False with _Monkey(MUT, _TYPE_URL_MAP={type_url: Struct}): @@ -315,7 +316,7 @@ def test_poll_http(self): def test__update_state_done(self): from google.longrunning import operations_pb2 - operation = self._makeOne(None, None) + operation = self._make_one(None, None) self.assertFalse(operation.complete) operation_pb = operations_pb2.Operation(done=True) operation._update_state(operation_pb) @@ -328,7 +329,7 @@ def test__update_state_metadata(self): from google.cloud._testing import _Monkey from google.cloud import operation as MUT - operation = self._makeOne(None, None) + operation = self._make_one(None, None) self.assertIsNone(operation.metadata) val_pb = Value(number_value=1337) @@ -346,7 +347,7 @@ def test__update_state_error(self): from google.rpc.status_pb2 import Status from google.cloud._testing import _Monkey - operation = self._makeOne(None, None) + operation = self._make_one(None, None) self.assertIsNone(operation.error) self.assertIsNone(operation.response) @@ -364,7 +365,7 @@ def test__update_state_response(self): from google.cloud._testing import _Monkey from google.cloud import operation as MUT - operation = self._makeOne(None, None) + operation = self._make_one(None, None) self.assertIsNone(operation.error) self.assertIsNone(operation.response) @@ -383,7 +384,7 @@ def test__update_state_response(self): def test__update_state_no_result(self): from google.longrunning import operations_pb2 - operation = self._makeOne(None, None) + operation = self._make_one(None, None) self.assertIsNone(operation.error) self.assertIsNone(operation.response) diff --git a/datastore/unit_tests/test__http.py b/datastore/unit_tests/test__http.py index c7f35c3b4772..e96eed96a032 100644 --- a/datastore/unit_tests/test__http.py +++ b/datastore/unit_tests/test__http.py @@ -19,12 +19,13 @@ class Test_DatastoreAPIOverHttp(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore._http import _DatastoreAPIOverHttp return _DatastoreAPIOverHttp - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test__rpc(self): class ReqPB(object): @@ -46,7 +47,7 @@ def FromString(cls, pb): METHOD = 'METHOD' URI = 'http://api-url' conn = _Connection(URI) - datastore_api = self._makeOne(conn) + datastore_api = self._make_one(conn) http = conn.http = Http({'status': '200'}, 'CONTENT') response = datastore_api._rpc(PROJECT, METHOD, ReqPB(), RspPB) self.assertIsInstance(response, RspPB) @@ -68,7 +69,7 @@ def test__request_w_200(self): DATA = b'DATA' URI = 'http://api-url' conn = _Connection(URI) - datastore_api = self._makeOne(conn) + datastore_api = self._make_one(conn) http = conn.http = Http({'status': '200'}, 'CONTENT') self.assertEqual(datastore_api._request(PROJECT, METHOD, DATA), 'CONTENT') @@ -96,7 +97,7 @@ def test__request_not_200(self): DATA = 'DATA' URI = 'http://api-url' conn = _Connection(URI) - datastore_api = self._makeOne(conn) + datastore_api = self._make_one(conn) conn.http = Http({'status': '400'}, error.SerializeToString()) with self.assertRaises(BadRequest) as exc: datastore_api._request(PROJECT, METHOD, DATA) @@ -109,7 +110,7 @@ def test__request_not_200(self): @unittest.skipUnless(_HAVE_GRPC, 'No gRPC') class Test__grpc_catch_rendezvous(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud.datastore._http import _grpc_catch_rendezvous return _grpc_catch_rendezvous() @@ -122,7 +123,7 @@ def _fake_method(exc, result=None): def test_success(self): expected = object() - with self._callFUT(): + with self._call_fut(): result = self._fake_method(None, expected) self.assertIs(result, expected) @@ -136,7 +137,7 @@ def test_failure_aborted(self): exc_state = _RPCState((), None, None, StatusCode.ABORTED, details) exc = GrpcRendezvous(exc_state, None, None, None) with self.assertRaises(Conflict): - with self._callFUT(): + with self._call_fut(): self._fake_method(exc) def test_failure_invalid_argument(self): @@ -151,7 +152,7 @@ def test_failure_invalid_argument(self): StatusCode.INVALID_ARGUMENT, details) exc = GrpcRendezvous(exc_state, None, None, None) with self.assertRaises(BadRequest): - with self._callFUT(): + with self._call_fut(): self._fake_method(exc) def test_failure_cancelled(self): @@ -162,23 +163,24 @@ def test_failure_cancelled(self): exc_state = _RPCState((), None, None, StatusCode.CANCELLED, None) exc = GrpcRendezvous(exc_state, None, None, None) with self.assertRaises(GrpcRendezvous): - with self._callFUT(): + with self._call_fut(): self._fake_method(exc) def test_commit_failure_non_grpc_err(self): exc = RuntimeError('Not a gRPC error') with self.assertRaises(RuntimeError): - with self._callFUT(): + with self._call_fut(): self._fake_method(exc) class Test_DatastoreAPIOverGRPC(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore._http import _DatastoreAPIOverGRPC return _DatastoreAPIOverGRPC - def _makeOne(self, stub, connection=None, secure=True, mock_args=None): + def _make_one(self, stub, connection=None, secure=True, mock_args=None): from google.cloud._testing import _Monkey from google.cloud.datastore import _http as MUT @@ -199,7 +201,7 @@ def mock_make_stub(*args): else: to_monkey = {'make_insecure_stub': mock_make_stub} with _Monkey(MUT, **to_monkey): - return self._getTargetClass()(connection, secure) + return self._get_target_class()(connection, secure) def test_constructor(self): from google.cloud.datastore import _http as MUT @@ -210,8 +212,8 @@ def test_constructor(self): stub = _GRPCStub() mock_args = [] - datastore_api = self._makeOne(stub, connection=conn, - mock_args=mock_args) + datastore_api = self._make_one(stub, connection=conn, + mock_args=mock_args) self.assertIs(datastore_api._stub, stub) self.assertEqual(mock_args, [( @@ -230,9 +232,9 @@ def test_constructor_insecure(self): stub = _GRPCStub() mock_args = [] - datastore_api = self._makeOne(stub, connection=conn, - secure=False, - mock_args=mock_args) + datastore_api = self._make_one(stub, connection=conn, + secure=False, + mock_args=mock_args) self.assertIs(datastore_api._stub, stub) self.assertEqual(mock_args, [( @@ -243,7 +245,7 @@ def test_constructor_insecure(self): def test_lookup(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -256,7 +258,7 @@ def test_lookup(self): def test_run_query(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -268,7 +270,7 @@ def test_run_query(self): def _run_query_failure_helper(self, exc, err_class): stub = _GRPCStub(side_effect=exc) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -296,7 +298,7 @@ def test_run_query_invalid_argument(self): def test_begin_transaction(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -310,7 +312,7 @@ def test_begin_transaction(self): def test_commit_success(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -323,7 +325,7 @@ def test_commit_success(self): def test_rollback(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -336,7 +338,7 @@ def test_rollback(self): def test_allocate_ids(self): return_val = object() stub = _GRPCStub(return_val) - datastore_api = self._makeOne(stub=stub) + datastore_api = self._make_one(stub=stub) request_pb = _RequestPB() project = 'PROJECT' @@ -350,7 +352,8 @@ def test_allocate_ids(self): class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore._http import Connection return Connection @@ -368,11 +371,11 @@ def _make_query_pb(self, kind): pb.kind.add().name = kind return pb - def _makeOne(self, credentials=None, http=None, use_grpc=False): + def _make_one(self, credentials=None, http=None, use_grpc=False): from google.cloud._testing import _Monkey from google.cloud.datastore import _http as MUT with _Monkey(MUT, _USE_GRPC=use_grpc): - return self._getTargetClass()(credentials=credentials, http=http) + return self._get_target_class()(credentials=credentials, http=http) def _verifyProtobufCall(self, called_with, URI, conn): self.assertEqual(called_with['uri'], URI) @@ -383,8 +386,8 @@ def _verifyProtobufCall(self, called_with, URI, conn): conn.USER_AGENT) def test_default_url(self): - klass = self._getTargetClass() - conn = self._makeOne() + klass = self._get_target_class() + conn = self._make_one() self.assertEqual(conn.api_base_url, klass.API_BASE_URL) def test_custom_url_from_env(self): @@ -397,13 +400,13 @@ def test_custom_url_from_env(self): fake_environ = {GCD_HOST: HOST} with _Monkey(os, environ=fake_environ): - conn = self._makeOne() + conn = self._make_one() self.assertNotEqual(conn.api_base_url, API_BASE_URL) self.assertEqual(conn.api_base_url, 'http://' + HOST) def test_ctor_defaults(self): - conn = self._makeOne() + conn = self._make_one() self.assertIsNone(conn.credentials) def test_ctor_without_grpc(self): @@ -418,7 +421,7 @@ def mock_api(connection): return return_val with _Monkey(MUT, _DatastoreAPIOverHttp=mock_api): - conn = self._makeOne(use_grpc=False) + conn = self._make_one(use_grpc=False) self.assertIsNone(conn.credentials) self.assertIs(conn._datastore_api, return_val) @@ -436,7 +439,7 @@ def mock_api(connection, secure): return return_val with _Monkey(MUT, _DatastoreAPIOverGRPC=mock_api): - conn = self._makeOne(use_grpc=True) + conn = self._make_one(use_grpc=True) self.assertIsNone(conn.credentials) self.assertIs(conn._datastore_api, return_val) @@ -449,18 +452,18 @@ def create_scoped_required(self): return False creds = Creds() - conn = self._makeOne(creds) + conn = self._make_one(creds) self.assertIs(conn.credentials, creds) def test_http_w_existing(self): - conn = self._makeOne() + conn = self._make_one() conn._http = http = object() self.assertIs(conn.http, http) def test_http_wo_creds(self): import httplib2 - conn = self._makeOne() + conn = self._make_one() self.assertIsInstance(conn.http, httplib2.Http) def test_http_w_creds(self): @@ -478,14 +481,14 @@ def create_scoped_required(self): return False creds = Creds() - conn = self._makeOne(creds) + conn = self._make_one(creds) self.assertIs(conn.http, authorized) self.assertIsInstance(creds._called_with, httplib2.Http) def test_build_api_url_w_default_base_version(self): PROJECT = 'PROJECT' METHOD = 'METHOD' - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -499,7 +502,7 @@ def test_build_api_url_w_explicit_base_version(self): VER = '3.1415926' PROJECT = 'PROJECT' METHOD = 'METHOD' - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ BASE, VER, @@ -515,7 +518,7 @@ def test_lookup_single_key_empty_response(self): PROJECT = 'PROJECT' key_pb = self._make_key_pb(PROJECT) rsp_pb = datastore_pb2.LookupResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -542,7 +545,7 @@ def test_lookup_single_key_empty_response_w_eventual(self): PROJECT = 'PROJECT' key_pb = self._make_key_pb(PROJECT) rsp_pb = datastore_pb2.LookupResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -571,7 +574,7 @@ def test_lookup_single_key_empty_response_w_eventual_and_transaction(self): PROJECT = 'PROJECT' TRANSACTION = b'TRANSACTION' key_pb = self._make_key_pb(PROJECT) - conn = self._makeOne() + conn = self._make_one() self.assertRaises(ValueError, conn.lookup, PROJECT, key_pb, eventual=True, transaction_id=TRANSACTION) @@ -582,7 +585,7 @@ def test_lookup_single_key_empty_response_w_transaction(self): TRANSACTION = b'TRANSACTION' key_pb = self._make_key_pb(PROJECT) rsp_pb = datastore_pb2.LookupResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -615,7 +618,7 @@ def test_lookup_single_key_nonempty_response(self): entity = entity_pb2.Entity() entity.key.CopyFrom(key_pb) rsp_pb.found.add(entity=entity) - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -644,7 +647,7 @@ def test_lookup_multiple_keys_empty_response(self): key_pb1 = self._make_key_pb(PROJECT) key_pb2 = self._make_key_pb(PROJECT, id_=2345) rsp_pb = datastore_pb2.LookupResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -677,7 +680,7 @@ def test_lookup_multiple_keys_w_missing(self): er_1.entity.key.CopyFrom(key_pb1) er_2 = rsp_pb.missing.add() er_2.entity.key.CopyFrom(key_pb2) - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -709,7 +712,7 @@ def test_lookup_multiple_keys_w_deferred(self): rsp_pb = datastore_pb2.LookupResponse() rsp_pb.deferred.add().CopyFrom(key_pb1) rsp_pb.deferred.add().CopyFrom(key_pb2) - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -749,7 +752,7 @@ def test_run_query_w_eventual_no_transaction(self): no_more = query_pb2.QueryResultBatch.NO_MORE_RESULTS rsp_pb.batch.more_results = no_more rsp_pb.batch.entity_result_type = query_pb2.EntityResult.FULL - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -788,7 +791,7 @@ def test_run_query_wo_eventual_w_transaction(self): no_more = query_pb2.QueryResultBatch.NO_MORE_RESULTS rsp_pb.batch.more_results = no_more rsp_pb.batch.entity_result_type = query_pb2.EntityResult.FULL - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -828,7 +831,7 @@ def test_run_query_w_eventual_and_transaction(self): no_more = query_pb2.QueryResultBatch.NO_MORE_RESULTS rsp_pb.batch.more_results = no_more rsp_pb.batch.entity_result_type = query_pb2.EntityResult.FULL - conn = self._makeOne() + conn = self._make_one() self.assertRaises(ValueError, conn.run_query, PROJECT, q_pb, eventual=True, transaction_id=TRANSACTION) @@ -845,7 +848,7 @@ def test_run_query_wo_namespace_empty_result(self): no_more = query_pb2.QueryResultBatch.NO_MORE_RESULTS rsp_pb.batch.more_results = no_more rsp_pb.batch.entity_result_type = query_pb2.EntityResult.FULL - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -878,7 +881,7 @@ def test_run_query_w_namespace_nonempty_result(self): rsp_pb.batch.entity_results.add(entity=entity) rsp_pb.batch.entity_result_type = 1 # FULL rsp_pb.batch.more_results = 3 # NO_MORE_RESULTS - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -903,7 +906,7 @@ def test_begin_transaction(self): TRANSACTION = b'TRANSACTION' rsp_pb = datastore_pb2.BeginTransactionResponse() rsp_pb.transaction = TRANSACTION - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -933,7 +936,7 @@ def test_commit_wo_transaction(self): insert.key.CopyFrom(key_pb) value_pb = _new_value_pb(insert, 'foo') value_pb.string_value = u'Foo' - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -979,7 +982,7 @@ def test_commit_w_transaction(self): insert.key.CopyFrom(key_pb) value_pb = _new_value_pb(insert, 'foo') value_pb.string_value = u'Foo' - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -1016,7 +1019,7 @@ def test_rollback_ok(self): TRANSACTION = b'xact' rsp_pb = datastore_pb2.RollbackResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -1037,7 +1040,7 @@ def test_allocate_ids_empty(self): PROJECT = 'PROJECT' rsp_pb = datastore_pb2.AllocateIdsResponse() - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -1068,7 +1071,7 @@ def test_allocate_ids_non_empty(self): rsp_pb = datastore_pb2.AllocateIdsResponse() rsp_pb.keys.add().CopyFrom(after_key_pbs[0]) rsp_pb.keys.add().CopyFrom(after_key_pbs[1]) - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.api_base_url, conn.API_VERSION, @@ -1090,7 +1093,7 @@ def test_allocate_ids_non_empty(self): class Test__parse_commit_response(unittest.TestCase): - def _callFUT(self, commit_response_pb): + def _call_fut(self, commit_response_pb): from google.cloud.datastore._http import _parse_commit_response return _parse_commit_response(commit_response_pb) @@ -1123,7 +1126,7 @@ def test_it(self): ], index_updates=index_updates, ) - result = self._callFUT(response) + result = self._call_fut(response) self.assertEqual(result, (index_updates, keys)) diff --git a/datastore/unit_tests/test_batch.py b/datastore/unit_tests/test_batch.py index e7ce9dd609b0..737668af02b4 100644 --- a/datastore/unit_tests/test_batch.py +++ b/datastore/unit_tests/test_batch.py @@ -17,13 +17,14 @@ class TestBatch(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.batch import Batch return Batch - def _makeOne(self, client): - return self._getTargetClass()(client) + def _make_one(self, client): + return self._get_target_class()(client) def test_ctor(self): from google.cloud.datastore._generated import datastore_pb2 @@ -31,7 +32,7 @@ def test_ctor(self): _NAMESPACE = 'NAMESPACE' connection = _Connection() client = _Client(_PROJECT, connection, _NAMESPACE) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertEqual(batch.project, _PROJECT) self.assertEqual(batch.connection, connection) @@ -47,8 +48,8 @@ def test_current(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch1 = self._makeOne(client) - batch2 = self._makeOne(client) + batch1 = self._make_one(client) + batch2 = self._make_one(client) self.assertIsNone(batch1.current()) self.assertIsNone(batch2.current()) with batch1: @@ -66,7 +67,7 @@ def test_put_entity_wo_key(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) batch.begin() self.assertRaises(ValueError, batch.put, _Entity()) @@ -75,7 +76,7 @@ def test_put_entity_wrong_status(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) entity = _Entity() entity.key = _Key('OTHER') @@ -86,7 +87,7 @@ def test_put_entity_w_key_wrong_project(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) entity = _Entity() entity.key = _Key('OTHER') @@ -98,7 +99,7 @@ def test_put_entity_w_partial_key(self): _PROPERTIES = {'foo': 'bar'} connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) entity = _Entity(_PROPERTIES) key = entity.key = _Key(_PROJECT) key._id = None @@ -122,7 +123,7 @@ def test_put_entity_w_completed_key(self): } connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) entity = _Entity(_PROPERTIES) entity.exclude_from_indexes = ('baz', 'spam') key = entity.key = _Key(_PROJECT) @@ -148,7 +149,7 @@ def test_delete_wrong_status(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) key = _Key(_PROJECT) key._id = None @@ -159,7 +160,7 @@ def test_delete_w_partial_key(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) key = _Key(_PROJECT) key._id = None @@ -170,7 +171,7 @@ def test_delete_w_key_wrong_project(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) key = _Key('OTHER') batch.begin() @@ -180,7 +181,7 @@ def test_delete_w_completed_key(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) key = _Key(_PROJECT) batch.begin() @@ -192,7 +193,7 @@ def test_delete_w_completed_key(self): def test_begin(self): _PROJECT = 'PROJECT' client = _Client(_PROJECT, None) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertEqual(batch._status, batch._INITIAL) batch.begin() self.assertEqual(batch._status, batch._IN_PROGRESS) @@ -200,7 +201,7 @@ def test_begin(self): def test_begin_fail(self): _PROJECT = 'PROJECT' client = _Client(_PROJECT, None) - batch = self._makeOne(client) + batch = self._make_one(client) batch._status = batch._IN_PROGRESS with self.assertRaises(ValueError): batch.begin() @@ -208,7 +209,7 @@ def test_begin_fail(self): def test_rollback(self): _PROJECT = 'PROJECT' client = _Client(_PROJECT, None) - batch = self._makeOne(client) + batch = self._make_one(client) batch.begin() self.assertEqual(batch._status, batch._IN_PROGRESS) batch.rollback() @@ -217,7 +218,7 @@ def test_rollback(self): def test_rollback_wrong_status(self): _PROJECT = 'PROJECT' client = _Client(_PROJECT, None) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertEqual(batch._status, batch._INITIAL) self.assertRaises(ValueError, batch.rollback) @@ -226,7 +227,7 @@ def test_commit(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertEqual(batch._status, batch._INITIAL) batch.begin() @@ -241,7 +242,7 @@ def test_commit_wrong_status(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertEqual(batch._status, batch._INITIAL) self.assertRaises(ValueError, batch.commit) @@ -251,7 +252,7 @@ def test_commit_w_partial_key_entities(self): _NEW_ID = 1234 connection = _Connection(_NEW_ID) client = _Client(_PROJECT, connection) - batch = self._makeOne(client) + batch = self._make_one(client) entity = _Entity({}) key = entity.key = _Key(_PROJECT) key._id = None @@ -278,7 +279,7 @@ def test_as_context_mgr_wo_error(self): client = _Client(_PROJECT, connection) self.assertEqual(list(client._batches), []) - with self._makeOne(client) as batch: + with self._make_one(client) as batch: self.assertEqual(list(client._batches), [batch]) batch.put(entity) @@ -301,10 +302,10 @@ def test_as_context_mgr_nested(self): client = _Client(_PROJECT, connection) self.assertEqual(list(client._batches), []) - with self._makeOne(client) as batch1: + with self._make_one(client) as batch1: self.assertEqual(list(client._batches), [batch1]) batch1.put(entity1) - with self._makeOne(client) as batch2: + with self._make_one(client) as batch2: self.assertEqual(list(client._batches), [batch2, batch1]) batch2.put(entity2) @@ -333,7 +334,7 @@ def test_as_context_mgr_w_error(self): self.assertEqual(list(client._batches), []) try: - with self._makeOne(client) as batch: + with self._make_one(client) as batch: self.assertEqual(list(client._batches), [batch]) batch.put(entity) raise ValueError("testing") @@ -347,7 +348,7 @@ def test_as_context_mgr_w_error(self): self.assertEqual(connection._committed, []) def test_as_context_mgr_enter_fails(self): - klass = self._getTargetClass() + klass = self._get_target_class() class FailedBegin(klass): diff --git a/datastore/unit_tests/test_client.py b/datastore/unit_tests/test_client.py index 79dd7b6b8b05..2484d93796bc 100644 --- a/datastore/unit_tests/test_client.py +++ b/datastore/unit_tests/test_client.py @@ -33,7 +33,7 @@ def _make_entity_pb(project, kind, integer_id, name=None, str_val=None): class Test__get_gcd_project(unittest.TestCase): - def _callFUT(self): + def _call_fut(self): from google.cloud.datastore.client import _get_gcd_project return _get_gcd_project() @@ -43,7 +43,7 @@ def test_no_value(self): environ = {} with _Monkey(os, getenv=environ.get): - project = self._callFUT() + project = self._call_fut() self.assertIsNone(project) def test_value_set(self): @@ -54,13 +54,13 @@ def test_value_set(self): MOCK_PROJECT = object() environ = {GCD_DATASET: MOCK_PROJECT} with _Monkey(os, getenv=environ.get): - project = self._callFUT() + project = self._call_fut() self.assertEqual(project, MOCK_PROJECT) class Test__determine_default_project(unittest.TestCase): - def _callFUT(self, project=None): + def _call_fut(self, project=None): from google.cloud.datastore.client import ( _determine_default_project) return _determine_default_project(project=project) @@ -86,7 +86,7 @@ def fallback_mock(project=None): } with _Monkey(client, **patched_methods): - returned_project = self._callFUT(project_called) + returned_project = self._call_fut(project_called) return returned_project, _callers @@ -120,24 +120,25 @@ class TestClient(unittest.TestCase): PROJECT = 'PROJECT' def setUp(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() self.original_cnxn_class = KLASS._connection_class KLASS._connection_class = _MockConnection def tearDown(self): - KLASS = self._getTargetClass() + KLASS = self._get_target_class() KLASS._connection_class = self.original_cnxn_class - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.client import Client return Client - def _makeOne(self, project=PROJECT, namespace=None, - credentials=None, http=None): - return self._getTargetClass()(project=project, - namespace=namespace, - credentials=credentials, - http=http) + def _make_one(self, project=PROJECT, namespace=None, + credentials=None, http=None): + return self._get_target_class()(project=project, + namespace=namespace, + credentials=credentials, + http=http) def test_ctor_w_project_no_environ(self): from google.cloud._testing import _Monkey @@ -146,7 +147,7 @@ def test_ctor_w_project_no_environ(self): # Some environments (e.g. AppVeyor CI) run in GCE, so # this test would fail artificially. with _Monkey(_MUT, _base_default_project=lambda project: None): - self.assertRaises(EnvironmentError, self._makeOne, None) + self.assertRaises(EnvironmentError, self._make_one, None) def test_ctor_w_implicit_inputs(self): from google.cloud._testing import _Monkey @@ -161,7 +162,7 @@ def fallback_mock(project): default_called.append(project) return project or OTHER - klass = self._getTargetClass() + klass = self._get_target_class() with _Monkey(_MUT, _determine_default_project=fallback_mock): with _Monkey(_base_client, @@ -181,10 +182,10 @@ def test_ctor_w_explicit_inputs(self): NAMESPACE = 'namespace' creds = object() http = object() - client = self._makeOne(project=OTHER, - namespace=NAMESPACE, - credentials=creds, - http=http) + client = self._make_one(project=OTHER, + namespace=NAMESPACE, + credentials=creds, + http=http) self.assertEqual(client.project, OTHER) self.assertEqual(client.namespace, NAMESPACE) self.assertIsInstance(client.connection, _MockConnection) @@ -195,7 +196,7 @@ def test_ctor_w_explicit_inputs(self): def test__push_batch_and__pop_batch(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) batch = client.batch() xact = client.transaction() client._push_batch(batch) @@ -220,7 +221,7 @@ def _get_multi(*args, **kw): return [] creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.get_multi = _get_multi key = object() @@ -243,7 +244,7 @@ def _get_multi(*args, **kw): return [_entity] creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.get_multi = _get_multi key, missing, deferred = object(), [], [] @@ -258,7 +259,7 @@ def _get_multi(*args, **kw): def test_get_multi_no_keys(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) results = client.get_multi([]) self.assertEqual(results, []) @@ -266,7 +267,7 @@ def test_get_multi_miss(self): from google.cloud.datastore.key import Key creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result() key = Key('Kind', 1234, project=self.PROJECT) results = client.get_multi([key]) @@ -287,7 +288,7 @@ def test_get_multi_miss_w_missing(self): path_element.id = ID creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) # Set missing entity on mock connection. client.connection._add_lookup_result(missing=[missed]) @@ -302,7 +303,7 @@ def test_get_multi_w_missing_non_empty(self): from google.cloud.datastore.key import Key creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) key = Key('Kind', 1234, project=self.PROJECT) missing = ['this', 'list', 'is', 'not', 'empty'] @@ -313,7 +314,7 @@ def test_get_multi_w_deferred_non_empty(self): from google.cloud.datastore.key import Key creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) key = Key('Kind', 1234, project=self.PROJECT) deferred = ['this', 'list', 'is', 'not', 'empty'] @@ -327,7 +328,7 @@ def test_get_multi_miss_w_deferred(self): # Set deferred entity on mock connection. creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result(deferred=[key.to_protobuf()]) deferred = [] @@ -352,7 +353,7 @@ def test_get_multi_w_deferred_from_backend_but_not_passed(self): entity2_pb.key.CopyFrom(key2_pb) creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) # mock up two separate requests client.connection._add_lookup_result([entity1_pb], deferred=[key2_pb]) client.connection._add_lookup_result([entity2_pb]) @@ -401,7 +402,7 @@ def test_get_multi_hit(self): # Make a connection to return the entity pb. creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result([entity_pb]) key = Key(KIND, ID, project=self.PROJECT) @@ -428,7 +429,7 @@ def test_get_multi_hit_w_transaction(self): # Make a connection to return the entity pb. creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result([entity_pb]) key = Key(KIND, ID, project=self.PROJECT) @@ -462,7 +463,7 @@ def test_get_multi_hit_multiple_keys_same_project(self): # Make a connection to return the entity pbs. creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result([entity_pb1, entity_pb2]) key1 = Key(KIND, ID1, project=self.PROJECT) @@ -488,7 +489,7 @@ def test_get_multi_hit_multiple_keys_different_project(self): key2 = Key('KIND', 1234, project=PROJECT2) creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with self.assertRaises(ValueError): client.get_multi([key1, key2]) @@ -506,7 +507,7 @@ def test_get_multi_max_loops(self): # Make a connection to return the entity pb. creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._add_lookup_result([entity_pb]) key = Key(KIND, ID, project=self.PROJECT) @@ -529,7 +530,7 @@ def _put_multi(*args, **kw): _called_with.append((args, kw)) creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.put_multi = _put_multi entity = object() @@ -540,7 +541,7 @@ def _put_multi(*args, **kw): def test_put_multi_no_entities(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) self.assertIsNone(client.put_multi([])) def test_put_multi_w_single_empty_entity(self): @@ -548,7 +549,7 @@ def test_put_multi_w_single_empty_entity(self): from google.cloud.datastore.entity import Entity creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) self.assertRaises(ValueError, client.put_multi, Entity()) def test_put_multi_no_batch_w_partial_key(self): @@ -559,7 +560,7 @@ def test_put_multi_no_batch_w_partial_key(self): key._id = None creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._commit.append([_KeyPB(key)]) result = client.put_multi([entity]) @@ -585,7 +586,7 @@ def test_put_multi_existing_batch_w_completed_key(self): from google.cloud.datastore.helpers import _property_tuples creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) entity = _Entity(foo=u'bar') key = entity.key = _Key(self.PROJECT) @@ -609,7 +610,7 @@ def _delete_multi(*args, **kw): _called_with.append((args, kw)) creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.delete_multi = _delete_multi key = object() @@ -620,7 +621,7 @@ def _delete_multi(*args, **kw): def test_delete_multi_no_keys(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) result = client.delete_multi([]) self.assertIsNone(result) self.assertEqual(len(client.connection._commit_cw), 0) @@ -629,7 +630,7 @@ def test_delete_multi_no_batch(self): key = _Key(self.PROJECT) creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) client.connection._commit.append([]) result = client.delete_multi([key]) @@ -645,7 +646,7 @@ def test_delete_multi_no_batch(self): def test_delete_multi_w_existing_batch(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) key = _Key(self.PROJECT) with _NoCommitBatch(client) as CURR_BATCH: @@ -658,7 +659,7 @@ def test_delete_multi_w_existing_batch(self): def test_delete_multi_w_existing_transaction(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) key = _Key(self.PROJECT) with _NoCommitTransaction(client) as CURR_XACT: @@ -676,7 +677,7 @@ def test_allocate_ids_w_partial_key(self): INCOMPLETE_KEY._id = None creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) result = client.allocate_ids(INCOMPLETE_KEY, NUM_IDS) @@ -685,7 +686,7 @@ def test_allocate_ids_w_partial_key(self): def test_allocate_ids_with_completed_key(self): creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) COMPLETE_KEY = _Key(self.PROJECT) self.assertRaises(ValueError, client.allocate_ids, COMPLETE_KEY, 2) @@ -695,7 +696,7 @@ def test_key_w_project(self): ID = 1234 creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) self.assertRaises(TypeError, client.key, KIND, ID, project=self.PROJECT) @@ -708,7 +709,7 @@ def test_key_wo_project(self): ID = 1234 creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with _Monkey(MUT, Key=_Dummy): key = client.key(KIND, ID) @@ -730,7 +731,7 @@ def test_key_w_namespace(self): NAMESPACE = object() creds = object() - client = self._makeOne(namespace=NAMESPACE, credentials=creds) + client = self._make_one(namespace=NAMESPACE, credentials=creds) with _Monkey(MUT, Key=_Dummy): key = client.key(KIND, ID) @@ -752,7 +753,7 @@ def test_key_w_namespace_collision(self): NAMESPACE2 = object() creds = object() - client = self._makeOne(namespace=NAMESPACE1, credentials=creds) + client = self._make_one(namespace=NAMESPACE1, credentials=creds) with _Monkey(MUT, Key=_Dummy): key = client.key(KIND, ID, namespace=NAMESPACE2) @@ -769,7 +770,7 @@ def test_batch(self): from google.cloud._testing import _Monkey creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with _Monkey(MUT, Batch=_Dummy): batch = client.batch() @@ -783,7 +784,7 @@ def test_transaction_defaults(self): from google.cloud._testing import _Monkey creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with _Monkey(MUT, Transaction=_Dummy): xact = client.transaction() @@ -796,8 +797,8 @@ def test_query_w_client(self): KIND = 'KIND' creds = object() - client = self._makeOne(credentials=creds) - other = self._makeOne(credentials=object()) + client = self._make_one(credentials=creds) + other = self._make_one(credentials=object()) self.assertRaises(TypeError, client.query, kind=KIND, client=other) @@ -805,7 +806,7 @@ def test_query_w_project(self): KIND = 'KIND' creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) self.assertRaises(TypeError, client.query, kind=KIND, project=self.PROJECT) @@ -815,7 +816,7 @@ def test_query_w_defaults(self): from google.cloud._testing import _Monkey creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with _Monkey(MUT, Query=_Dummy): query = client.query() @@ -841,7 +842,7 @@ def test_query_explicit(self): DISTINCT_ON = ['DISTINCT_ON'] creds = object() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) with _Monkey(MUT, Query=_Dummy): query = client.query( @@ -876,7 +877,7 @@ def test_query_w_namespace(self): NAMESPACE = object() creds = object() - client = self._makeOne(namespace=NAMESPACE, credentials=creds) + client = self._make_one(namespace=NAMESPACE, credentials=creds) with _Monkey(MUT, Query=_Dummy): query = client.query(kind=KIND) @@ -899,7 +900,7 @@ def test_query_w_namespace_collision(self): NAMESPACE2 = object() creds = object() - client = self._makeOne(namespace=NAMESPACE1, credentials=creds) + client = self._make_one(namespace=NAMESPACE1, credentials=creds) with _Monkey(MUT, Query=_Dummy): query = client.query(kind=KIND, namespace=NAMESPACE2) diff --git a/datastore/unit_tests/test_entity.py b/datastore/unit_tests/test_entity.py index 3a5674a85cd4..30d40f947cc6 100644 --- a/datastore/unit_tests/test_entity.py +++ b/datastore/unit_tests/test_entity.py @@ -21,16 +21,17 @@ class TestEntity(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.entity import Entity return Entity - def _makeOne(self, key=None, exclude_from_indexes=()): - klass = self._getTargetClass() + def _make_one(self, key=None, exclude_from_indexes=()): + klass = self._get_target_class() return klass(key=key, exclude_from_indexes=exclude_from_indexes) def test_ctor_defaults(self): - klass = self._getTargetClass() + klass = self._get_target_class() entity = klass() self.assertIsNone(entity.key) self.assertIsNone(entity.kind) @@ -39,7 +40,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): _EXCLUDE_FROM_INDEXES = ['foo', 'bar'] key = _Key() - entity = self._makeOne( + entity = self._make_one( key=key, exclude_from_indexes=_EXCLUDE_FROM_INDEXES) self.assertEqual(sorted(entity.exclude_from_indexes), sorted(_EXCLUDE_FROM_INDEXES)) @@ -47,13 +48,13 @@ def test_ctor_explicit(self): def test_ctor_bad_exclude_from_indexes(self): BAD_EXCLUDE_FROM_INDEXES = object() key = _Key() - self.assertRaises(TypeError, self._makeOne, key=key, + self.assertRaises(TypeError, self._make_one, key=key, exclude_from_indexes=BAD_EXCLUDE_FROM_INDEXES) def test___eq_____ne___w_non_entity(self): from google.cloud.datastore.key import Key key = Key(_KIND, _ID, project=_PROJECT) - entity = self._makeOne(key=key) + entity = self._make_one(key=key) self.assertFalse(entity == object()) self.assertTrue(entity != object()) @@ -62,9 +63,9 @@ def test___eq_____ne___w_different_keys(self): _ID1 = 1234 _ID2 = 2345 key1 = Key(_KIND, _ID1, project=_PROJECT) - entity1 = self._makeOne(key=key1) + entity1 = self._make_one(key=key1) key2 = Key(_KIND, _ID2, project=_PROJECT) - entity2 = self._makeOne(key=key2) + entity2 = self._make_one(key=key2) self.assertFalse(entity1 == entity2) self.assertTrue(entity1 != entity2) @@ -76,12 +77,12 @@ def test___eq_____ne___w_same_keys(self): meaning = 9 key1 = Key(_KIND, _ID, project=_PROJECT) - entity1 = self._makeOne(key=key1, exclude_from_indexes=(name,)) + entity1 = self._make_one(key=key1, exclude_from_indexes=(name,)) entity1[name] = value entity1._meanings[name] = (meaning, value) key2 = Key(_KIND, _ID, project=_PROJECT) - entity2 = self._makeOne(key=key2, exclude_from_indexes=(name,)) + entity2 = self._make_one(key=key2, exclude_from_indexes=(name,)) entity2[name] = value entity2._meanings[name] = (meaning, value) @@ -91,10 +92,10 @@ 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._makeOne(key=key1) + entity1 = self._make_one(key=key1) entity1['foo'] = 'Foo' key2 = Key(_KIND, _ID, project=_PROJECT) - entity2 = self._makeOne(key=key2) + entity2 = self._make_one(key=key2) entity1['bar'] = 'Bar' self.assertFalse(entity1 == entity2) self.assertTrue(entity1 != entity2) @@ -103,9 +104,9 @@ 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._makeOne(key=key1) + entity1 = self._make_one(key=key1) entity1['some_key'] = key1 - entity2 = self._makeOne(key=key1) + entity2 = self._make_one(key=key1) entity2['some_key'] = key2 self.assertTrue(entity1 == entity2) self.assertFalse(entity1 != entity2) @@ -116,9 +117,9 @@ def test___eq_____ne___w_same_keys_props_w_diff_keys_as_value(self): _ID2 = 2345 key1 = Key(_KIND, _ID1, project=_PROJECT) key2 = Key(_KIND, _ID2, project=_PROJECT) - entity1 = self._makeOne(key=key1) + entity1 = self._make_one(key=key1) entity1['some_key'] = key1 - entity2 = self._makeOne(key=key1) + entity2 = self._make_one(key=key1) entity2['some_key'] = key2 self.assertFalse(entity1 == entity2) self.assertTrue(entity1 != entity2) @@ -126,12 +127,12 @@ 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._makeOne(key=key) - sub1 = self._makeOne() + entity1 = self._make_one(key=key) + sub1 = self._make_one() sub1.update({'foo': 'Foo'}) entity1['some_entity'] = sub1 - entity2 = self._makeOne(key=key) - sub2 = self._makeOne() + entity2 = self._make_one(key=key) + sub2 = self._make_one() sub2.update({'foo': 'Foo'}) entity2['some_entity'] = sub2 self.assertTrue(entity1 == entity2) @@ -140,12 +141,12 @@ 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._makeOne(key=key) - sub1 = self._makeOne() + entity1 = self._make_one(key=key) + sub1 = self._make_one() sub1.update({'foo': 'Foo'}) entity1['some_entity'] = sub1 - entity2 = self._makeOne(key=key) - sub2 = self._makeOne() + entity2 = self._make_one(key=key) + sub2 = self._make_one() sub2.update({'foo': 'Bar'}) entity2['some_entity'] = sub2 self.assertFalse(entity1 == entity2) @@ -158,10 +159,10 @@ def test__eq__same_value_different_exclude(self): value = 42 key = Key(_KIND, _ID, project=_PROJECT) - entity1 = self._makeOne(key=key, exclude_from_indexes=(name,)) + entity1 = self._make_one(key=key, exclude_from_indexes=(name,)) entity1[name] = value - entity2 = self._makeOne(key=key, exclude_from_indexes=()) + entity2 = self._make_one(key=key, exclude_from_indexes=()) entity2[name] = value self.assertFalse(entity1 == entity2) @@ -174,23 +175,23 @@ def test__eq__same_value_different_meanings(self): meaning = 9 key = Key(_KIND, _ID, project=_PROJECT) - entity1 = self._makeOne(key=key, exclude_from_indexes=(name,)) + entity1 = self._make_one(key=key, exclude_from_indexes=(name,)) entity1[name] = value - entity2 = self._makeOne(key=key, exclude_from_indexes=(name,)) + entity2 = self._make_one(key=key, exclude_from_indexes=(name,)) entity2[name] = value entity2._meanings[name] = (meaning, value) self.assertFalse(entity1 == entity2) def test___repr___no_key_empty(self): - entity = self._makeOne() + entity = self._make_one() self.assertEqual(repr(entity), '') def test___repr___w_key_non_empty(self): key = _Key() key._path = '/bar/baz' - entity = self._makeOne(key=key) + entity = self._make_one(key=key) entity['foo'] = 'Foo' self.assertEqual(repr(entity), "") diff --git a/datastore/unit_tests/test_helpers.py b/datastore/unit_tests/test_helpers.py index 5d6a90eed0ff..f3fa3391bbb7 100644 --- a/datastore/unit_tests/test_helpers.py +++ b/datastore/unit_tests/test_helpers.py @@ -17,7 +17,7 @@ class Test__new_value_pb(unittest.TestCase): - def _callFUT(self, entity_pb, name): + def _call_fut(self, entity_pb, name): from google.cloud.datastore.helpers import _new_value_pb return _new_value_pb(entity_pb, name) @@ -26,7 +26,7 @@ def test_it(self): entity_pb = entity_pb2.Entity() name = 'foo' - result = self._callFUT(entity_pb, name) + result = self._call_fut(entity_pb, name) self.assertIsInstance(result, entity_pb2.Value) self.assertEqual(len(entity_pb.properties), 1) @@ -35,7 +35,7 @@ def test_it(self): class Test__property_tuples(unittest.TestCase): - def _callFUT(self, entity_pb): + def _call_fut(self, entity_pb): from google.cloud.datastore.helpers import _property_tuples return _property_tuples(entity_pb) @@ -50,7 +50,7 @@ def test_it(self): val_pb1 = _new_value_pb(entity_pb, name1) val_pb2 = _new_value_pb(entity_pb, name2) - result = self._callFUT(entity_pb) + result = self._call_fut(entity_pb) self.assertIsInstance(result, types.GeneratorType) self.assertEqual(sorted(result), sorted([(name1, val_pb1), (name2, val_pb2)])) @@ -58,7 +58,7 @@ def test_it(self): class Test_entity_from_protobuf(unittest.TestCase): - def _callFUT(self, val): + def _call_fut(self, val): from google.cloud.datastore.helpers import entity_from_protobuf return entity_from_protobuf(val) @@ -93,7 +93,7 @@ def test_it(self): indexed_array_val_pb = array_pb2.add() indexed_array_val_pb.integer_value = 12 - entity = self._callFUT(entity_pb) + entity = self._call_fut(entity_pb) self.assertEqual(entity.kind, _KIND) self.assertEqual(entity.exclude_from_indexes, frozenset(['bar', 'baz'])) @@ -130,13 +130,13 @@ def test_mismatched_value_indexed(self): unindexed_value_pb2.integer_value = 11 with self.assertRaises(ValueError): - self._callFUT(entity_pb) + self._call_fut(entity_pb) def test_entity_no_key(self): from google.cloud.datastore._generated import entity_pb2 entity_pb = entity_pb2.Entity() - entity = self._callFUT(entity_pb) + entity = self._call_fut(entity_pb) self.assertIsNone(entity.key) self.assertEqual(dict(entity), {}) @@ -151,7 +151,7 @@ def test_entity_with_meaning(self): value_pb.meaning = meaning = 9 value_pb.string_value = val = u'something' - entity = self._callFUT(entity_pb) + entity = self._call_fut(entity_pb) self.assertIsNone(entity.key) self.assertEqual(dict(entity), {name: val}) self.assertEqual(entity._meanings, {name: (meaning, val)}) @@ -178,7 +178,7 @@ def test_nested_entity_no_key(self): outside_val_pb = _new_value_pb(entity_pb, OUTSIDE_NAME) outside_val_pb.entity_value.CopyFrom(entity_inside) - entity = self._callFUT(entity_pb) + entity = self._call_fut(entity_pb) self.assertEqual(entity.key.project, PROJECT) self.assertEqual(entity.key.flat_path, (KIND,)) self.assertEqual(len(entity), 1) @@ -191,7 +191,7 @@ def test_nested_entity_no_key(self): class Test_entity_to_protobuf(unittest.TestCase): - def _callFUT(self, entity): + def _call_fut(self, entity): from google.cloud.datastore.helpers import entity_to_protobuf return entity_to_protobuf(entity) @@ -218,7 +218,7 @@ def test_empty(self): from google.cloud.datastore.entity import Entity entity = Entity() - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) self._compareEntityProto(entity_pb, entity_pb2.Entity()) def test_key_only(self): @@ -230,7 +230,7 @@ def test_key_only(self): project = 'PROJECT' key = Key(kind, name, project=project) entity = Entity(key=key) - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) expected_pb = entity_pb2.Entity() expected_pb.key.partition_id.project_id = project @@ -250,7 +250,7 @@ def test_simple_fields(self): entity[name1] = value1 = 42 name2 = 'bar' entity[name2] = value2 = u'some-string' - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) expected_pb = entity_pb2.Entity() val_pb1 = _new_value_pb(expected_pb, name1) @@ -266,7 +266,7 @@ def test_with_empty_list(self): entity = Entity() entity['foo'] = [] - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) self._compareEntityProto(entity_pb, entity_pb2.Entity()) @@ -317,7 +317,7 @@ def test_inverts_to_protobuf(self): # Convert to the user-space Entity. entity = entity_from_protobuf(original_pb) # Convert the user-space Entity back to a protobuf. - new_pb = self._callFUT(entity) + new_pb = self._call_fut(entity) # NOTE: entity_to_protobuf() strips the project so we "cheat". new_pb.key.partition_id.project_id = project @@ -332,7 +332,7 @@ def test_meaning_with_change(self): name = 'foo' entity[name] = value = 42 entity._meanings[name] = (9, 1337) - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) expected_pb = entity_pb2.Entity() value_pb = _new_value_pb(expected_pb, name) @@ -351,7 +351,7 @@ def test_variable_meanings(self): entity[name] = values = [1, 20, 300] meaning = 9 entity._meanings[name] = ([None, meaning, None], values) - entity_pb = self._callFUT(entity) + entity_pb = self._call_fut(entity) # Construct the expected protobuf. expected_pb = entity_pb2.Entity() @@ -370,7 +370,7 @@ def test_variable_meanings(self): class Test_key_from_protobuf(unittest.TestCase): - def _callFUT(self, val): + def _call_fut(self, val): from google.cloud.datastore.helpers import key_from_protobuf return key_from_protobuf(val) @@ -394,7 +394,7 @@ def _makePB(self, project=None, namespace=None, path=()): def test_wo_namespace_in_pb(self): _PROJECT = 'PROJECT' pb = self._makePB(path=[{'kind': 'KIND'}], project=_PROJECT) - key = self._callFUT(pb) + key = self._call_fut(pb) self.assertEqual(key.project, _PROJECT) self.assertIsNone(key.namespace) @@ -403,7 +403,7 @@ def test_w_namespace_in_pb(self): _NAMESPACE = 'NAMESPACE' pb = self._makePB(path=[{'kind': 'KIND'}], namespace=_NAMESPACE, project=_PROJECT) - key = self._callFUT(pb) + key = self._call_fut(pb) self.assertEqual(key.project, _PROJECT) self.assertEqual(key.namespace, _NAMESPACE) @@ -414,17 +414,17 @@ def test_w_nested_path_in_pb(self): {'kind': 'GRANDCHILD', 'id': 5678}, ] pb = self._makePB(path=_PATH, project='PROJECT') - key = self._callFUT(pb) + key = self._call_fut(pb) self.assertEqual(key.path, _PATH) def test_w_nothing_in_pb(self): pb = self._makePB() - self.assertRaises(ValueError, self._callFUT, pb) + self.assertRaises(ValueError, self._call_fut, pb) class Test__pb_attr_value(unittest.TestCase): - def _callFUT(self, val): + def _call_fut(self, val): from google.cloud.datastore.helpers import _pb_attr_value return _pb_attr_value(val) @@ -437,7 +437,7 @@ def test_datetime_naive(self): micros = 4375 naive = datetime.datetime(2014, 9, 16, 10, 19, 32, micros) # No zone. utc = datetime.datetime(2014, 9, 16, 10, 19, 32, micros, UTC) - name, value = self._callFUT(naive) + name, value = self._call_fut(naive) self.assertEqual(name, 'timestamp_value') self.assertEqual(value.seconds, calendar.timegm(utc.timetuple())) self.assertEqual(value.nanos, 1000 * micros) @@ -449,7 +449,7 @@ def test_datetime_w_zone(self): micros = 4375 utc = datetime.datetime(2014, 9, 16, 10, 19, 32, micros, UTC) - name, value = self._callFUT(utc) + name, value = self._call_fut(utc) self.assertEqual(name, 'timestamp_value') self.assertEqual(value.seconds, calendar.timegm(utc.timetuple())) self.assertEqual(value.nanos, 1000 * micros) @@ -458,34 +458,34 @@ def test_key(self): from google.cloud.datastore.key import Key key = Key('PATH', 1234, project='PROJECT') - name, value = self._callFUT(key) + name, value = self._call_fut(key) self.assertEqual(name, 'key_value') self.assertEqual(value, key.to_protobuf()) def test_bool(self): - name, value = self._callFUT(False) + name, value = self._call_fut(False) self.assertEqual(name, 'boolean_value') self.assertEqual(value, False) def test_float(self): - name, value = self._callFUT(3.1415926) + name, value = self._call_fut(3.1415926) self.assertEqual(name, 'double_value') self.assertEqual(value, 3.1415926) def test_int(self): - name, value = self._callFUT(42) + name, value = self._call_fut(42) self.assertEqual(name, 'integer_value') self.assertEqual(value, 42) def test_long(self): must_be_long = (1 << 63) - 1 - name, value = self._callFUT(must_be_long) + name, value = self._call_fut(must_be_long) self.assertEqual(name, 'integer_value') self.assertEqual(value, must_be_long) def test_native_str(self): import six - name, value = self._callFUT('str') + name, value = self._call_fut('str') if six.PY2: self.assertEqual(name, 'blob_value') else: # pragma: NO COVER Python 3 @@ -493,25 +493,25 @@ def test_native_str(self): self.assertEqual(value, 'str') def test_bytes(self): - name, value = self._callFUT(b'bytes') + name, value = self._call_fut(b'bytes') self.assertEqual(name, 'blob_value') self.assertEqual(value, b'bytes') def test_unicode(self): - name, value = self._callFUT(u'str') + name, value = self._call_fut(u'str') self.assertEqual(name, 'string_value') self.assertEqual(value, u'str') def test_entity(self): from google.cloud.datastore.entity import Entity entity = Entity() - name, value = self._callFUT(entity) + name, value = self._call_fut(entity) self.assertEqual(name, 'entity_value') self.assertIs(value, entity) def test_array(self): values = ['a', 0, 3.14] - name, value = self._callFUT(values) + name, value = self._call_fut(values) self.assertEqual(name, 'array_value') self.assertIs(value, values) @@ -523,24 +523,24 @@ def test_geo_point(self): lng = 99.0007 geo_pt = GeoPoint(latitude=lat, longitude=lng) geo_pt_pb = latlng_pb2.LatLng(latitude=lat, longitude=lng) - name, value = self._callFUT(geo_pt) + name, value = self._call_fut(geo_pt) self.assertEqual(name, 'geo_point_value') self.assertEqual(value, geo_pt_pb) def test_null(self): from google.protobuf import struct_pb2 - name, value = self._callFUT(None) + name, value = self._call_fut(None) self.assertEqual(name, 'null_value') self.assertEqual(value, struct_pb2.NULL_VALUE) def test_object(self): - self.assertRaises(ValueError, self._callFUT, object()) + self.assertRaises(ValueError, self._call_fut, object()) class Test__get_value_from_value_pb(unittest.TestCase): - def _callFUT(self, pb): + def _call_fut(self, pb): from google.cloud.datastore.helpers import _get_value_from_value_pb return _get_value_from_value_pb(pb) @@ -563,7 +563,7 @@ def test_datetime(self): pb = entity_pb2.Value() pb.timestamp_value.seconds = calendar.timegm(utc.timetuple()) pb.timestamp_value.nanos = 1000 * micros - self.assertEqual(self._callFUT(pb), utc) + self.assertEqual(self._call_fut(pb), utc) def test_key(self): from google.cloud.datastore._generated import entity_pb2 @@ -572,28 +572,28 @@ def test_key(self): pb = entity_pb2.Value() expected = Key('KIND', 1234, project='PROJECT').to_protobuf() pb.key_value.CopyFrom(expected) - found = self._callFUT(pb) + found = self._call_fut(pb) self.assertEqual(found.to_protobuf(), expected) def test_bool(self): pb = self._makePB('boolean_value', False) - self.assertEqual(self._callFUT(pb), False) + self.assertEqual(self._call_fut(pb), False) def test_float(self): pb = self._makePB('double_value', 3.1415926) - self.assertEqual(self._callFUT(pb), 3.1415926) + self.assertEqual(self._call_fut(pb), 3.1415926) def test_int(self): pb = self._makePB('integer_value', 42) - self.assertEqual(self._callFUT(pb), 42) + self.assertEqual(self._call_fut(pb), 42) def test_bytes(self): pb = self._makePB('blob_value', b'str') - self.assertEqual(self._callFUT(pb), b'str') + self.assertEqual(self._call_fut(pb), b'str') def test_unicode(self): pb = self._makePB('string_value', u'str') - self.assertEqual(self._callFUT(pb), u'str') + self.assertEqual(self._call_fut(pb), u'str') def test_entity(self): from google.cloud.datastore._generated import entity_pb2 @@ -607,7 +607,7 @@ def test_entity(self): value_pb = _new_value_pb(entity_pb, 'foo') value_pb.string_value = 'Foo' - entity = self._callFUT(pb) + entity = self._call_fut(pb) self.assertIsInstance(entity, Entity) self.assertEqual(entity['foo'], 'Foo') @@ -620,7 +620,7 @@ def test_array(self): item_pb.string_value = 'Foo' item_pb = array_pb.add() item_pb.string_value = 'Bar' - items = self._callFUT(pb) + items = self._call_fut(pb) self.assertEqual(items, ['Foo', 'Bar']) def test_geo_point(self): @@ -632,7 +632,7 @@ def test_geo_point(self): lng = 13.37 geo_pt_pb = latlng_pb2.LatLng(latitude=lat, longitude=lng) pb = entity_pb2.Value(geo_point_value=geo_pt_pb) - result = self._callFUT(pb) + result = self._call_fut(pb) self.assertIsInstance(result, GeoPoint) self.assertEqual(result.latitude, lat) self.assertEqual(result.longitude, lng) @@ -642,7 +642,7 @@ def test_null(self): from google.cloud.datastore._generated import entity_pb2 pb = entity_pb2.Value(null_value=struct_pb2.NULL_VALUE) - result = self._callFUT(pb) + result = self._call_fut(pb) self.assertIsNone(result) def test_unknown(self): @@ -650,12 +650,12 @@ def test_unknown(self): pb = entity_pb2.Value() with self.assertRaises(ValueError): - self._callFUT(pb) + self._call_fut(pb) class Test_set_protobuf_value(unittest.TestCase): - def _callFUT(self, value_pb, val): + def _call_fut(self, value_pb, val): from google.cloud.datastore.helpers import _set_protobuf_value return _set_protobuf_value(value_pb, val) @@ -672,7 +672,7 @@ def test_datetime(self): pb = self._makePB() micros = 4375 utc = datetime.datetime(2014, 9, 16, 10, 19, 32, micros, UTC) - self._callFUT(pb, utc) + self._call_fut(pb, utc) value = pb.timestamp_value self.assertEqual(value.seconds, calendar.timegm(utc.timetuple())) self.assertEqual(value.nanos, 1000 * micros) @@ -682,44 +682,44 @@ def test_key(self): pb = self._makePB() key = Key('KIND', 1234, project='PROJECT') - self._callFUT(pb, key) + self._call_fut(pb, key) value = pb.key_value self.assertEqual(value, key.to_protobuf()) def test_none(self): pb = self._makePB() - self._callFUT(pb, None) + self._call_fut(pb, None) self.assertEqual(pb.WhichOneof('value_type'), 'null_value') def test_bool(self): pb = self._makePB() - self._callFUT(pb, False) + self._call_fut(pb, False) value = pb.boolean_value self.assertEqual(value, False) def test_float(self): pb = self._makePB() - self._callFUT(pb, 3.1415926) + self._call_fut(pb, 3.1415926) value = pb.double_value self.assertEqual(value, 3.1415926) def test_int(self): pb = self._makePB() - self._callFUT(pb, 42) + self._call_fut(pb, 42) value = pb.integer_value self.assertEqual(value, 42) def test_long(self): pb = self._makePB() must_be_long = (1 << 63) - 1 - self._callFUT(pb, must_be_long) + self._call_fut(pb, must_be_long) value = pb.integer_value self.assertEqual(value, must_be_long) def test_native_str(self): import six pb = self._makePB() - self._callFUT(pb, 'str') + self._call_fut(pb, 'str') if six.PY2: value = pb.blob_value else: # pragma: NO COVER Python 3 @@ -728,13 +728,13 @@ def test_native_str(self): def test_bytes(self): pb = self._makePB() - self._callFUT(pb, b'str') + self._call_fut(pb, b'str') value = pb.blob_value self.assertEqual(value, b'str') def test_unicode(self): pb = self._makePB() - self._callFUT(pb, u'str') + self._call_fut(pb, u'str') value = pb.string_value self.assertEqual(value, u'str') @@ -744,7 +744,7 @@ def test_entity_empty_wo_key(self): pb = self._makePB() entity = Entity() - self._callFUT(pb, entity) + self._call_fut(pb, entity) value = pb.entity_value self.assertEqual(value.key.SerializeToString(), b'') self.assertEqual(len(list(_property_tuples(value))), 0) @@ -760,7 +760,7 @@ def test_entity_w_key(self): key = Key('KIND', 123, project='PROJECT') entity = Entity(key=key) entity[name] = value - self._callFUT(pb, entity) + self._call_fut(pb, entity) entity_pb = pb.entity_value self.assertEqual(entity_pb.key, key.to_protobuf()) @@ -772,7 +772,7 @@ def test_entity_w_key(self): def test_array(self): pb = self._makePB() values = [u'a', 0, 3.14] - self._callFUT(pb, values) + self._call_fut(pb, values) marshalled = pb.array_value.values self.assertEqual(len(marshalled), len(values)) self.assertEqual(marshalled[0].string_value, values[0]) @@ -788,13 +788,13 @@ def test_geo_point(self): lng = 3.337 geo_pt = GeoPoint(latitude=lat, longitude=lng) geo_pt_pb = latlng_pb2.LatLng(latitude=lat, longitude=lng) - self._callFUT(pb, geo_pt) + self._call_fut(pb, geo_pt) self.assertEqual(pb.geo_point_value, geo_pt_pb) class Test__get_meaning(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.datastore.helpers import _get_meaning return _get_meaning(*args, **kwargs) @@ -802,7 +802,7 @@ def test_no_meaning(self): from google.cloud.datastore._generated import entity_pb2 value_pb = entity_pb2.Value() - result = self._callFUT(value_pb) + result = self._call_fut(value_pb) self.assertIsNone(result) def test_single(self): @@ -811,7 +811,7 @@ def test_single(self): value_pb = entity_pb2.Value() value_pb.meaning = meaning = 22 value_pb.string_value = u'hi' - result = self._callFUT(value_pb) + result = self._call_fut(value_pb) self.assertEqual(meaning, result) def test_empty_array_value(self): @@ -821,7 +821,7 @@ def test_empty_array_value(self): value_pb.array_value.values.add() value_pb.array_value.values.pop() - result = self._callFUT(value_pb, is_list=True) + result = self._call_fut(value_pb, is_list=True) self.assertEqual(None, result) def test_array_value(self): @@ -836,7 +836,7 @@ def test_array_value(self): sub_value_pb1.string_value = u'hi' sub_value_pb2.string_value = u'bye' - result = self._callFUT(value_pb, is_list=True) + result = self._call_fut(value_pb, is_list=True) self.assertEqual(meaning, result) def test_array_value_multiple_meanings(self): @@ -853,7 +853,7 @@ def test_array_value_multiple_meanings(self): sub_value_pb1.string_value = u'hi' sub_value_pb2.string_value = u'bye' - result = self._callFUT(value_pb, is_list=True) + result = self._call_fut(value_pb, is_list=True) self.assertEqual(result, [meaning1, meaning2]) def test_array_value_meaning_partially_unset(self): @@ -868,23 +868,24 @@ def test_array_value_meaning_partially_unset(self): sub_value_pb1.string_value = u'hi' sub_value_pb2.string_value = u'bye' - result = self._callFUT(value_pb, is_list=True) + result = self._call_fut(value_pb, is_list=True) self.assertEqual(result, [meaning1, None]) class TestGeoPoint(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.helpers import GeoPoint return GeoPoint - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): lat = 81.2 lng = 359.9999 - geo_pt = self._makeOne(lat, lng) + geo_pt = self._make_one(lat, lng) self.assertEqual(geo_pt.latitude, lat) self.assertEqual(geo_pt.longitude, lng) @@ -893,7 +894,7 @@ def test_to_protobuf(self): lat = 0.0001 lng = 20.03 - geo_pt = self._makeOne(lat, lng) + geo_pt = self._make_one(lat, lng) result = geo_pt.to_protobuf() geo_pt_pb = latlng_pb2.LatLng(latitude=lat, longitude=lng) self.assertEqual(result, geo_pt_pb) @@ -901,26 +902,26 @@ def test_to_protobuf(self): def test___eq__(self): lat = 0.0001 lng = 20.03 - geo_pt1 = self._makeOne(lat, lng) - geo_pt2 = self._makeOne(lat, lng) + geo_pt1 = self._make_one(lat, lng) + geo_pt2 = self._make_one(lat, lng) self.assertEqual(geo_pt1, geo_pt2) def test___eq__type_differ(self): lat = 0.0001 lng = 20.03 - geo_pt1 = self._makeOne(lat, lng) + geo_pt1 = self._make_one(lat, lng) geo_pt2 = object() self.assertNotEqual(geo_pt1, geo_pt2) def test___ne__same_value(self): lat = 0.0001 lng = 20.03 - geo_pt1 = self._makeOne(lat, lng) - geo_pt2 = self._makeOne(lat, lng) + geo_pt1 = self._make_one(lat, lng) + geo_pt2 = self._make_one(lat, lng) comparison_val = (geo_pt1 != geo_pt2) self.assertFalse(comparison_val) def test___ne__(self): - geo_pt1 = self._makeOne(0.0, 1.0) - geo_pt2 = self._makeOne(2.0, 3.0) + geo_pt1 = self._make_one(0.0, 1.0) + geo_pt2 = self._make_one(2.0, 3.0) self.assertNotEqual(geo_pt1, geo_pt2) diff --git a/datastore/unit_tests/test_key.py b/datastore/unit_tests/test_key.py index 22aaefb27656..b2227d297b31 100644 --- a/datastore/unit_tests/test_key.py +++ b/datastore/unit_tests/test_key.py @@ -19,23 +19,24 @@ class TestKey(unittest.TestCase): _DEFAULT_PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.key import Key return Key - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_ctor_empty(self): - self.assertRaises(ValueError, self._makeOne) + self.assertRaises(ValueError, self._make_one) def test_ctor_no_project(self): - klass = self._getTargetClass() + klass = self._get_target_class() self.assertRaises(ValueError, klass, 'KIND') def test_ctor_w_explicit_project_empty_path(self): _PROJECT = 'PROJECT' - self.assertRaises(ValueError, self._makeOne, project=_PROJECT) + self.assertRaises(ValueError, self._make_one, project=_PROJECT) def test_ctor_parent(self): _PARENT_KIND = 'KIND1' @@ -48,10 +49,10 @@ def test_ctor_parent(self): {'kind': _PARENT_KIND, 'id': _PARENT_ID}, {'kind': _CHILD_KIND, 'id': _CHILD_ID}, ] - parent_key = self._makeOne(_PARENT_KIND, _PARENT_ID, - project=_PARENT_PROJECT, - namespace=_PARENT_NAMESPACE) - key = self._makeOne(_CHILD_KIND, _CHILD_ID, parent=parent_key) + parent_key = self._make_one(_PARENT_KIND, _PARENT_ID, + project=_PARENT_PROJECT, + namespace=_PARENT_NAMESPACE) + key = self._make_one(_CHILD_KIND, _CHILD_ID, parent=parent_key) self.assertEqual(key.project, parent_key.project) self.assertEqual(key.namespace, parent_key.namespace) self.assertEqual(key.kind, _CHILD_KIND) @@ -59,33 +60,33 @@ def test_ctor_parent(self): self.assertIs(key.parent, parent_key) def test_ctor_partial_parent(self): - parent_key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + parent_key = self._make_one('KIND', project=self._DEFAULT_PROJECT) with self.assertRaises(ValueError): - self._makeOne('KIND2', 1234, parent=parent_key) + self._make_one('KIND2', 1234, parent=parent_key) def test_ctor_parent_bad_type(self): with self.assertRaises(AttributeError): - self._makeOne('KIND2', 1234, parent=('KIND1', 1234), - project=self._DEFAULT_PROJECT) + self._make_one('KIND2', 1234, parent=('KIND1', 1234), + project=self._DEFAULT_PROJECT) def test_ctor_parent_bad_namespace(self): - parent_key = self._makeOne('KIND', 1234, namespace='FOO', - project=self._DEFAULT_PROJECT) + parent_key = self._make_one('KIND', 1234, namespace='FOO', + project=self._DEFAULT_PROJECT) with self.assertRaises(ValueError): - self._makeOne('KIND2', 1234, namespace='BAR', parent=parent_key, - project=self._DEFAULT_PROJECT) + self._make_one('KIND2', 1234, namespace='BAR', parent=parent_key, + PROJECT=self._DEFAULT_PROJECT) def test_ctor_parent_bad_project(self): - parent_key = self._makeOne('KIND', 1234, project='FOO') + parent_key = self._make_one('KIND', 1234, project='FOO') with self.assertRaises(ValueError): - self._makeOne('KIND2', 1234, parent=parent_key, - project='BAR') + self._make_one('KIND2', 1234, parent=parent_key, + project='BAR') def test_ctor_parent_empty_path(self): - parent_key = self._makeOne('KIND', 1234, - project=self._DEFAULT_PROJECT) + parent_key = self._make_one('KIND', 1234, + project=self._DEFAULT_PROJECT) with self.assertRaises(ValueError): - self._makeOne(parent=parent_key) + self._make_one(parent=parent_key) def test_ctor_explicit(self): _PROJECT = 'PROJECT-ALT' @@ -93,24 +94,24 @@ def test_ctor_explicit(self): _KIND = 'KIND' _ID = 1234 _PATH = [{'kind': _KIND, 'id': _ID}] - key = self._makeOne(_KIND, _ID, namespace=_NAMESPACE, - project=_PROJECT) + key = self._make_one(_KIND, _ID, namespace=_NAMESPACE, + project=_PROJECT) self.assertEqual(key.project, _PROJECT) self.assertEqual(key.namespace, _NAMESPACE) self.assertEqual(key.kind, _KIND) self.assertEqual(key.path, _PATH) def test_ctor_bad_kind(self): - self.assertRaises(ValueError, self._makeOne, object(), + self.assertRaises(ValueError, self._make_one, object(), project=self._DEFAULT_PROJECT) def test_ctor_bad_id_or_name(self): - self.assertRaises(ValueError, self._makeOne, 'KIND', object(), - project=self._DEFAULT_PROJECT) - self.assertRaises(ValueError, self._makeOne, 'KIND', None, + self.assertRaises(ValueError, self._make_one, 'KIND', object(), project=self._DEFAULT_PROJECT) - self.assertRaises(ValueError, self._makeOne, 'KIND', 10, 'KIND2', None, + self.assertRaises(ValueError, self._make_one, 'KIND', None, project=self._DEFAULT_PROJECT) + self.assertRaises(ValueError, self._make_one, 'KIND', 10, 'KIND2', + None, project=self._DEFAULT_PROJECT) def test__clone(self): _PROJECT = 'PROJECT-ALT' @@ -118,8 +119,8 @@ def test__clone(self): _KIND = 'KIND' _ID = 1234 _PATH = [{'kind': _KIND, 'id': _ID}] - key = self._makeOne(_KIND, _ID, namespace=_NAMESPACE, - project=_PROJECT) + key = self._make_one(_KIND, _ID, namespace=_NAMESPACE, + project=_PROJECT) clone = key._clone() self.assertEqual(clone.project, _PROJECT) self.assertEqual(clone.namespace, _NAMESPACE) @@ -135,9 +136,9 @@ def test__clone_with_parent(self): _ID2 = 2345 _PATH = [{'kind': _KIND1, 'id': _ID1}, {'kind': _KIND2, 'id': _ID2}] - parent = self._makeOne(_KIND1, _ID1, namespace=_NAMESPACE, - project=_PROJECT) - key = self._makeOne(_KIND2, _ID2, parent=parent) + parent = self._make_one(_KIND1, _ID1, namespace=_NAMESPACE, + project=_PROJECT) + key = self._make_one(_KIND2, _ID2, parent=parent) self.assertIs(key.parent, parent) clone = key._clone() self.assertIs(clone.parent, key.parent) @@ -149,15 +150,15 @@ def test___eq_____ne___w_non_key(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _NAME = 'one' - key = self._makeOne(_KIND, _NAME, project=_PROJECT) + key = self._make_one(_KIND, _NAME, project=_PROJECT) self.assertFalse(key == object()) self.assertTrue(key != object()) def test___eq_____ne___two_incomplete_keys_same_kind(self): _PROJECT = 'PROJECT' _KIND = 'KIND' - key1 = self._makeOne(_KIND, project=_PROJECT) - key2 = self._makeOne(_KIND, project=_PROJECT) + key1 = self._make_one(_KIND, project=_PROJECT) + key2 = self._make_one(_KIND, project=_PROJECT) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -165,8 +166,8 @@ def test___eq_____ne___incomplete_key_w_complete_key_same_kind(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _ID = 1234 - key1 = self._makeOne(_KIND, project=_PROJECT) - key2 = self._makeOne(_KIND, _ID, project=_PROJECT) + key1 = self._make_one(_KIND, project=_PROJECT) + key2 = self._make_one(_KIND, _ID, project=_PROJECT) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -174,8 +175,8 @@ def test___eq_____ne___complete_key_w_incomplete_key_same_kind(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _ID = 1234 - key1 = self._makeOne(_KIND, _ID, project=_PROJECT) - key2 = self._makeOne(_KIND, project=_PROJECT) + key1 = self._make_one(_KIND, _ID, project=_PROJECT) + key2 = self._make_one(_KIND, project=_PROJECT) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -184,8 +185,8 @@ def test___eq_____ne___same_kind_different_ids(self): _KIND = 'KIND' _ID1 = 1234 _ID2 = 2345 - key1 = self._makeOne(_KIND, _ID1, project=_PROJECT) - key2 = self._makeOne(_KIND, _ID2, project=_PROJECT) + key1 = self._make_one(_KIND, _ID1, project=_PROJECT) + key2 = self._make_one(_KIND, _ID2, project=_PROJECT) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -193,8 +194,8 @@ def test___eq_____ne___same_kind_and_id(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _ID = 1234 - key1 = self._makeOne(_KIND, _ID, project=_PROJECT) - key2 = self._makeOne(_KIND, _ID, project=_PROJECT) + key1 = self._make_one(_KIND, _ID, project=_PROJECT) + key2 = self._make_one(_KIND, _ID, project=_PROJECT) self.assertTrue(key1 == key2) self.assertFalse(key1 != key2) @@ -203,8 +204,8 @@ def test___eq_____ne___same_kind_and_id_different_project(self): _PROJECT2 = 'PROJECT2' _KIND = 'KIND' _ID = 1234 - key1 = self._makeOne(_KIND, _ID, project=_PROJECT1) - key2 = self._makeOne(_KIND, _ID, project=_PROJECT2) + key1 = self._make_one(_KIND, _ID, project=_PROJECT1) + key2 = self._make_one(_KIND, _ID, project=_PROJECT2) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -214,10 +215,10 @@ def test___eq_____ne___same_kind_and_id_different_namespace(self): _NAMESPACE2 = 'NAMESPACE2' _KIND = 'KIND' _ID = 1234 - key1 = self._makeOne(_KIND, _ID, project=_PROJECT, - namespace=_NAMESPACE1) - key2 = self._makeOne(_KIND, _ID, project=_PROJECT, - namespace=_NAMESPACE2) + key1 = self._make_one(_KIND, _ID, project=_PROJECT, + namespace=_NAMESPACE1) + key2 = self._make_one(_KIND, _ID, project=_PROJECT, + namespace=_NAMESPACE2) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -226,8 +227,8 @@ def test___eq_____ne___same_kind_different_names(self): _KIND = 'KIND' _NAME1 = 'one' _NAME2 = 'two' - key1 = self._makeOne(_KIND, _NAME1, project=_PROJECT) - key2 = self._makeOne(_KIND, _NAME2, project=_PROJECT) + key1 = self._make_one(_KIND, _NAME1, project=_PROJECT) + key2 = self._make_one(_KIND, _NAME2, project=_PROJECT) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -235,8 +236,8 @@ def test___eq_____ne___same_kind_and_name(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _NAME = 'one' - key1 = self._makeOne(_KIND, _NAME, project=_PROJECT) - key2 = self._makeOne(_KIND, _NAME, project=_PROJECT) + key1 = self._make_one(_KIND, _NAME, project=_PROJECT) + key2 = self._make_one(_KIND, _NAME, project=_PROJECT) self.assertTrue(key1 == key2) self.assertFalse(key1 != key2) @@ -245,8 +246,8 @@ def test___eq_____ne___same_kind_and_name_different_project(self): _PROJECT2 = 'PROJECT2' _KIND = 'KIND' _NAME = 'one' - key1 = self._makeOne(_KIND, _NAME, project=_PROJECT1) - key2 = self._makeOne(_KIND, _NAME, project=_PROJECT2) + key1 = self._make_one(_KIND, _NAME, project=_PROJECT1) + key2 = self._make_one(_KIND, _NAME, project=_PROJECT2) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) @@ -256,17 +257,17 @@ def test___eq_____ne___same_kind_and_name_different_namespace(self): _NAMESPACE2 = 'NAMESPACE2' _KIND = 'KIND' _NAME = 'one' - key1 = self._makeOne(_KIND, _NAME, project=_PROJECT, - namespace=_NAMESPACE1) - key2 = self._makeOne(_KIND, _NAME, project=_PROJECT, - namespace=_NAMESPACE2) + key1 = self._make_one(_KIND, _NAME, project=_PROJECT, + namespace=_NAMESPACE1) + key2 = self._make_one(_KIND, _NAME, project=_PROJECT, + namespace=_NAMESPACE2) self.assertFalse(key1 == key2) self.assertTrue(key1 != key2) def test___hash___incomplete(self): _PROJECT = 'PROJECT' _KIND = 'KIND' - key = self._makeOne(_KIND, project=_PROJECT) + key = self._make_one(_KIND, project=_PROJECT) self.assertNotEqual(hash(key), hash(_KIND) + hash(_PROJECT) + hash(None)) @@ -274,7 +275,7 @@ def test___hash___completed_w_id(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _ID = 1234 - key = self._makeOne(_KIND, _ID, project=_PROJECT) + key = self._make_one(_KIND, _ID, project=_PROJECT) self.assertNotEqual(hash(key), hash(_KIND) + hash(_ID) + hash(_PROJECT) + hash(None)) @@ -283,13 +284,13 @@ def test___hash___completed_w_name(self): _PROJECT = 'PROJECT' _KIND = 'KIND' _NAME = 'NAME' - key = self._makeOne(_KIND, _NAME, project=_PROJECT) + key = self._make_one(_KIND, _NAME, project=_PROJECT) self.assertNotEqual(hash(key), hash(_KIND) + hash(_NAME) + hash(_PROJECT) + hash(None)) def test_completed_key_on_partial_w_id(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) _ID = 1234 new_key = key.completed_key(_ID) self.assertIsNot(key, new_key) @@ -297,7 +298,7 @@ def test_completed_key_on_partial_w_id(self): self.assertIsNone(new_key.name) def test_completed_key_on_partial_w_name(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) _NAME = 'NAME' new_key = key.completed_key(_NAME) self.assertIsNot(key, new_key) @@ -305,18 +306,18 @@ def test_completed_key_on_partial_w_name(self): self.assertEqual(new_key.name, _NAME) def test_completed_key_on_partial_w_invalid(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) self.assertRaises(ValueError, key.completed_key, object()) def test_completed_key_on_complete(self): - key = self._makeOne('KIND', 1234, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', 1234, project=self._DEFAULT_PROJECT) self.assertRaises(ValueError, key.completed_key, 5678) def test_to_protobuf_defaults(self): from google.cloud.datastore._generated import entity_pb2 _KIND = 'KIND' - key = self._makeOne(_KIND, project=self._DEFAULT_PROJECT) + key = self._make_one(_KIND, project=self._DEFAULT_PROJECT) pb = key.to_protobuf() self.assertIsInstance(pb, entity_pb2.Key) @@ -335,14 +336,14 @@ def test_to_protobuf_defaults(self): def test_to_protobuf_w_explicit_project(self): _PROJECT = 'PROJECT-ALT' - key = self._makeOne('KIND', project=_PROJECT) + key = self._make_one('KIND', project=_PROJECT) pb = key.to_protobuf() self.assertEqual(pb.partition_id.project_id, _PROJECT) def test_to_protobuf_w_explicit_namespace(self): _NAMESPACE = 'NAMESPACE' - key = self._makeOne('KIND', namespace=_NAMESPACE, - project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', namespace=_NAMESPACE, + project=self._DEFAULT_PROJECT) pb = key.to_protobuf() self.assertEqual(pb.partition_id.namespace_id, _NAMESPACE) @@ -351,8 +352,8 @@ def test_to_protobuf_w_explicit_path(self): _CHILD = 'CHILD' _ID = 1234 _NAME = 'NAME' - key = self._makeOne(_PARENT, _NAME, _CHILD, _ID, - project=self._DEFAULT_PROJECT) + key = self._make_one(_PARENT, _NAME, _CHILD, _ID, + project=self._DEFAULT_PROJECT) pb = key.to_protobuf() elems = list(pb.path) self.assertEqual(len(elems), 2) @@ -362,7 +363,7 @@ def test_to_protobuf_w_explicit_path(self): self.assertEqual(elems[1].id, _ID) def test_to_protobuf_w_no_kind(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) # Force the 'kind' to be unset. Maybe `to_protobuf` should fail # on this? The backend certainly will. key._path[-1].pop('kind') @@ -371,60 +372,60 @@ def test_to_protobuf_w_no_kind(self): self.assertEqual(pb.path[0].kind, '') def test_is_partial_no_name_or_id(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) self.assertTrue(key.is_partial) def test_is_partial_w_id(self): _ID = 1234 - key = self._makeOne('KIND', _ID, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', _ID, project=self._DEFAULT_PROJECT) self.assertFalse(key.is_partial) def test_is_partial_w_name(self): _NAME = 'NAME' - key = self._makeOne('KIND', _NAME, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', _NAME, project=self._DEFAULT_PROJECT) self.assertFalse(key.is_partial) def test_id_or_name_no_name_or_id(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) self.assertIsNone(key.id_or_name) def test_id_or_name_no_name_or_id_child(self): - key = self._makeOne('KIND1', 1234, 'KIND2', - project=self._DEFAULT_PROJECT) + key = self._make_one('KIND1', 1234, 'KIND2', + project=self._DEFAULT_PROJECT) self.assertIsNone(key.id_or_name) def test_id_or_name_w_id_only(self): _ID = 1234 - key = self._makeOne('KIND', _ID, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', _ID, project=self._DEFAULT_PROJECT) self.assertEqual(key.id_or_name, _ID) def test_id_or_name_w_name_only(self): _NAME = 'NAME' - key = self._makeOne('KIND', _NAME, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', _NAME, project=self._DEFAULT_PROJECT) self.assertEqual(key.id_or_name, _NAME) def test_parent_default(self): - key = self._makeOne('KIND', project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', project=self._DEFAULT_PROJECT) self.assertIsNone(key.parent) def test_parent_explicit_top_level(self): - key = self._makeOne('KIND', 1234, project=self._DEFAULT_PROJECT) + key = self._make_one('KIND', 1234, project=self._DEFAULT_PROJECT) self.assertIsNone(key.parent) def test_parent_explicit_nested(self): _PARENT_KIND = 'KIND1' _PARENT_ID = 1234 _PARENT_PATH = [{'kind': _PARENT_KIND, 'id': _PARENT_ID}] - key = self._makeOne(_PARENT_KIND, _PARENT_ID, 'KIND2', - project=self._DEFAULT_PROJECT) + key = self._make_one(_PARENT_KIND, _PARENT_ID, 'KIND2', + project=self._DEFAULT_PROJECT) self.assertEqual(key.parent.path, _PARENT_PATH) def test_parent_multiple_calls(self): _PARENT_KIND = 'KIND1' _PARENT_ID = 1234 _PARENT_PATH = [{'kind': _PARENT_KIND, 'id': _PARENT_ID}] - key = self._makeOne(_PARENT_KIND, _PARENT_ID, 'KIND2', - project=self._DEFAULT_PROJECT) + key = self._make_one(_PARENT_KIND, _PARENT_ID, 'KIND2', + project=self._DEFAULT_PROJECT) parent = key.parent self.assertEqual(parent.path, _PARENT_PATH) new_parent = key.parent diff --git a/datastore/unit_tests/test_query.py b/datastore/unit_tests/test_query.py index 7c2d2238410d..728dbc3dc63d 100644 --- a/datastore/unit_tests/test_query.py +++ b/datastore/unit_tests/test_query.py @@ -19,12 +19,13 @@ class TestQuery(unittest.TestCase): _PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.query import Query return Query - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _makeClient(self, connection=None): if connection is None: @@ -33,7 +34,7 @@ def _makeClient(self, connection=None): def test_ctor_defaults(self): client = self._makeClient() - query = self._makeOne(client) + query = self._make_one(client) self.assertIs(query._client, client) self.assertEqual(query.project, client.project) self.assertIsNone(query.kind) @@ -55,7 +56,7 @@ def test_ctor_explicit(self): PROJECTION = ['foo', 'bar', 'baz'] ORDER = ['foo', 'bar'] DISTINCT_ON = ['foo'] - query = self._makeOne( + query = self._make_one( client, kind=_KIND, project=_PROJECT, @@ -78,26 +79,26 @@ def test_ctor_explicit(self): def test_ctor_bad_projection(self): BAD_PROJECTION = object() - self.assertRaises(TypeError, self._makeOne, self._makeClient(), + self.assertRaises(TypeError, self._make_one, self._makeClient(), projection=BAD_PROJECTION) def test_ctor_bad_order(self): BAD_ORDER = object() - self.assertRaises(TypeError, self._makeOne, self._makeClient(), + self.assertRaises(TypeError, self._make_one, self._makeClient(), order=BAD_ORDER) def test_ctor_bad_distinct_on(self): BAD_DISTINCT_ON = object() - self.assertRaises(TypeError, self._makeOne, self._makeClient(), + self.assertRaises(TypeError, self._make_one, self._makeClient(), distinct_on=BAD_DISTINCT_ON) def test_ctor_bad_filters(self): FILTERS_CANT_UNPACK = [('one', 'two')] - self.assertRaises(ValueError, self._makeOne, self._makeClient(), + self.assertRaises(ValueError, self._make_one, self._makeClient(), filters=FILTERS_CANT_UNPACK) def test_namespace_setter_w_non_string(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) def _assign(val): query.namespace = val @@ -106,12 +107,12 @@ def _assign(val): def test_namespace_setter(self): _NAMESPACE = 'OTHER_NAMESPACE' - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.namespace = _NAMESPACE self.assertEqual(query.namespace, _NAMESPACE) def test_kind_setter_w_non_string(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) def _assign(val): query.kind = val @@ -120,21 +121,21 @@ def _assign(val): def test_kind_setter_wo_existing(self): _KIND = 'KIND' - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.kind = _KIND self.assertEqual(query.kind, _KIND) def test_kind_setter_w_existing(self): _KIND_BEFORE = 'KIND_BEFORE' _KIND_AFTER = 'KIND_AFTER' - query = self._makeOne(self._makeClient(), kind=_KIND_BEFORE) + query = self._make_one(self._makeClient(), kind=_KIND_BEFORE) self.assertEqual(query.kind, _KIND_BEFORE) query.kind = _KIND_AFTER self.assertEqual(query.project, self._PROJECT) self.assertEqual(query.kind, _KIND_AFTER) def test_ancestor_setter_w_non_key(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) def _assign(val): query.ancestor = val @@ -146,7 +147,7 @@ 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._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.add_filter('name', '=', _NAME) query.ancestor = key self.assertEqual(query.ancestor.path, key.path) @@ -154,22 +155,22 @@ 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._makeOne(client=self._makeClient(), ancestor=key) + query = self._make_one(client=self._makeClient(), ancestor=key) del query.ancestor self.assertIsNone(query.ancestor) def test_add_filter_setter_w_unknown_operator(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) self.assertRaises(ValueError, query.add_filter, 'firstname', '~~', 'John') def test_add_filter_w_known_operator(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.add_filter('firstname', '=', u'John') self.assertEqual(query.filters, [('firstname', '=', u'John')]) def test_add_filter_w_all_operators(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.add_filter('leq_prop', '<=', u'val1') query.add_filter('geq_prop', '>=', u'val2') query.add_filter('lt_prop', '<', u'val3') @@ -184,7 +185,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._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) other = Entity() other['firstname'] = u'John' other['lastname'] = u'Smith' @@ -192,14 +193,14 @@ def test_add_filter_w_known_operator_and_entity(self): self.assertEqual(query.filters, [('other', '=', other)]) def test_add_filter_w_whitespace_property_name(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) PROPERTY_NAME = ' property with lots of space ' query.add_filter(PROPERTY_NAME, '=', u'John') self.assertEqual(query.filters, [(PROPERTY_NAME, '=', u'John')]) def test_add_filter___key__valid_key(self): from google.cloud.datastore.key import Key - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) key = Key('Foo', project=self._PROJECT) query.add_filter('__key__', '=', key) self.assertEqual(query.filters, [('__key__', '=', key)]) @@ -207,40 +208,40 @@ 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._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.add_filter('__key__', '<', key) self.assertEqual(query.filters, [('__key__', '<', key)]) def test_filter___key__invalid_value(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) self.assertRaises(ValueError, query.add_filter, '__key__', '=', None) def test_projection_setter_empty(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.projection = [] self.assertEqual(query.projection, []) def test_projection_setter_string(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.projection = 'field1' self.assertEqual(query.projection, ['field1']) def test_projection_setter_non_empty(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.projection = ['field1', 'field2'] self.assertEqual(query.projection, ['field1', 'field2']) def test_projection_setter_multiple_calls(self): _PROJECTION1 = ['field1', 'field2'] _PROJECTION2 = ['field3'] - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.projection = _PROJECTION1 self.assertEqual(query.projection, _PROJECTION1) query.projection = _PROJECTION2 self.assertEqual(query.projection, _PROJECTION2) def test_keys_only(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.keys_only() self.assertEqual(query.projection, ['__key__']) @@ -248,7 +249,7 @@ def test_key_filter_defaults(self): from google.cloud.datastore.key import Key client = self._makeClient() - query = self._makeOne(client) + query = self._make_one(client) self.assertEqual(query.filters, []) key = Key('Kind', 1234, project='project') query.key_filter(key) @@ -258,51 +259,51 @@ def test_key_filter_explicit(self): from google.cloud.datastore.key import Key client = self._makeClient() - query = self._makeOne(client) + query = self._make_one(client) self.assertEqual(query.filters, []) key = Key('Kind', 1234, project='project') query.key_filter(key, operator='>') self.assertEqual(query.filters, [('__key__', '>', key)]) def test_order_setter_empty(self): - query = self._makeOne(self._makeClient(), order=['foo', '-bar']) + query = self._make_one(self._makeClient(), order=['foo', '-bar']) query.order = [] self.assertEqual(query.order, []) def test_order_setter_string(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.order = 'field' self.assertEqual(query.order, ['field']) def test_order_setter_single_item_list_desc(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.order = ['-field'] self.assertEqual(query.order, ['-field']) def test_order_setter_multiple(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.order = ['foo', '-bar'] self.assertEqual(query.order, ['foo', '-bar']) def test_distinct_on_setter_empty(self): - query = self._makeOne(self._makeClient(), distinct_on=['foo', 'bar']) + query = self._make_one(self._makeClient(), distinct_on=['foo', 'bar']) query.distinct_on = [] self.assertEqual(query.distinct_on, []) def test_distinct_on_setter_string(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.distinct_on = 'field1' self.assertEqual(query.distinct_on, ['field1']) def test_distinct_on_setter_non_empty(self): - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.distinct_on = ['field1', 'field2'] self.assertEqual(query.distinct_on, ['field1', 'field2']) def test_distinct_on_multiple_calls(self): _DISTINCT_ON1 = ['field1', 'field2'] _DISTINCT_ON2 = ['field3'] - query = self._makeOne(self._makeClient()) + query = self._make_one(self._makeClient()) query.distinct_on = _DISTINCT_ON1 self.assertEqual(query.distinct_on, _DISTINCT_ON1) query.distinct_on = _DISTINCT_ON2 @@ -313,7 +314,7 @@ def test_fetch_defaults_w_client_attr(self): connection = _Connection() client = self._makeClient(connection) - query = self._makeOne(client) + query = self._make_one(client) iterator = query.fetch() self.assertIsInstance(iterator, Iterator) @@ -328,7 +329,7 @@ def test_fetch_w_explicit_client(self): connection = _Connection() client = self._makeClient(connection) other_client = self._makeClient(connection) - query = self._makeOne(client) + query = self._make_one(client) iterator = query.fetch(limit=7, offset=8, client=other_client) self.assertIsInstance(iterator, Iterator) self.assertIs(iterator._query, query) @@ -339,17 +340,18 @@ def test_fetch_w_explicit_client(self): class TestIterator(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.query import Iterator return Iterator - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor_defaults(self): query = object() client = object() - iterator = self._makeOne(query, client) + iterator = self._make_one(query, client) self.assertFalse(iterator._started) self.assertIs(iterator.client, client) @@ -370,7 +372,7 @@ def test_constructor_explicit(self): offset = 9 start_cursor = b'8290\xff' end_cursor = b'so20rc\ta' - iterator = self._makeOne( + iterator = self._make_one( query, client, limit=limit, offset=offset, start_cursor=start_cursor, end_cursor=end_cursor) @@ -392,7 +394,7 @@ def test__build_protobuf_empty(self): client = _Client(None, None) query = Query(client) - iterator = self._makeOne(query, client) + iterator = self._make_one(query, client) pb = iterator._build_protobuf() expected_pb = query_pb2.Query() @@ -410,7 +412,7 @@ def test__build_protobuf_all_values(self): start_cursor = 'abcd' end_bytes = b'\xc3\x1c\xb3' end_cursor = 'wxyz' - iterator = self._makeOne( + iterator = self._make_one( query, client, limit=limit, offset=offset, start_cursor=start_cursor, end_cursor=end_cursor) self.assertEqual(iterator.max_results, limit) @@ -429,8 +431,8 @@ def test__build_protobuf_all_values(self): def test__process_query_results(self): from google.cloud.datastore._generated import query_pb2 - iterator = self._makeOne(None, None, - end_cursor='abcd') + iterator = self._make_one(None, None, + end_cursor='abcd') self.assertIsNotNone(iterator._end_cursor) entity_pbs = object() @@ -450,8 +452,8 @@ def test__process_query_results(self): def test__process_query_results_done(self): from google.cloud.datastore._generated import query_pb2 - iterator = self._makeOne(None, None, - end_cursor='abcd') + iterator = self._make_one(None, None, + end_cursor='abcd') self.assertIsNotNone(iterator._end_cursor) entity_pbs = object() @@ -468,7 +470,7 @@ def test__process_query_results_done(self): self.assertFalse(iterator._more_results) def test__process_query_results_bad_enum(self): - iterator = self._makeOne(None, None) + iterator = self._make_one(None, None) more_results_enum = 999 with self.assertRaises(ValueError): iterator._process_query_results( @@ -486,7 +488,7 @@ def test__next_page(self): project = 'prujekt' client = _Client(project, connection) query = Query(client) - iterator = self._makeOne(query, client) + iterator = self._make_one(query, client) page = iterator._next_page() self.assertIsInstance(page, Page) @@ -505,7 +507,7 @@ def test__next_page_no_more(self): connection = _Connection() client = _Client(None, connection) query = Query(client) - iterator = self._makeOne(query, client) + iterator = self._make_one(query, client) iterator._more_results = False page = iterator._next_page() @@ -515,7 +517,7 @@ def test__next_page_no_more(self): class Test__item_to_entity(unittest.TestCase): - def _callFUT(self, iterator, entity_pb): + def _call_fut(self, iterator, entity_pb): from google.cloud.datastore.query import _item_to_entity return _item_to_entity(iterator, entity_pb) @@ -532,21 +534,21 @@ def mocked(entity_pb): entity_pb = object() with _Monkey(helpers, entity_from_protobuf=mocked): - self.assertIs(result, self._callFUT(None, entity_pb)) + self.assertIs(result, self._call_fut(None, entity_pb)) self.assertEqual(entities, [entity_pb]) class Test__pb_from_query(unittest.TestCase): - def _callFUT(self, query): + def _call_fut(self, query): from google.cloud.datastore.query import _pb_from_query return _pb_from_query(query) def test_empty(self): from google.cloud.datastore._generated import query_pb2 - pb = self._callFUT(_Query()) + pb = self._call_fut(_Query()) self.assertEqual(list(pb.projection), []) self.assertEqual(list(pb.kind), []) self.assertEqual(list(pb.order), []) @@ -562,12 +564,12 @@ def test_empty(self): self.assertEqual(pb.offset, 0) def test_projection(self): - pb = self._callFUT(_Query(projection=['a', 'b', 'c'])) + pb = self._call_fut(_Query(projection=['a', 'b', 'c'])) self.assertEqual([item.property.name for item in pb.projection], ['a', 'b', 'c']) def test_kind(self): - pb = self._callFUT(_Query(kind='KIND')) + pb = self._call_fut(_Query(kind='KIND')) self.assertEqual([item.name for item in pb.kind], ['KIND']) def test_ancestor(self): @@ -575,7 +577,7 @@ def test_ancestor(self): from google.cloud.datastore._generated import query_pb2 ancestor = Key('Ancestor', 123, project='PROJECT') - pb = self._callFUT(_Query(ancestor=ancestor)) + pb = self._call_fut(_Query(ancestor=ancestor)) cfilter = pb.filter.composite_filter self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND) self.assertEqual(len(cfilter.filters), 1) @@ -591,7 +593,7 @@ def test_filter(self): query.OPERATORS = { '=': query_pb2.PropertyFilter.EQUAL, } - pb = self._callFUT(query) + pb = self._call_fut(query) cfilter = pb.filter.composite_filter self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND) self.assertEqual(len(cfilter.filters), 1) @@ -608,7 +610,7 @@ def test_filter_key(self): query.OPERATORS = { '=': query_pb2.PropertyFilter.EQUAL, } - pb = self._callFUT(query) + pb = self._call_fut(query) cfilter = pb.filter.composite_filter self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND) self.assertEqual(len(cfilter.filters), 1) @@ -620,7 +622,7 @@ def test_filter_key(self): def test_order(self): from google.cloud.datastore._generated import query_pb2 - pb = self._callFUT(_Query(order=['a', '-b', 'c'])) + pb = self._call_fut(_Query(order=['a', '-b', 'c'])) self.assertEqual([item.property.name for item in pb.order], ['a', 'b', 'c']) self.assertEqual([item.direction for item in pb.order], @@ -629,7 +631,7 @@ def test_order(self): query_pb2.PropertyOrder.ASCENDING]) def test_distinct_on(self): - pb = self._callFUT(_Query(distinct_on=['a', 'b', 'c'])) + pb = self._call_fut(_Query(distinct_on=['a', 'b', 'c'])) self.assertEqual([item.name for item in pb.distinct_on], ['a', 'b', 'c']) diff --git a/datastore/unit_tests/test_transaction.py b/datastore/unit_tests/test_transaction.py index 8b28ee0cb277..46fbf21320e5 100644 --- a/datastore/unit_tests/test_transaction.py +++ b/datastore/unit_tests/test_transaction.py @@ -17,12 +17,13 @@ class TestTransaction(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.datastore.transaction import Transaction return Transaction - def _makeOne(self, client, **kw): - return self._getTargetClass()(client, **kw) + def _make_one(self, client, **kw): + return self._get_target_class()(client, **kw) def test_ctor_defaults(self): from google.cloud.datastore._generated import datastore_pb2 @@ -30,11 +31,11 @@ def test_ctor_defaults(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) self.assertEqual(xact.project, _PROJECT) self.assertEqual(xact.connection, connection) self.assertIsNone(xact.id) - self.assertEqual(xact._status, self._getTargetClass()._INITIAL) + self.assertEqual(xact._status, self._get_target_class()._INITIAL) self.assertIsInstance(xact._commit_request, datastore_pb2.CommitRequest) self.assertIs(xact.mutations, xact._commit_request.mutations) @@ -44,8 +45,8 @@ def test_current(self): _PROJECT = 'PROJECT' connection = _Connection() client = _Client(_PROJECT, connection) - xact1 = self._makeOne(client) - xact2 = self._makeOne(client) + xact1 = self._make_one(client) + xact2 = self._make_one(client) self.assertIsNone(xact1.current()) self.assertIsNone(xact2.current()) with xact1: @@ -69,7 +70,7 @@ def test_begin(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact.begin() self.assertEqual(xact.id, 234) self.assertEqual(connection._begun, _PROJECT) @@ -78,7 +79,7 @@ def test_begin_tombstoned(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact.begin() self.assertEqual(xact.id, 234) self.assertEqual(connection._begun, _PROJECT) @@ -92,7 +93,7 @@ def test_begin_w_begin_transaction_failure(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) connection._side_effect = RuntimeError with self.assertRaises(RuntimeError): @@ -105,7 +106,7 @@ def test_rollback(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact.begin() xact.rollback() self.assertIsNone(xact.id) @@ -115,7 +116,7 @@ def test_commit_no_partial_keys(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact._commit_request = commit_request = object() xact.begin() xact.commit() @@ -130,7 +131,7 @@ def test_commit_w_partial_keys(self): connection = _Connection(234) connection._completed_keys = [_make_key(_KIND, _ID, _PROJECT)] client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact.begin() entity = _Entity() xact.put(entity) @@ -145,7 +146,7 @@ def test_context_manager_no_raise(self): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact._commit_request = commit_request = object() with xact: self.assertEqual(xact.id, 234) @@ -162,7 +163,7 @@ class Foo(Exception): _PROJECT = 'PROJECT' connection = _Connection(234) client = _Client(_PROJECT, connection) - xact = self._makeOne(client) + xact = self._make_one(client) xact._mutation = object() try: with xact: diff --git a/dns/unit_tests/test_changes.py b/dns/unit_tests/test_changes.py index 4c5090469521..40a6f30b5d4e 100644 --- a/dns/unit_tests/test_changes.py +++ b/dns/unit_tests/test_changes.py @@ -20,12 +20,13 @@ class TestChanges(unittest.TestCase): ZONE_NAME = 'example.com' CHANGES_NAME = 'changeset_id' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.dns.changes import Changes return Changes - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _setUpConstants(self): from google.cloud._helpers import UTC @@ -82,7 +83,7 @@ def _verifyResourceProperties(self, changes, resource, zone): def test_ctor(self): zone = _Zone() - changes = self._makeOne(zone) + changes = self._make_one(zone) self.assertIs(changes.zone, zone) self.assertIsNone(changes.name) @@ -97,7 +98,7 @@ def test_from_api_repr_missing_additions_deletions(self): del RESOURCE['additions'] del RESOURCE['deletions'] zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() changes = klass.from_api_repr(RESOURCE, zone=zone) @@ -107,7 +108,7 @@ def test_from_api_repr(self): self._setUpConstants() RESOURCE = self._makeResource() zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() changes = klass.from_api_repr(RESOURCE, zone=zone) @@ -115,19 +116,19 @@ def test_from_api_repr(self): def test_name_setter_bad_value(self): zone = _Zone() - changes = self._makeOne(zone) + changes = self._make_one(zone) with self.assertRaises(ValueError): changes.name = 12345 def test_name_setter(self): zone = _Zone() - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.name = 'NAME' self.assertEqual(changes.name, 'NAME') def test_add_record_set_invalid_value(self): zone = _Zone() - changes = self._makeOne(zone) + changes = self._make_one(zone) with self.assertRaises(ValueError): changes.add_record_set(object()) @@ -135,7 +136,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._makeOne(zone) + changes = self._make_one(zone) rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600, ['www.example.com'], zone) changes.add_record_set(rrs) @@ -143,7 +144,7 @@ def test_add_record_set(self): def test_delete_record_set_invalid_value(self): zone = _Zone() - changes = self._makeOne(zone) + changes = self._make_one(zone) with self.assertRaises(ValueError): changes.delete_record_set(object()) @@ -151,7 +152,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._makeOne(zone) + changes = self._make_one(zone) rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600, ['www.example.com'], zone) changes.delete_record_set(rrs) @@ -163,7 +164,7 @@ def test_create_wo_additions_or_deletions(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) zone = _Zone(client) - changes = self._makeOne(zone) + changes = self._make_one(zone) with self.assertRaises(ValueError): changes.create() @@ -179,7 +180,7 @@ def test_create_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) zone = _Zone(client) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.add_record_set(ResourceRecordSet( 'test.example.com', 'CNAME', 3600, ['www.example.com'], zone)) changes.delete_record_set(ResourceRecordSet( @@ -209,7 +210,7 @@ def test_create_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) zone = _Zone(client1) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.add_record_set(ResourceRecordSet( 'test.example.com', 'CNAME', 3600, ['www.example.com'], zone)) changes.delete_record_set(ResourceRecordSet( @@ -236,7 +237,7 @@ def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) zone = _Zone(client) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.name = self.CHANGES_NAME self.assertFalse(changes.exists()) @@ -255,7 +256,7 @@ def test_exists_hit_w_alternate_client(self): conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) zone = _Zone(client1) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.name = self.CHANGES_NAME self.assertTrue(changes.exists(client=client2)) @@ -275,7 +276,7 @@ def test_reload_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) zone = _Zone(client) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.name = self.CHANGES_NAME changes.reload() @@ -296,7 +297,7 @@ def test_reload_w_alternate_client(self): conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) zone = _Zone(client1) - changes = self._makeOne(zone) + changes = self._make_one(zone) changes.name = self.CHANGES_NAME changes.reload(client=client2) diff --git a/dns/unit_tests/test_client.py b/dns/unit_tests/test_client.py index 3a81e1a01754..0f849ed9dbb4 100644 --- a/dns/unit_tests/test_client.py +++ b/dns/unit_tests/test_client.py @@ -20,19 +20,20 @@ class TestClient(unittest.TestCase): PROJECT = 'PROJECT' ZONE_NAME = 'zone-name' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.dns.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from google.cloud.dns.connection import Connection creds = _Credentials() http = object() - client = self._makeOne(project=self.PROJECT, credentials=creds, - http=http) + client = self._make_one(project=self.PROJECT, credentials=creds, + http=http) self.assertIsInstance(client.connection, Connection) self.assertIs(client.connection.credentials, creds) self.assertIs(client.connection.http, http) @@ -58,7 +59,7 @@ def test_quotas_defaults(self): CONVERTED = {key: int(value) for key, value in DATA['quota'].items()} creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) conn = client.connection = _Connection(DATA) quotas = client.quotas() @@ -93,7 +94,7 @@ def test_quotas_w_kind_key(self): WITH_KIND = {'quota': DATA['quota'].copy()} WITH_KIND['quota']['kind'] = 'dns#quota' creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) conn = client.connection = _Connection(WITH_KIND) quotas = client.quotas() @@ -130,7 +131,7 @@ def test_list_zones_defaults(self): ] } creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_zones() @@ -175,7 +176,7 @@ def test_list_zones_explicit(self): ] } creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) conn = client.connection = _Connection(DATA) iterator = client.list_zones(max_results=3, page_token=TOKEN) @@ -203,7 +204,7 @@ def test_zone_explicit(self): DESCRIPTION = 'DESCRIPTION' DNS_NAME = 'test.example.com' creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) zone = client.zone(self.ZONE_NAME, DNS_NAME, DESCRIPTION) self.assertIsInstance(zone, ManagedZone) self.assertEqual(zone.name, self.ZONE_NAME) @@ -215,7 +216,7 @@ def test_zone_w_dns_name_wo_description(self): from google.cloud.dns.zone import ManagedZone DNS_NAME = 'test.example.com' creds = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) zone = client.zone(self.ZONE_NAME, DNS_NAME) self.assertIsInstance(zone, ManagedZone) self.assertEqual(zone.name, self.ZONE_NAME) @@ -226,7 +227,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 = _Credentials() - client = self._makeOne(self.PROJECT, creds) + client = self._make_one(self.PROJECT, creds) zone = client.zone(self.ZONE_NAME) self.assertIsInstance(zone, ManagedZone) self.assertEqual(zone.name, self.ZONE_NAME) diff --git a/dns/unit_tests/test_connection.py b/dns/unit_tests/test_connection.py index c054eb1e63ad..88f1aa93b577 100644 --- a/dns/unit_tests/test_connection.py +++ b/dns/unit_tests/test_connection.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.dns.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, 'dns', @@ -37,7 +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._makeOne() + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL) diff --git a/dns/unit_tests/test_resource_record_set.py b/dns/unit_tests/test_resource_record_set.py index ace2e755e2d1..6b71bd5cea67 100644 --- a/dns/unit_tests/test_resource_record_set.py +++ b/dns/unit_tests/test_resource_record_set.py @@ -17,18 +17,19 @@ class TestResourceRecordSet(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.dns.resource_record_set import ResourceRecordSet return ResourceRecordSet - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): zone = _Zone() - rrs = self._makeOne('test.example.com', 'CNAME', 3600, - ['www.example.com'], zone) + rrs = self._make_one('test.example.com', 'CNAME', 3600, + ['www.example.com'], zone) self.assertEqual(rrs.name, 'test.example.com') self.assertEqual(rrs.record_type, 'CNAME') @@ -38,7 +39,7 @@ def test_ctor(self): def test_from_api_repr_missing_rrdatas(self): zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr({'name': 'test.example.com', @@ -47,7 +48,7 @@ def test_from_api_repr_missing_rrdatas(self): def test_from_api_repr_missing_ttl(self): zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr({'name': 'test.example.com', @@ -56,7 +57,7 @@ def test_from_api_repr_missing_ttl(self): def test_from_api_repr_missing_type(self): zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr({'name': 'test.example.com', @@ -65,7 +66,7 @@ def test_from_api_repr_missing_type(self): def test_from_api_repr_missing_name(self): zone = _Zone() - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr({'type': 'CNAME', @@ -81,7 +82,7 @@ def test_from_api_repr_bare(self): 'ttl': '3600', 'rrdatas': ['www.example.com'], } - klass = self._getTargetClass() + klass = self._get_target_class() rrs = klass.from_api_repr(RESOURCE, zone=zone) self.assertEqual(rrs.name, 'test.example.com') self.assertEqual(rrs.record_type, 'CNAME') diff --git a/dns/unit_tests/test_zone.py b/dns/unit_tests/test_zone.py index 63b34339bc7e..681da61d2420 100644 --- a/dns/unit_tests/test_zone.py +++ b/dns/unit_tests/test_zone.py @@ -21,12 +21,13 @@ class TestManagedZone(unittest.TestCase): DESCRIPTION = 'ZONE DESCRIPTION' DNS_NAME = 'test.example.com' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.dns.zone import ManagedZone return ManagedZone - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _setUpConstants(self): import datetime @@ -85,7 +86,7 @@ def _verifyResourceProperties(self, zone, resource): self.assertEqual(zone.name_server_set, resource.get('nameServerSet')) def test_ctor_defaults(self): - zone = self._makeOne(self.ZONE_NAME) + zone = self._make_one(self.ZONE_NAME) self.assertEqual(zone.name, self.ZONE_NAME) self.assertIsNone(zone.dns_name) self.assertIsNone(zone._client) @@ -102,7 +103,7 @@ def test_ctor_defaults(self): def test_ctor_wo_description(self): client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) self.assertEqual(zone.name, self.ZONE_NAME) self.assertEqual(zone.dns_name, self.DNS_NAME) self.assertIs(zone._client, client) @@ -117,7 +118,7 @@ def test_ctor_wo_description(self): def test_ctor_explicit(self): DESCRIPTION = 'DESCRIPTION' client = _Client(self.PROJECT) - zone = self._makeOne( + zone = self._make_one( self.ZONE_NAME, self.DNS_NAME, client, DESCRIPTION) self.assertEqual(zone.name, self.ZONE_NAME) self.assertEqual(zone.dns_name, self.DNS_NAME) @@ -134,7 +135,7 @@ def test_from_api_repr_missing_identity(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = {} - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(KeyError): klass.from_api_repr(RESOURCE, client=client) @@ -145,7 +146,7 @@ def test_from_api_repr_bare(self): 'name': self.ZONE_NAME, 'dnsName': self.DNS_NAME, } - klass = self._getTargetClass() + klass = self._get_target_class() zone = klass.from_api_repr(RESOURCE, client=client) self.assertIs(zone._client, client) self._verifyResourceProperties(zone, RESOURCE) @@ -154,32 +155,32 @@ def test_from_api_repr_w_properties(self): self._setUpConstants() client = _Client(self.PROJECT) RESOURCE = self._makeResource() - klass = self._getTargetClass() + klass = self._get_target_class() zone = klass.from_api_repr(RESOURCE, client=client) self.assertIs(zone._client, client) self._verifyResourceProperties(zone, RESOURCE) def test_description_setter_bad_value(self): client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) with self.assertRaises(ValueError): zone.description = 12345 def test_description_setter(self): client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) zone.description = 'DESCRIPTION' self.assertEqual(zone.description, 'DESCRIPTION') def test_name_server_set_setter_bad_value(self): client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) with self.assertRaises(ValueError): zone.name_server_set = 12345 def test_name_server_set_setter(self): client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) zone.name_server_set = 'NAME_SERVER_SET' self.assertEqual(zone.name_server_set, 'NAME_SERVER_SET') @@ -190,7 +191,7 @@ def test_resource_record_set(self): TTL = 3600 RRDATAS = ['www.example.com'] client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) rrs = zone.resource_record_set(RRS_NAME, RRS_TYPE, TTL, RRDATAS) self.assertIsInstance(rrs, ResourceRecordSet) self.assertEqual(rrs.name, RRS_NAME) @@ -202,7 +203,7 @@ def test_resource_record_set(self): def test_changes(self): from google.cloud.dns.changes import Changes client = _Client(self.PROJECT) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) changes = zone.changes() self.assertIsInstance(changes, Changes) self.assertIs(changes.zone, zone) @@ -212,7 +213,7 @@ def test_create_w_bound_client(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) zone.create() @@ -239,7 +240,7 @@ def test_create_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) zone.name_server_set = NAME_SERVER_SET zone.description = DESCRIPTION @@ -272,7 +273,7 @@ def _api_request(**kw): conn = _Connection() conn.api_request = _api_request client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, client=client) + zone = self._make_one(self.ZONE_NAME, client=client) with self.assertRaises(BadRequest): zone.create() @@ -297,7 +298,7 @@ def test_create_w_missing_output_properties(self): self.WHEN = None conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) zone.create() @@ -317,7 +318,7 @@ def test_exists_miss_w_bound_client(self): PATH = 'projects/%s/managedZones/%s' % (self.PROJECT, self.ZONE_NAME) conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) self.assertFalse(zone.exists()) @@ -333,7 +334,7 @@ def test_exists_hit_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) self.assertTrue(zone.exists(client=client2)) @@ -349,7 +350,7 @@ def test_reload_w_bound_client(self): RESOURCE = self._makeResource() conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, client=client) + zone = self._make_one(self.ZONE_NAME, client=client) zone.reload() @@ -368,7 +369,7 @@ def test_reload_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) zone.reload(client=client2) @@ -383,7 +384,7 @@ def test_delete_w_bound_client(self): PATH = 'projects/%s/managedZones/%s' % (self.PROJECT, self.ZONE_NAME) conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) zone.delete() @@ -398,7 +399,7 @@ def test_delete_w_alternate_client(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) zone.delete(client=client2) @@ -439,7 +440,7 @@ def test_list_resource_record_sets_defaults(self): } conn = _Connection(DATA) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) iterator = zone.list_resource_record_sets() self.assertIs(zone, iterator.zone) @@ -493,7 +494,7 @@ def test_list_resource_record_sets_explicit(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(DATA) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) iterator = zone.list_resource_record_sets( max_results=3, page_token=TOKEN, client=client2) @@ -568,7 +569,7 @@ def test_list_changes_defaults(self): conn = _Connection(data) client = _Client(project=self.PROJECT, connection=conn) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client) iterator = zone.list_changes() self.assertIs(zone, iterator.zone) @@ -622,7 +623,7 @@ def test_list_changes_explicit(self): client1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(data) client2 = _Client(project=self.PROJECT, connection=conn2) - zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client1) + zone = self._make_one(self.ZONE_NAME, self.DNS_NAME, client1) page_token = 'TOKEN' iterator = zone.list_changes( diff --git a/error_reporting/unit_tests/test_client.py b/error_reporting/unit_tests/test_client.py index a3a54f0c89dc..a94919ecaacc 100644 --- a/error_reporting/unit_tests/test_client.py +++ b/error_reporting/unit_tests/test_client.py @@ -18,7 +18,8 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.error_reporting.client import Client return Client @@ -26,8 +27,8 @@ def _getHttpContext(self): from google.cloud.error_reporting.client import HTTPContext return HTTPContext - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _makeHTTP(self, *args, **kw): return self._getHttpContext()(*args, **kw) @@ -38,24 +39,24 @@ def _makeHTTP(self, *args, **kw): def test_ctor_default(self): CREDENTIALS = _Credentials() - target = self._makeOne(project=self.PROJECT, - credentials=CREDENTIALS) + target = self._make_one(project=self.PROJECT, + credentials=CREDENTIALS) self.assertEquals(target.service, target.DEFAULT_SERVICE) self.assertEquals(target.version, None) def test_ctor_params(self): CREDENTIALS = _Credentials() - target = self._makeOne(project=self.PROJECT, - credentials=CREDENTIALS, - service=self.SERVICE, - version=self.VERSION) + target = self._make_one(project=self.PROJECT, + credentials=CREDENTIALS, + service=self.SERVICE, + version=self.VERSION) self.assertEquals(target.service, self.SERVICE) self.assertEquals(target.version, self.VERSION) def test_report_exception(self): CREDENTIALS = _Credentials() - target = self._makeOne(project=self.PROJECT, - credentials=CREDENTIALS) + target = self._make_one(project=self.PROJECT, + credentials=CREDENTIALS) logger = _Logger() target.logging_client.logger = lambda _: logger @@ -76,10 +77,10 @@ def test_report_exception_with_service_version_in_constructor(self): CREDENTIALS = _Credentials() SERVICE = "notdefault" VERSION = "notdefaultversion" - target = self._makeOne(project=self.PROJECT, - credentials=CREDENTIALS, - service=SERVICE, - version=VERSION) + target = self._make_one(project=self.PROJECT, + credentials=CREDENTIALS, + service=SERVICE, + version=VERSION) logger = _Logger() target.logging_client.logger = lambda _: logger @@ -109,8 +110,8 @@ def test_report_exception_with_service_version_in_constructor(self): def test_report(self): CREDENTIALS = _Credentials() - target = self._makeOne(project=self.PROJECT, - credentials=CREDENTIALS) + target = self._make_one(project=self.PROJECT, + credentials=CREDENTIALS) logger = _Logger() target.logging_client.logger = lambda _: logger diff --git a/language/unit_tests/test_client.py b/language/unit_tests/test_client.py index 8b603cb8d832..95c77ad32fd5 100644 --- a/language/unit_tests/test_client.py +++ b/language/unit_tests/test_client.py @@ -17,19 +17,20 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from google.cloud.language.connection import Connection creds = _Credentials() http = object() - client = self._makeOne(credentials=creds, http=http) + client = self._make_one(credentials=creds, http=http) self.assertIsInstance(client.connection, Connection) self.assertIs(client.connection.credentials, creds) self.assertIs(client.connection.http, http) @@ -38,7 +39,7 @@ def test_document_from_text_factory(self): from google.cloud.language.document import Document creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) content = 'abc' language = 'es' @@ -53,7 +54,7 @@ def test_document_from_text_factory(self): def test_document_from_text_factory_failure(self): creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) with self.assertRaises(TypeError): client.document_from_text('abc', doc_type='foo') @@ -62,7 +63,7 @@ def test_document_from_html_factory(self): from google.cloud.language.document import Document creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) content = 'abc' language = 'ja' @@ -77,7 +78,7 @@ def test_document_from_html_factory(self): def test_document_from_html_factory_failure(self): creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) with self.assertRaises(TypeError): client.document_from_html('abc', doc_type='foo') @@ -86,7 +87,7 @@ def test_document_from_url_factory(self): from google.cloud.language.document import Document creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) gcs_url = 'gs://my-text-bucket/sentiment-me.txt' document = client.document_from_url(gcs_url) @@ -101,7 +102,7 @@ def test_document_from_url_factory_explicit(self): from google.cloud.language.document import Encoding creds = _Credentials() - client = self._makeOne(credentials=creds, http=object()) + client = self._make_one(credentials=creds, http=object()) encoding = Encoding.UTF32 gcs_url = 'gs://my-text-bucket/sentiment-me.txt' diff --git a/language/unit_tests/test_connection.py b/language/unit_tests/test_connection.py index 694ec5ba3693..534582002292 100644 --- a/language/unit_tests/test_connection.py +++ b/language/unit_tests/test_connection.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url(self): - conn = self._makeOne() + conn = self._make_one() uri = '/'.join([ conn.API_BASE_URL, conn.API_VERSION, diff --git a/language/unit_tests/test_document.py b/language/unit_tests/test_document.py index 836be446ea08..db43af5e81ca 100644 --- a/language/unit_tests/test_document.py +++ b/language/unit_tests/test_document.py @@ -97,19 +97,20 @@ def _get_entities(include_entities): class TestDocument(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.document import Document return Document - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor_defaults(self): import google.cloud.language.document as MUT client = object() content = 'abc' - document = self._makeOne(client, content) + document = self._make_one(client, content) self.assertIs(document.client, client) self.assertEqual(document.content, content) self.assertIsNone(document.gcs_url) @@ -123,10 +124,10 @@ def test_constructor_explicit(self): client = object() gcs_url = 'gs://some-bucket/some-obj.html' language = 'ja' - document = self._makeOne(client, gcs_url=gcs_url, - doc_type=MUT.Document.HTML, - language=language, - encoding=MUT.Encoding.UTF32) + document = self._make_one(client, gcs_url=gcs_url, + doc_type=MUT.Document.HTML, + language=language, + encoding=MUT.Encoding.UTF32) self.assertIs(document.client, client) self.assertIsNone(document.content) self.assertEqual(document.gcs_url, gcs_url) @@ -136,17 +137,17 @@ def test_constructor_explicit(self): def test_constructor_no_text(self): with self.assertRaises(ValueError): - self._makeOne(None, content=None, gcs_url=None) + self._make_one(None, content=None, gcs_url=None) def test_constructor_text_and_gcs(self): with self.assertRaises(ValueError): - self._makeOne(None, content='abc', - gcs_url='gs://some-bucket/some-obj.txt') + self._make_one(None, content='abc', + gcs_url='gs://some-bucket/some-obj.txt') def test__to_dict_with_content(self): - klass = self._getTargetClass() + klass = self._get_target_class() content = 'Hello World' - document = self._makeOne(None, content=content) + document = self._make_one(None, content=content) info = document._to_dict() self.assertEqual(info, { 'content': content, @@ -155,9 +156,9 @@ def test__to_dict_with_content(self): }) def test__to_dict_with_gcs(self): - klass = self._getTargetClass() + klass = self._get_target_class() gcs_url = 'gs://some-bucket/some-obj.html' - document = self._makeOne(None, gcs_url=gcs_url) + document = self._make_one(None, gcs_url=gcs_url) info = document._to_dict() self.assertEqual(info, { 'gcsContentUri': gcs_url, @@ -166,8 +167,8 @@ def test__to_dict_with_gcs(self): }) def test__to_dict_with_no_content(self): - klass = self._getTargetClass() - document = self._makeOne(None, content='') + klass = self._get_target_class() + document = self._make_one(None, content='') document.content = None # Manually unset the content. info = document._to_dict() self.assertEqual(info, { @@ -230,7 +231,7 @@ def test_analyze_entities(self): } connection = _Connection(response) client = _Client(connection=connection) - document = self._makeOne(client, content) + document = self._make_one(client, content) entities = document.analyze_entities() self.assertEqual(len(entities), 2) @@ -267,7 +268,7 @@ def test_analyze_sentiment(self): } connection = _Connection(response) client = _Client(connection=connection) - document = self._makeOne(client, content) + document = self._make_one(client, content) sentiment = document.analyze_sentiment() self._verify_sentiment(sentiment, polarity, magnitude) @@ -325,7 +326,7 @@ def _annotate_text_helper(self, include_sentiment, connection = _Connection(response) client = _Client(connection=connection) - document = self._makeOne(client, ANNOTATE_CONTENT) + document = self._make_one(client, ANNOTATE_CONTENT) annotations = document.annotate_text( include_syntax=include_syntax, include_entities=include_entities, diff --git a/language/unit_tests/test_entity.py b/language/unit_tests/test_entity.py index 33ea6d8fa1df..b595220f00bf 100644 --- a/language/unit_tests/test_entity.py +++ b/language/unit_tests/test_entity.py @@ -17,12 +17,13 @@ class TestEntity(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.entity import Entity return Entity - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor_defaults(self): name = 'Italian' @@ -33,8 +34,8 @@ def test_constructor_defaults(self): metadata.update(base_metadata) salience = 0.19960518 mentions = ['Italian'] - entity = self._makeOne(name, entity_type, metadata, - salience, mentions) + entity = self._make_one(name, entity_type, metadata, + salience, mentions) self.assertEqual(entity.name, name) self.assertEqual(entity.entity_type, entity_type) self.assertEqual(entity.wikipedia_url, wiki_url) @@ -43,7 +44,7 @@ def test_constructor_defaults(self): self.assertEqual(entity.mentions, mentions) def test_from_api_repr(self): - klass = self._getTargetClass() + klass = self._get_target_class() name = 'Italy' entity_type = 'LOCATION' salience = 0.223 diff --git a/language/unit_tests/test_sentiment.py b/language/unit_tests/test_sentiment.py index 356e7f781311..de545faca848 100644 --- a/language/unit_tests/test_sentiment.py +++ b/language/unit_tests/test_sentiment.py @@ -17,22 +17,23 @@ class TestSentiment(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.sentiment import Sentiment return Sentiment - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): polarity = 1 magnitude = 2.3 - sentiment = self._makeOne(polarity, magnitude) + sentiment = self._make_one(polarity, magnitude) self.assertEqual(sentiment.polarity, polarity) self.assertEqual(sentiment.magnitude, magnitude) def test_from_api_repr(self): - klass = self._getTargetClass() + klass = self._get_target_class() polarity = -1 magnitude = 5.55 payload = { diff --git a/language/unit_tests/test_syntax.py b/language/unit_tests/test_syntax.py index 5f738fc56069..da6f09e54de4 100644 --- a/language/unit_tests/test_syntax.py +++ b/language/unit_tests/test_syntax.py @@ -17,12 +17,13 @@ class TestPartOfSpeech(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.syntax import PartOfSpeech return PartOfSpeech def test_reverse(self): - klass = self._getTargetClass() + klass = self._get_target_class() for attr in dir(klass): if attr.startswith('_'): continue @@ -35,12 +36,13 @@ def test_reverse(self): class TestToken(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.syntax import Token return Token - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): from google.cloud.language.syntax import PartOfSpeech @@ -51,8 +53,8 @@ def test_constructor(self): edge_index = 3 edge_label = 'PREDET' lemma = text_content - token = self._makeOne(text_content, text_begin, part_of_speech, - edge_index, edge_label, lemma) + token = self._make_one(text_content, text_begin, part_of_speech, + edge_index, edge_label, lemma) self.assertEqual(token.text_content, text_content) self.assertEqual(token.text_begin, text_begin) self.assertEqual(token.part_of_speech, part_of_speech) @@ -63,7 +65,7 @@ def test_constructor(self): def test_from_api_repr(self): from google.cloud.language.syntax import PartOfSpeech - klass = self._getTargetClass() + klass = self._get_target_class() text_content = 'pretty' text_begin = -1 part_of_speech = PartOfSpeech.ADJECTIVE @@ -95,22 +97,23 @@ def test_from_api_repr(self): class TestSentence(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.language.syntax import Sentence return Sentence - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): content = "All the king's horses." begin = 11 - sentence = self._makeOne(content, begin) + sentence = self._make_one(content, begin) self.assertEqual(sentence.content, content) self.assertEqual(sentence.begin, begin) def test_from_api_repr(self): - klass = self._getTargetClass() + klass = self._get_target_class() content = 'All the pretty horses.' begin = -1 payload = { diff --git a/logging/unit_tests/handlers/test_handlers.py b/logging/unit_tests/handlers/test_handlers.py index f836e5a335d5..54c38f9b82cb 100644 --- a/logging/unit_tests/handlers/test_handlers.py +++ b/logging/unit_tests/handlers/test_handlers.py @@ -20,21 +20,22 @@ class TestCloudLoggingHandler(unittest.TestCase): PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.handlers.handlers import CloudLoggingHandler return CloudLoggingHandler - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): client = _Client(self.PROJECT) - handler = self._makeOne(client, transport=_Transport) + handler = self._make_one(client, transport=_Transport) self.assertEqual(handler.client, client) def test_emit(self): client = _Client(self.PROJECT) - handler = self._makeOne(client, transport=_Transport) + handler = self._make_one(client, transport=_Transport) LOGNAME = 'loggername' MESSAGE = 'hello world' record = _Record(LOGNAME, logging.INFO, MESSAGE) @@ -45,7 +46,7 @@ def test_emit(self): class TestSetupLogging(unittest.TestCase): - def _callFUT(self, handler, excludes=None): + def _call_fut(self, handler, excludes=None): from google.cloud.logging.handlers.handlers import setup_logging if excludes: return setup_logging(handler, excluded_loggers=excludes) @@ -54,7 +55,7 @@ def _callFUT(self, handler, excludes=None): def test_setup_logging(self): handler = _Handler(logging.INFO) - self._callFUT(handler) + self._call_fut(handler) root_handlers = logging.getLogger().handlers self.assertIn(handler, root_handlers) @@ -64,7 +65,7 @@ def test_setup_logging_excludes(self): EXCLUDED_LOGGER_NAME = 'excludeme' handler = _Handler(logging.INFO) - self._callFUT(handler, (EXCLUDED_LOGGER_NAME,)) + self._call_fut(handler, (EXCLUDED_LOGGER_NAME,)) included_logger = logging.getLogger(INCLUDED_LOGGER_NAME) self.assertTrue(included_logger.propagate) diff --git a/logging/unit_tests/handlers/transports/test_background_thread.py b/logging/unit_tests/handlers/transports/test_background_thread.py index d9ae8297ec22..a7ef4fc43190 100644 --- a/logging/unit_tests/handlers/transports/test_background_thread.py +++ b/logging/unit_tests/handlers/transports/test_background_thread.py @@ -21,24 +21,25 @@ class TestBackgroundThreadHandler(unittest.TestCase): PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.handlers.transports import ( BackgroundThreadTransport) return BackgroundThreadTransport - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): client = _Client(self.PROJECT) NAME = 'python_logger' - transport = self._makeOne(client, NAME) + transport = self._make_one(client, NAME) self.assertEquals(transport.worker.logger.name, NAME) def test_send(self): client = _Client(self.PROJECT) NAME = 'python_logger' - transport = self._makeOne(client, NAME) + transport = self._make_one(client, NAME) transport.worker.batch = client.logger(NAME).batch() PYTHON_LOGGER_NAME = 'mylogger' @@ -57,23 +58,24 @@ def test_send(self): class TestWorker(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.handlers.transports import background_thread return background_thread._Worker - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): NAME = 'python_logger' logger = _Logger(NAME) - worker = self._makeOne(logger) + worker = self._make_one(logger) self.assertEquals(worker.batch, logger._batch) def test_run(self): NAME = 'python_logger' logger = _Logger(NAME) - worker = self._makeOne(logger) + worker = self._make_one(logger) PYTHON_LOGGER_NAME = 'mylogger' MESSAGE = 'hello world' @@ -99,7 +101,7 @@ def test_run_after_stopped(self): # No-op NAME = 'python_logger' logger = _Logger(NAME) - worker = self._makeOne(logger) + worker = self._make_one(logger) PYTHON_LOGGER_NAME = 'mylogger' MESSAGE = 'hello world' @@ -118,7 +120,7 @@ def test_run_enqueue_early(self): # No-op NAME = 'python_logger' logger = _Logger(NAME) - worker = self._makeOne(logger) + worker = self._make_one(logger) PYTHON_LOGGER_NAME = 'mylogger' MESSAGE = 'hello world' diff --git a/logging/unit_tests/handlers/transports/test_base.py b/logging/unit_tests/handlers/transports/test_base.py index 9e3324e3ba0c..0fd673fc2a1b 100644 --- a/logging/unit_tests/handlers/transports/test_base.py +++ b/logging/unit_tests/handlers/transports/test_base.py @@ -19,14 +19,15 @@ class TestBaseHandler(unittest.TestCase): PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.handlers.transports import Transport return Transport - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_send_is_abstract(self): - target = self._makeOne() + target = self._make_one() with self.assertRaises(NotImplementedError): target.send(None, None) diff --git a/logging/unit_tests/handlers/transports/test_sync.py b/logging/unit_tests/handlers/transports/test_sync.py index 7639a8f77787..54e14dcbdfff 100644 --- a/logging/unit_tests/handlers/transports/test_sync.py +++ b/logging/unit_tests/handlers/transports/test_sync.py @@ -20,24 +20,25 @@ class TestSyncHandler(unittest.TestCase): PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.handlers.transports import SyncTransport return SyncTransport - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): client = _Client(self.PROJECT) NAME = 'python_logger' - transport = self._makeOne(client, NAME) + transport = self._make_one(client, NAME) self.assertEqual(transport.logger.name, 'python_logger') def test_send(self): client = _Client(self.PROJECT) STACKDRIVER_LOGGER_NAME = 'python' PYTHON_LOGGER_NAME = 'mylogger' - transport = self._makeOne(client, STACKDRIVER_LOGGER_NAME) + transport = self._make_one(client, STACKDRIVER_LOGGER_NAME) MESSAGE = 'hello world' record = _Record(PYTHON_LOGGER_NAME, logging.INFO, MESSAGE) diff --git a/logging/unit_tests/test__gax.py b/logging/unit_tests/test__gax.py index 7c79b2c1c10b..7497a07efc7d 100644 --- a/logging/unit_tests/test__gax.py +++ b/logging/unit_tests/test__gax.py @@ -32,8 +32,8 @@ class _Base(object): PROJECT_PATH = 'projects/%s' % (PROJECT,) FILTER = 'logName:syslog AND severity>=ERROR' - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) @unittest.skipUnless(_HAVE_GAX, 'No gax-python') @@ -41,14 +41,15 @@ class Test_LoggingAPI(_Base, unittest.TestCase): LOG_NAME = 'log_name' LOG_PATH = 'projects/%s/logs/%s' % (_Base.PROJECT, LOG_NAME) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._gax import _LoggingAPI return _LoggingAPI def test_ctor(self): gax_api = _GAXLoggingAPI() client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) self.assertIs(api._gax_api, gax_api) self.assertIs(api._client, client) @@ -80,7 +81,7 @@ def test_list_entries_no_paging(self): gax_api = _GAXLoggingAPI(_list_log_entries_response=response) client = Client(project=self.PROJECT, credentials=object(), use_gax=True) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_entries( [self.PROJECT], self.FILTER, DESCENDING) @@ -136,7 +137,7 @@ def _list_entries_with_paging_helper(self, payload, struct_pb): gax_api = _GAXLoggingAPI(_list_log_entries_response=response) client = Client(project=self.PROJECT, credentials=object(), use_gax=True) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_entries( [self.PROJECT], page_size=SIZE, page_token=TOKEN) @@ -275,7 +276,7 @@ def test_list_entries_with_extra_properties(self): gax_api = _GAXLoggingAPI(_list_log_entries_response=response) client = Client(project=self.PROJECT, credentials=object(), use_gax=True) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_entries( [self.PROJECT], page_size=SIZE, page_token=TOKEN) @@ -327,7 +328,7 @@ def test_write_entries_single(self): 'textPayload': TEXT, } gax_api = _GAXLoggingAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.write_entries([ENTRY]) @@ -400,7 +401,7 @@ def test_write_entries_w_extra_properties(self): 'operation': OPERATION, } gax_api = _GAXLoggingAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.write_entries([ENTRY]) @@ -475,7 +476,7 @@ def _write_entries_multiple_helper(self, json_payload, json_struct_pb): 'foo': 'bar', } gax_api = _GAXLoggingAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.write_entries(ENTRIES, self.LOG_PATH, RESOURCE, LABELS) @@ -559,7 +560,7 @@ def test_write_entries_multiple_nested_payload(self): def test_logger_delete(self): gax_api = _GAXLoggingAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.logger_delete(self.PROJECT, self.LOG_NAME) @@ -571,7 +572,7 @@ def test_logger_delete_not_found(self): from google.cloud.exceptions import NotFound gax_api = _GAXLoggingAPI(_delete_not_found=True) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.logger_delete(self.PROJECT, self.LOG_NAME) @@ -584,7 +585,7 @@ def test_logger_delete_error(self): from google.gax.errors import GaxError gax_api = _GAXLoggingAPI(_random_gax_error=True) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.logger_delete(self.PROJECT, self.LOG_NAME) @@ -600,14 +601,15 @@ class Test_SinksAPI(_Base, unittest.TestCase): SINK_PATH = 'projects/%s/sinks/%s' % (_Base.PROJECT, SINK_NAME) DESTINATION_URI = 'faux.googleapis.com/destination' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._gax import _SinksAPI return _SinksAPI def test_ctor(self): gax_api = _GAXSinksAPI() client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) self.assertIs(api._gax_api, gax_api) self.assertIs(api._client, client) @@ -625,7 +627,7 @@ def test_list_sinks_no_paging(self): response = _GAXPageIterator([sink_pb], page_token=TOKEN) gax_api = _GAXSinksAPI(_list_sinks_response=response) client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_sinks(self.PROJECT) page = six.next(iterator.pages) @@ -661,7 +663,7 @@ def test_list_sinks_w_paging(self): response = _GAXPageIterator([sink_pb]) gax_api = _GAXSinksAPI(_list_sinks_response=response) client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_sinks( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) @@ -687,7 +689,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.sink_create( @@ -697,7 +699,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(Conflict): api.sink_create( @@ -707,7 +709,7 @@ def test_sink_create_conflict(self): def test_sink_create_ok(self): from google.logging.v2.logging_config_pb2 import LogSink gax_api = _GAXSinksAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.sink_create( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) @@ -724,7 +726,7 @@ def test_sink_create_ok(self): def test_sink_get_error(self): from google.cloud.exceptions import NotFound gax_api = _GAXSinksAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.sink_get(self.PROJECT, self.SINK_NAME) @@ -732,7 +734,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.sink_get(self.PROJECT, self.SINK_NAME) @@ -749,7 +751,7 @@ def test_sink_get_hit(self): destination=self.DESTINATION_URI, filter=self.FILTER) gax_api = _GAXSinksAPI(_get_sink_response=sink_pb) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) response = api.sink_get(self.PROJECT, self.SINK_NAME) @@ -762,7 +764,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.sink_update( @@ -772,7 +774,7 @@ def test_sink_update_error(self): def test_sink_update_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXSinksAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.sink_update( @@ -786,7 +788,7 @@ def test_sink_update_hit(self): destination=self.DESTINATION_URI, filter=self.FILTER) gax_api = _GAXSinksAPI(_update_sink_response=response) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.sink_update( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) @@ -803,7 +805,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.sink_delete(self.PROJECT, self.SINK_NAME) @@ -811,14 +813,14 @@ 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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.sink_delete(self.PROJECT, self.SINK_NAME) def test_sink_delete_hit(self): gax_api = _GAXSinksAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.sink_delete(self.PROJECT, self.SINK_NAME) @@ -833,13 +835,14 @@ class Test_MetricsAPI(_Base, unittest.TestCase): METRIC_PATH = 'projects/%s/metrics/%s' % (_Base.PROJECT, METRIC_NAME) DESCRIPTION = 'Description' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._gax import _MetricsAPI return _MetricsAPI def test_ctor(self): gax_api = _GAXMetricsAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) self.assertIs(api._gax_api, gax_api) def test_list_metrics_no_paging(self): @@ -856,7 +859,7 @@ def test_list_metrics_no_paging(self): response = _GAXPageIterator([metric_pb], page_token=TOKEN) gax_api = _GAXMetricsAPI(_list_log_metrics_response=response) client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_metrics(self.PROJECT) page = six.next(iterator.pages) @@ -892,7 +895,7 @@ def test_list_metrics_w_paging(self): response = _GAXPageIterator([metric_pb]) gax_api = _GAXMetricsAPI(_list_log_metrics_response=response) client = object() - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_metrics( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) @@ -918,7 +921,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.metric_create( @@ -928,7 +931,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(Conflict): api.metric_create( @@ -938,7 +941,7 @@ def test_metric_create_conflict(self): def test_metric_create_ok(self): from google.logging.v2.logging_metrics_pb2 import LogMetric gax_api = _GAXMetricsAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.metric_create( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) @@ -955,7 +958,7 @@ def test_metric_create_ok(self): def test_metric_get_error(self): from google.cloud.exceptions import NotFound gax_api = _GAXMetricsAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.metric_get(self.PROJECT, self.METRIC_NAME) @@ -963,7 +966,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.metric_get(self.PROJECT, self.METRIC_NAME) @@ -980,7 +983,7 @@ def test_metric_get_hit(self): description=self.DESCRIPTION, filter=self.FILTER) gax_api = _GAXMetricsAPI(_get_log_metric_response=metric_pb) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) response = api.metric_get(self.PROJECT, self.METRIC_NAME) @@ -993,7 +996,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.metric_update( @@ -1003,7 +1006,7 @@ def test_metric_update_error(self): def test_metric_update_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXMetricsAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.metric_update( @@ -1017,7 +1020,7 @@ def test_metric_update_hit(self): description=self.DESCRIPTION, filter=self.FILTER) gax_api = _GAXMetricsAPI(_update_log_metric_response=response) - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.metric_update( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) @@ -1034,7 +1037,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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(GaxError): api.metric_delete(self.PROJECT, self.METRIC_NAME) @@ -1042,14 +1045,14 @@ 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._makeOne(gax_api, None) + api = self._make_one(gax_api, None) with self.assertRaises(NotFound): api.metric_delete(self.PROJECT, self.METRIC_NAME) def test_metric_delete_hit(self): gax_api = _GAXMetricsAPI() - api = self._makeOne(gax_api, None) + api = self._make_one(gax_api, None) api.metric_delete(self.PROJECT, self.METRIC_NAME) diff --git a/logging/unit_tests/test__http.py b/logging/unit_tests/test__http.py index 942450063487..1a6d5cd5d9f3 100644 --- a/logging/unit_tests/test__http.py +++ b/logging/unit_tests/test__http.py @@ -20,17 +20,18 @@ class TestConnection(unittest.TestCase): PROJECT = 'project' FILTER = 'logName:syslog AND severity>=ERROR' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._http import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_default_url(self): creds = _Credentials() - conn = self._makeOne(creds) - klass = self._getTargetClass() + conn = self._make_one(creds) + klass = self._get_target_class() self.assertEqual(conn.credentials._scopes, klass.SCOPE) @@ -42,17 +43,18 @@ class Test_LoggingAPI(unittest.TestCase): LOGGER_NAME = 'LOGGER_NAME' FILTER = 'logName:syslog AND severity>=ERROR' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._http import _LoggingAPI return _LoggingAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): connection = object() client = _Client(connection) - api = self._makeOne(client) + api = self._make_one(client) self.assertIs(api._connection, connection) self.assertIs(api._client, client) @@ -93,7 +95,7 @@ def test_list_entries_no_paging(self): client = Client(project=self.PROJECT, credentials=object(), use_gax=False) client.connection = _Connection(RETURNED) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_entries([self.PROJECT]) page = six.next(iterator.pages) @@ -171,7 +173,7 @@ def test_list_entries_w_paging(self): client = Client(project=self.PROJECT, credentials=object(), use_gax=False) client.connection = _Connection(RETURNED) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_entries( projects=[PROJECT1, PROJECT2], filter_=self.FILTER, @@ -228,7 +230,7 @@ def test_write_entries_single(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.write_entries([ENTRY]) @@ -261,7 +263,7 @@ def test_write_entries_multiple(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.write_entries([ENTRY1, ENTRY2], LOG_NAME, RESOURCE, LABELS) @@ -274,7 +276,7 @@ def test_logger_delete(self): path = '/projects/%s/logs/%s' % (self.PROJECT, self.LOGGER_NAME) conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.logger_delete(self.PROJECT, self.LOGGER_NAME) @@ -291,17 +293,18 @@ class Test_SinksAPI(unittest.TestCase): SINK_PATH = 'projects/%s/sinks/%s' % (PROJECT, SINK_NAME) DESTINATION_URI = 'faux.googleapis.com/destination' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._http import _SinksAPI return _SinksAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): connection = object() client = _Client(connection) - api = self._makeOne(client) + api = self._make_one(client) self.assertIs(api._connection, connection) self.assertIs(api._client, client) @@ -320,7 +323,7 @@ def test_list_sinks_no_paging(self): } conn = _Connection(RETURNED) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_sinks(self.PROJECT) page = six.next(iterator.pages) @@ -360,7 +363,7 @@ def test_list_sinks_w_paging(self): } conn = _Connection(RETURNED) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_sinks( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) @@ -399,7 +402,7 @@ def test_sink_create_conflict(self): conn = _Connection() conn._raise_conflict = True client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(Conflict): api.sink_create( @@ -419,7 +422,7 @@ def test_sink_create_ok(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.sink_create( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) @@ -433,7 +436,7 @@ def test_sink_get_miss(self): from google.cloud.exceptions import NotFound conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.sink_get(self.PROJECT, self.SINK_NAME) @@ -450,7 +453,7 @@ def test_sink_get_hit(self): } conn = _Connection(RESPONSE) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) response = api.sink_get(self.PROJECT, self.SINK_NAME) @@ -468,7 +471,7 @@ def test_sink_update_miss(self): } conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.sink_update( @@ -488,7 +491,7 @@ def test_sink_update_hit(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.sink_update( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) @@ -502,7 +505,7 @@ def test_sink_delete_miss(self): from google.cloud.exceptions import NotFound conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.sink_delete(self.PROJECT, self.SINK_NAME) @@ -514,7 +517,7 @@ def test_sink_delete_miss(self): def test_sink_delete_hit(self): conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.sink_delete(self.PROJECT, self.SINK_NAME) @@ -532,12 +535,13 @@ class Test_MetricsAPI(unittest.TestCase): METRIC_PATH = 'projects/%s/metrics/%s' % (PROJECT, METRIC_NAME) DESCRIPTION = 'DESCRIPTION' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging._http import _MetricsAPI return _MetricsAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_list_metrics_no_paging(self): import six @@ -553,7 +557,7 @@ def test_list_metrics_no_paging(self): } conn = _Connection(RETURNED) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_metrics(self.PROJECT) page = six.next(iterator.pages) @@ -592,7 +596,7 @@ def test_list_metrics_w_paging(self): } conn = _Connection(RETURNED) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_metrics( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) @@ -631,7 +635,7 @@ def test_metric_create_conflict(self): conn = _Connection() conn._raise_conflict = True client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(Conflict): api.metric_create( @@ -651,7 +655,7 @@ def test_metric_create_ok(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.metric_create( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) @@ -665,7 +669,7 @@ def test_metric_get_miss(self): from google.cloud.exceptions import NotFound conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.metric_get(self.PROJECT, self.METRIC_NAME) @@ -682,7 +686,7 @@ def test_metric_get_hit(self): } conn = _Connection(RESPONSE) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) response = api.metric_get(self.PROJECT, self.METRIC_NAME) @@ -700,7 +704,7 @@ def test_metric_update_miss(self): } conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.metric_update( @@ -720,7 +724,7 @@ def test_metric_update_hit(self): } conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.metric_update( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) @@ -734,7 +738,7 @@ def test_metric_delete_miss(self): from google.cloud.exceptions import NotFound conn = _Connection() client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.metric_delete(self.PROJECT, self.METRIC_NAME) @@ -746,7 +750,7 @@ def test_metric_delete_miss(self): def test_metric_delete_hit(self): conn = _Connection({}) client = _Client(conn) - api = self._makeOne(client) + api = self._make_one(client) api.metric_delete(self.PROJECT, self.METRIC_NAME) diff --git a/logging/unit_tests/test_client.py b/logging/unit_tests/test_client.py index b498c13df656..ea6bd89fb961 100644 --- a/logging/unit_tests/test_client.py +++ b/logging/unit_tests/test_client.py @@ -26,23 +26,24 @@ class TestClient(unittest.TestCase): FILTER = 'logName:syslog AND severity>=ERROR' DESCRIPTION = 'DESCRIPTION' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) self.assertEqual(client.project, self.PROJECT) def test_logging_api_wo_gax(self): from google.cloud.logging._http import _LoggingAPI - client = self._makeOne(self.PROJECT, credentials=_Credentials(), - use_gax=False) + client = self._make_one(self.PROJECT, credentials=_Credentials(), + use_gax=False) conn = client.connection = object() api = client.logging_api @@ -64,8 +65,8 @@ def make_api(client_obj): return api_obj creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=True) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=True) with _Monkey(MUT, make_gax_logging_api=make_api): api = client.logging_api @@ -83,8 +84,8 @@ def test_no_gax_ctor(self): creds = _Credentials() with _Monkey(MUT, _USE_GAX=True): - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=False) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=False) api = client.logging_api self.assertIsInstance(api, _LoggingAPI) @@ -95,7 +96,7 @@ def test_sinks_api_wo_gax(self): from google.cloud._testing import _Monkey with _Monkey(MUT, _USE_GAX=False): - client = self._makeOne(self.PROJECT, credentials=_Credentials()) + client = self._make_one(self.PROJECT, credentials=_Credentials()) conn = client.connection = object() api = client.sinks_api @@ -118,8 +119,8 @@ def make_api(client_obj): return api_obj creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=True) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=True) with _Monkey(MUT, make_gax_sinks_api=make_api): api = client.sinks_api @@ -136,7 +137,7 @@ def test_metrics_api_wo_gax(self): from google.cloud._testing import _Monkey with _Monkey(MUT, _USE_GAX=False): - client = self._makeOne(self.PROJECT, credentials=_Credentials()) + client = self._make_one(self.PROJECT, credentials=_Credentials()) conn = client.connection = object() api = client.metrics_api @@ -159,8 +160,8 @@ def make_api(client_obj): return api_obj creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=True) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=True) with _Monkey(MUT, make_gax_metrics_api=make_api): api = client.metrics_api @@ -174,7 +175,7 @@ def make_api(client_obj): def test_logger(self): from google.cloud.logging.logger import Logger creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) logger = client.logger(self.LOGGER_NAME) self.assertIsInstance(logger, Logger) self.assertEqual(logger.name, self.LOGGER_NAME) @@ -198,8 +199,8 @@ def test_list_entries_defaults(self): self.PROJECT, self.LOGGER_NAME), }] creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=False) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=False) returned = { 'entries': ENTRIES, 'nextPageToken': TOKEN, @@ -262,8 +263,8 @@ def test_list_entries_explicit(self): 'logName': 'projects/%s/logs/%s' % ( self.PROJECT, self.LOGGER_NAME), }] - client = self._makeOne(self.PROJECT, credentials=_Credentials(), - use_gax=False) + client = self._make_one(self.PROJECT, credentials=_Credentials(), + use_gax=False) returned = {'entries': ENTRIES} client.connection = _Connection(returned) @@ -314,7 +315,7 @@ def test_list_entries_explicit(self): def test_sink_defaults(self): from google.cloud.logging.sink import Sink creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) sink = client.sink(self.SINK_NAME) self.assertIsInstance(sink, Sink) self.assertEqual(sink.name, self.SINK_NAME) @@ -326,7 +327,7 @@ def test_sink_defaults(self): def test_sink_explicit(self): from google.cloud.logging.sink import Sink creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) sink = client.sink(self.SINK_NAME, self.FILTER, self.DESTINATION_URI) self.assertIsInstance(sink, Sink) self.assertEqual(sink.name, self.SINK_NAME) @@ -348,8 +349,8 @@ def test_list_sinks_no_paging(self): 'filter': FILTER, 'destination': self.DESTINATION_URI, }] - client = self._makeOne(project=PROJECT, credentials=_Credentials(), - use_gax=False) + client = self._make_one(project=PROJECT, credentials=_Credentials(), + use_gax=False) returned = { 'sinks': SINKS, 'nextPageToken': TOKEN, @@ -394,8 +395,8 @@ def test_list_sinks_with_paging(self): 'filter': FILTER, 'destination': self.DESTINATION_URI, }] - client = self._makeOne(project=PROJECT, credentials=_Credentials(), - use_gax=False) + client = self._make_one(project=PROJECT, credentials=_Credentials(), + use_gax=False) returned = { 'sinks': SINKS, } @@ -432,7 +433,7 @@ def test_metric_defaults(self): from google.cloud.logging.metric import Metric creds = _Credentials() - client_obj = self._makeOne(project=self.PROJECT, credentials=creds) + client_obj = self._make_one(project=self.PROJECT, credentials=creds) metric = client_obj.metric(self.METRIC_NAME) self.assertIsInstance(metric, Metric) self.assertEqual(metric.name, self.METRIC_NAME) @@ -445,7 +446,7 @@ def test_metric_explicit(self): from google.cloud.logging.metric import Metric creds = _Credentials() - client_obj = self._makeOne(project=self.PROJECT, credentials=creds) + client_obj = self._make_one(project=self.PROJECT, credentials=creds) metric = client_obj.metric(self.METRIC_NAME, self.FILTER, description=self.DESCRIPTION) self.assertIsInstance(metric, Metric) @@ -463,7 +464,7 @@ def test_list_metrics_no_paging(self): 'filter': self.FILTER, 'description': self.DESCRIPTION, }] - client = self._makeOne( + client = self._make_one( project=self.PROJECT, credentials=_Credentials(), use_gax=False) returned = { @@ -505,7 +506,7 @@ def test_list_metrics_with_paging(self): 'filter': self.FILTER, 'description': self.DESCRIPTION, }] - client = self._makeOne( + client = self._make_one( project=self.PROJECT, credentials=_Credentials(), use_gax=False) returned = { diff --git a/logging/unit_tests/test_entries.py b/logging/unit_tests/test_entries.py index 5a78243b1336..0ae4a5e112f9 100644 --- a/logging/unit_tests/test_entries.py +++ b/logging/unit_tests/test_entries.py @@ -17,7 +17,7 @@ class Test_logger_name_from_path(unittest.TestCase): - def _callFUT(self, path): + def _call_fut(self, path): from google.cloud.logging.entries import logger_name_from_path return logger_name_from_path(path) @@ -25,14 +25,14 @@ def test_w_simple_name(self): LOGGER_NAME = 'LOGGER_NAME' PROJECT = 'my-project-1234' PATH = 'projects/%s/logs/%s' % (PROJECT, LOGGER_NAME) - logger_name = self._callFUT(PATH) + logger_name = self._call_fut(PATH) self.assertEqual(logger_name, LOGGER_NAME) def test_w_name_w_all_extras(self): LOGGER_NAME = 'LOGGER_NAME-part.one~part.two%part-three' PROJECT = 'my-project-1234' PATH = 'projects/%s/logs/%s' % (PROJECT, LOGGER_NAME) - logger_name = self._callFUT(PATH) + logger_name = self._call_fut(PATH) self.assertEqual(logger_name, LOGGER_NAME) @@ -41,7 +41,8 @@ class Test_BaseEntry(unittest.TestCase): PROJECT = 'PROJECT' LOGGER_NAME = 'LOGGER_NAME' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.entries import _BaseEntry class _Dummy(_BaseEntry): @@ -49,13 +50,13 @@ class _Dummy(_BaseEntry): return _Dummy - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): PAYLOAD = 'PAYLOAD' logger = _Logger(self.LOGGER_NAME, self.PROJECT) - entry = self._makeOne(PAYLOAD, logger) + entry = self._make_one(PAYLOAD, logger) self.assertEqual(entry.payload, PAYLOAD) self.assertIs(entry.logger, logger) self.assertIsNone(entry.insert_id) @@ -80,12 +81,12 @@ def test_ctor_explicit(self): 'status': STATUS, } logger = _Logger(self.LOGGER_NAME, self.PROJECT) - entry = self._makeOne(PAYLOAD, logger, - insert_id=IID, - timestamp=TIMESTAMP, - labels=LABELS, - severity=SEVERITY, - http_request=REQUEST) + entry = self._make_one(PAYLOAD, logger, + insert_id=IID, + timestamp=TIMESTAMP, + labels=LABELS, + severity=SEVERITY, + http_request=REQUEST) self.assertEqual(entry.payload, PAYLOAD) self.assertIs(entry.logger, logger) self.assertEqual(entry.insert_id, IID) @@ -104,7 +105,7 @@ def test_from_api_repr_missing_data_no_loggers(self): 'dummyPayload': PAYLOAD, 'logName': LOG_NAME, } - klass = self._getTargetClass() + klass = self._get_target_class() entry = klass.from_api_repr(API_REPR, client) self.assertEqual(entry.payload, PAYLOAD) self.assertIsNone(entry.insert_id) @@ -119,7 +120,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._getTargetClass() + klass = self._get_target_class() client = _Client(self.PROJECT) PAYLOAD = 'PAYLOAD' SEVERITY = 'CRITICAL' @@ -179,7 +180,7 @@ def test_from_api_repr_w_loggers_w_logger_match(self): } LOGGER = object() loggers = {LOG_NAME: LOGGER} - klass = self._getTargetClass() + klass = self._get_target_class() entry = klass.from_api_repr(API_REPR, client, loggers=loggers) self.assertEqual(entry.payload, PAYLOAD) self.assertEqual(entry.insert_id, IID) @@ -193,12 +194,13 @@ class TestProtobufEntry(unittest.TestCase): PROJECT = 'PROJECT' LOGGER_NAME = 'LOGGER_NAME' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.entries import ProtobufEntry return ProtobufEntry - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_parse_message(self): import json @@ -208,7 +210,7 @@ def test_parse_message(self): message = Struct(fields={'foo': Value(bool_value=False)}) with_true = Struct(fields={'foo': Value(bool_value=True)}) PAYLOAD = json.loads(MessageToJson(with_true)) - entry = self._makeOne(PAYLOAD, LOGGER) + entry = self._make_one(PAYLOAD, LOGGER) entry.parse_message(message) self.assertTrue(message.fields['foo']) diff --git a/logging/unit_tests/test_logger.py b/logging/unit_tests/test_logger.py index 0524dfddbc9d..c2770f83d9f3 100644 --- a/logging/unit_tests/test_logger.py +++ b/logging/unit_tests/test_logger.py @@ -20,17 +20,18 @@ class TestLogger(unittest.TestCase): PROJECT = 'test-project' LOGGER_NAME = 'logger-name' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.logger import Logger return Logger - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): conn = object() client = _Client(self.PROJECT, conn) - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) self.assertEqual(logger.name, self.LOGGER_NAME) self.assertIs(logger.client, client) self.assertEqual(logger.project, self.PROJECT) @@ -44,7 +45,7 @@ def test_ctor_explicit(self): LABELS = {'foo': 'bar', 'baz': 'qux'} conn = object() client = _Client(self.PROJECT, conn) - logger = self._makeOne(self.LOGGER_NAME, client=client, labels=LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client, labels=LABELS) self.assertEqual(logger.name, self.LOGGER_NAME) self.assertIs(logger.client, client) self.assertEqual(logger.project, self.PROJECT) @@ -58,7 +59,7 @@ def test_batch_w_bound_client(self): from google.cloud.logging.logger import Batch conn = object() client = _Client(self.PROJECT, conn) - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) batch = logger.batch() self.assertIsInstance(batch, Batch) self.assertIs(batch.logger, logger) @@ -70,7 +71,7 @@ def test_batch_w_alternate_client(self): conn2 = object() client1 = _Client(self.PROJECT, conn1) client2 = _Client(self.PROJECT, conn2) - logger = self._makeOne(self.LOGGER_NAME, client=client1) + logger = self._make_one(self.LOGGER_NAME, client=client1) batch = logger.batch(client2) self.assertIsInstance(batch, Batch) self.assertIs(batch.logger, logger) @@ -88,7 +89,7 @@ def test_log_text_w_str_implicit_client(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) logger.log_text(TEXT) @@ -109,8 +110,8 @@ def test_log_text_w_default_labels(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client, + labels=DEFAULT_LABELS) logger.log_text(TEXT) @@ -146,8 +147,8 @@ def test_log_text_w_unicode_explicit_client_labels_severity_httpreq(self): client1 = _Client(self.PROJECT) client2 = _Client(self.PROJECT) api = client2.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client1, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client1, + labels=DEFAULT_LABELS) logger.log_text(TEXT, client=client2, labels=LABELS, insert_id=IID, severity=SEVERITY, http_request=REQUEST) @@ -167,7 +168,7 @@ def test_log_struct_w_implicit_client(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) logger.log_struct(STRUCT) @@ -188,8 +189,8 @@ def test_log_struct_w_default_labels(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client, + labels=DEFAULT_LABELS) logger.log_struct(STRUCT) @@ -225,8 +226,8 @@ def test_log_struct_w_explicit_client_labels_severity_httpreq(self): client1 = _Client(self.PROJECT) client2 = _Client(self.PROJECT) api = client2.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client1, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client1, + labels=DEFAULT_LABELS) logger.log_struct(STRUCT, client=client2, labels=LABELS, insert_id=IID, severity=SEVERITY, @@ -250,7 +251,7 @@ def test_log_proto_w_implicit_client(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) logger.log_proto(message) @@ -274,8 +275,8 @@ def test_log_proto_w_default_labels(self): }] client = _Client(self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client, + labels=DEFAULT_LABELS) logger.log_proto(message) @@ -314,8 +315,8 @@ def test_log_proto_w_explicit_client_labels_severity_httpreq(self): client1 = _Client(self.PROJECT) client2 = _Client(self.PROJECT) api = client2.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client1, - labels=DEFAULT_LABELS) + logger = self._make_one(self.LOGGER_NAME, client=client1, + labels=DEFAULT_LABELS) logger.log_proto(message, client=client2, labels=LABELS, insert_id=IID, severity=SEVERITY, @@ -327,7 +328,7 @@ def test_log_proto_w_explicit_client_labels_severity_httpreq(self): def test_delete_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) logger.delete() @@ -338,7 +339,7 @@ def test_delete_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.logging_api = _DummyLoggingAPI() - logger = self._makeOne(self.LOGGER_NAME, client=client1) + logger = self._make_one(self.LOGGER_NAME, client=client1) logger.delete(client=client2) @@ -358,7 +359,7 @@ def test_list_entries_defaults(self): } client.connection = _Connection(returned) - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) iterator = logger.list_entries() page = six.next(iterator.pages) @@ -391,7 +392,7 @@ def test_list_entries_explicit(self): client = Client(project=self.PROJECT, credentials=object(), use_gax=False) client.connection = _Connection({}) - logger = self._makeOne(self.LOGGER_NAME, client=client) + logger = self._make_one(self.LOGGER_NAME, client=client) iterator = logger.list_entries( projects=[PROJECT1, PROJECT2], filter_=FILTER, order_by=DESCENDING, page_size=PAGE_SIZE, page_token=TOKEN) @@ -421,17 +422,18 @@ class TestBatch(unittest.TestCase): PROJECT = 'test-project' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.logger import Batch return Batch - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_ctor_defaults(self): logger = _Logger() client = _Client(project=self.PROJECT) - batch = self._makeOne(logger, client) + batch = self._make_one(logger, client) self.assertIs(batch.logger, logger) self.assertIs(batch.client, client) self.assertEqual(len(batch.entries), 0) @@ -440,7 +442,7 @@ def test_log_text_defaults(self): TEXT = 'This is the entry text' client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_text(TEXT) self.assertEqual(batch.entries, [('text', TEXT, None, None, None, None)]) @@ -460,7 +462,7 @@ def test_log_text_explicit(self): } client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_text(TEXT, labels=LABELS, insert_id=IID, severity=SEVERITY, http_request=REQUEST) self.assertEqual(batch.entries, @@ -470,7 +472,7 @@ def test_log_struct_defaults(self): STRUCT = {'message': 'Message text', 'weather': 'partly cloudy'} client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_struct(STRUCT) self.assertEqual(batch.entries, [('struct', STRUCT, None, None, None, None)]) @@ -490,7 +492,7 @@ def test_log_struct_explicit(self): } client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_struct(STRUCT, labels=LABELS, insert_id=IID, severity=SEVERITY, http_request=REQUEST) self.assertEqual(batch.entries, @@ -501,7 +503,7 @@ def test_log_proto_defaults(self): message = Struct(fields={'foo': Value(bool_value=True)}) client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_proto(message) self.assertEqual(batch.entries, [('proto', message, None, None, None, None)]) @@ -522,7 +524,7 @@ def test_log_proto_explicit(self): } client = _Client(project=self.PROJECT, connection=object()) logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_proto(message, labels=LABELS, insert_id=IID, severity=SEVERITY, http_request=REQUEST) self.assertEqual(batch.entries, @@ -531,7 +533,7 @@ def test_log_proto_explicit(self): def test_commit_w_invalid_entry_type(self): logger = _Logger() client = _Client(project=self.PROJECT, connection=object()) - batch = self._makeOne(logger, client) + batch = self._make_one(logger, client) batch.entries.append(('bogus', 'BOGUS', None, None, None, None)) with self.assertRaises(ValueError): batch.commit() @@ -558,7 +560,7 @@ def test_commit_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.logging_api = _DummyLoggingAPI() logger = _Logger() - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) batch.log_text(TEXT, insert_id=IID1) batch.log_struct(STRUCT, insert_id=IID2) @@ -602,7 +604,7 @@ def test_commit_w_alternate_client(self): {'protoPayload': json.loads(MessageToJson(message)), 'httpRequest': REQUEST}, ] - batch = self._makeOne(logger, client=client1) + batch = self._make_one(logger, client=client1) batch.log_text(TEXT, labels=LABELS) batch.log_struct(STRUCT, severity=SEVERITY) @@ -644,7 +646,7 @@ def test_context_mgr_success(self): {'protoPayload': json.loads(MessageToJson(message)), 'severity': SEVERITY}, ] - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) with batch as other: other.log_text(TEXT, http_request=REQUEST) @@ -679,7 +681,7 @@ def test_context_mgr_failure(self): ('struct', STRUCT, None, None, SEVERITY, None), ('proto', message, LABELS, None, None, REQUEST), ] - batch = self._makeOne(logger, client=client) + batch = self._make_one(logger, client=client) try: with batch as other: diff --git a/logging/unit_tests/test_metric.py b/logging/unit_tests/test_metric.py index 8f777ec0e33e..5f4b05c054d2 100644 --- a/logging/unit_tests/test_metric.py +++ b/logging/unit_tests/test_metric.py @@ -22,17 +22,18 @@ class TestMetric(unittest.TestCase): FILTER = 'logName:syslog AND severity>=ERROR' DESCRIPTION = 'DESCRIPTION' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.metric import Metric return Metric - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): FULL = 'projects/%s/metrics/%s' % (self.PROJECT, self.METRIC_NAME) client = _Client(self.PROJECT) - metric = self._makeOne(self.METRIC_NAME, client=client) + metric = self._make_one(self.METRIC_NAME, client=client) self.assertEqual(metric.name, self.METRIC_NAME) self.assertIsNone(metric.filter_) self.assertEqual(metric.description, '') @@ -44,8 +45,8 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): FULL = 'projects/%s/metrics/%s' % (self.PROJECT, self.METRIC_NAME) client = _Client(self.PROJECT) - metric = self._makeOne(self.METRIC_NAME, self.FILTER, - client=client, description=self.DESCRIPTION) + metric = self._make_one(self.METRIC_NAME, self.FILTER, + client=client, description=self.DESCRIPTION) self.assertEqual(metric.name, self.METRIC_NAME) self.assertEqual(metric.filter_, self.FILTER) self.assertEqual(metric.description, self.DESCRIPTION) @@ -61,7 +62,7 @@ def test_from_api_repr_minimal(self): 'name': self.METRIC_NAME, 'filter': self.FILTER, } - klass = self._getTargetClass() + klass = self._get_target_class() metric = klass.from_api_repr(RESOURCE, client=client) self.assertEqual(metric.name, self.METRIC_NAME) self.assertEqual(metric.filter_, self.FILTER) @@ -79,7 +80,7 @@ def test_from_api_repr_w_description(self): 'filter': self.FILTER, 'description': DESCRIPTION, } - klass = self._getTargetClass() + klass = self._get_target_class() metric = klass.from_api_repr(RESOURCE, client=client) self.assertEqual(metric.name, self.METRIC_NAME) self.assertEqual(metric.filter_, self.FILTER) @@ -91,7 +92,7 @@ def test_from_api_repr_w_description(self): def test_create_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client) metric.create() @@ -103,8 +104,8 @@ def test_create_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client1, - description=self.DESCRIPTION) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client1, + description=self.DESCRIPTION) metric.create(client=client2) @@ -115,7 +116,7 @@ def test_create_w_alternate_client(self): def test_exists_miss_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client) self.assertFalse(metric.exists()) @@ -131,7 +132,7 @@ def test_exists_hit_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.metrics_api = _DummyMetricsAPI() api._metric_get_response = RESOURCE - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client1) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client1) self.assertTrue(metric.exists(client=client2)) @@ -147,8 +148,8 @@ def test_reload_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.metrics_api = _DummyMetricsAPI() api._metric_get_response = RESOURCE - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client, - description=self.DESCRIPTION) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client, + description=self.DESCRIPTION) metric.reload() @@ -168,7 +169,7 @@ def test_reload_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.metrics_api = _DummyMetricsAPI() api._metric_get_response = RESOURCE - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client1) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client1) metric.reload(client=client2) @@ -180,7 +181,7 @@ def test_reload_w_alternate_client(self): def test_update_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client) metric.update() @@ -192,8 +193,8 @@ def test_update_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client1, - description=self.DESCRIPTION) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client1, + description=self.DESCRIPTION) metric.update(client=client2) @@ -204,7 +205,7 @@ def test_update_w_alternate_client(self): def test_delete_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client) metric.delete() @@ -215,7 +216,7 @@ def test_delete_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.metrics_api = _DummyMetricsAPI() - metric = self._makeOne(self.METRIC_NAME, self.FILTER, client=client1) + metric = self._make_one(self.METRIC_NAME, self.FILTER, client=client1) metric.delete(client=client2) diff --git a/logging/unit_tests/test_sink.py b/logging/unit_tests/test_sink.py index 64245e66db72..ca2a7a6df9c4 100644 --- a/logging/unit_tests/test_sink.py +++ b/logging/unit_tests/test_sink.py @@ -22,17 +22,18 @@ class TestSink(unittest.TestCase): FILTER = 'logName:syslog AND severity>=INFO' DESTINATION_URI = 'faux.googleapis.com/destination' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.logging.sink import Sink return Sink - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): FULL = 'projects/%s/sinks/%s' % (self.PROJECT, self.SINK_NAME) client = _Client(self.PROJECT) - sink = self._makeOne(self.SINK_NAME, client=client) + sink = self._make_one(self.SINK_NAME, client=client) self.assertEqual(sink.name, self.SINK_NAME) self.assertIsNone(sink.filter_) self.assertIsNone(sink.destination) @@ -44,8 +45,9 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): FULL = 'projects/%s/sinks/%s' % (self.PROJECT, self.SINK_NAME) client = _Client(self.PROJECT) - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) self.assertEqual(sink.name, self.SINK_NAME) self.assertEqual(sink.filter_, self.FILTER) self.assertEqual(sink.destination, self.DESTINATION_URI) @@ -62,7 +64,7 @@ def test_from_api_repr_minimal(self): 'filter': self.FILTER, 'destination': self.DESTINATION_URI, } - klass = self._getTargetClass() + klass = self._get_target_class() sink = klass.from_api_repr(RESOURCE, client=client) self.assertEqual(sink.name, self.SINK_NAME) self.assertEqual(sink.filter_, self.FILTER) @@ -79,7 +81,7 @@ def test_from_api_repr_w_description(self): 'filter': self.FILTER, 'destination': self.DESTINATION_URI, } - klass = self._getTargetClass() + klass = self._get_target_class() sink = klass.from_api_repr(RESOURCE, client=client) self.assertEqual(sink.name, self.SINK_NAME) self.assertEqual(sink.filter_, self.FILTER) @@ -91,8 +93,9 @@ def test_from_api_repr_w_description(self): def test_create_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) sink.create() @@ -103,8 +106,9 @@ def test_create_w_bound_client(self): def test_create_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client1) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client1) api = client2.sinks_api = _DummySinksAPI() sink.create(client=client2) @@ -116,8 +120,9 @@ def test_create_w_alternate_client(self): def test_exists_miss_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) self.assertFalse(sink.exists()) @@ -134,8 +139,9 @@ def test_exists_hit_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.sinks_api = _DummySinksAPI() api._sink_get_response = RESOURCE - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client1) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client1) self.assertTrue(sink.exists(client=client2)) @@ -153,8 +159,9 @@ def test_reload_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.sinks_api = _DummySinksAPI() api._sink_get_response = RESOURCE - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) sink.reload() @@ -175,8 +182,9 @@ def test_reload_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.sinks_api = _DummySinksAPI() api._sink_get_response = RESOURCE - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client1) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client1) sink.reload(client=client2) @@ -188,8 +196,9 @@ def test_reload_w_alternate_client(self): def test_update_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) sink.update() @@ -201,8 +210,9 @@ def test_update_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client1) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client1) sink.update(client=client2) @@ -213,8 +223,9 @@ def test_update_w_alternate_client(self): def test_delete_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client) sink.delete() @@ -225,8 +236,9 @@ def test_delete_w_alternate_client(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) api = client2.sinks_api = _DummySinksAPI() - sink = self._makeOne(self.SINK_NAME, self.FILTER, self.DESTINATION_URI, - client=client1) + sink = self._make_one(self.SINK_NAME, self.FILTER, + self.DESTINATION_URI, + client=client1) sink.delete(client=client2) diff --git a/monitoring/unit_tests/test__dataframe.py b/monitoring/unit_tests/test__dataframe.py index 9c7d3c0a63aa..859dda8a39b4 100644 --- a/monitoring/unit_tests/test__dataframe.py +++ b/monitoring/unit_tests/test__dataframe.py @@ -86,21 +86,21 @@ def P(timestamp, value): @unittest.skipUnless(HAVE_PANDAS, 'No pandas') class Test__build_dataframe(unittest.TestCase): # pragma: NO COVER - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.monitoring._dataframe import _build_dataframe return _build_dataframe(*args, **kwargs) def test_both_label_and_labels_illegal(self): with self.assertRaises(ValueError): - self._callFUT([], label='instance_name', labels=['zone']) + self._call_fut([], label='instance_name', labels=['zone']) def test_empty_labels_illegal(self): with self.assertRaises(ValueError): - self._callFUT([], labels=[]) + self._call_fut([], labels=[]) def test_simple_label(self): iterable = generate_query_results() - dataframe = self._callFUT(iterable, label='instance_name') + dataframe = self._call_fut(iterable, label='instance_name') self.assertEqual(dataframe.shape, DIMENSIONS) self.assertEqual(dataframe.values.tolist(), ARRAY) @@ -115,7 +115,7 @@ def test_multiple_labels(self): NAMES = ['resource_type', 'instance_id'] iterable = generate_query_results() - dataframe = self._callFUT(iterable, labels=NAMES) + dataframe = self._call_fut(iterable, labels=NAMES) self.assertEqual(dataframe.shape, DIMENSIONS) self.assertEqual(dataframe.values.tolist(), ARRAY) @@ -134,7 +134,7 @@ def test_multiple_labels_with_just_one(self): NAMES = [NAME] iterable = generate_query_results() - dataframe = self._callFUT(iterable, labels=NAMES) + dataframe = self._call_fut(iterable, labels=NAMES) self.assertEqual(dataframe.shape, DIMENSIONS) self.assertEqual(dataframe.values.tolist(), ARRAY) @@ -152,7 +152,7 @@ def test_smart_labels(self): 'instance_name'] iterable = generate_query_results() - dataframe = self._callFUT(iterable) + dataframe = self._call_fut(iterable) self.assertEqual(dataframe.shape, DIMENSIONS) self.assertEqual(dataframe.values.tolist(), ARRAY) @@ -169,7 +169,7 @@ def test_smart_labels(self): self.assertIsNone(dataframe.index.name) def test_empty_table_simple_label(self): - dataframe = self._callFUT([], label='instance_name') + dataframe = self._call_fut([], label='instance_name') self.assertEqual(dataframe.shape, (0, 0)) self.assertIsNone(dataframe.columns.name) self.assertIsNone(dataframe.index.name) @@ -177,7 +177,7 @@ def test_empty_table_simple_label(self): def test_empty_table_multiple_labels(self): NAMES = ['resource_type', 'instance_id'] - dataframe = self._callFUT([], labels=NAMES) + dataframe = self._call_fut([], labels=NAMES) self.assertEqual(dataframe.shape, (0, 0)) self.assertEqual(dataframe.columns.names, NAMES) self.assertIsNone(dataframe.columns.name) @@ -187,7 +187,7 @@ def test_empty_table_multiple_labels(self): def test_empty_table_multiple_labels_with_just_one(self): NAME = 'instance_id' NAMES = [NAME] - dataframe = self._callFUT([], labels=NAMES) + dataframe = self._call_fut([], labels=NAMES) self.assertEqual(dataframe.shape, (0, 0)) self.assertEqual(dataframe.columns.names, NAMES) self.assertEqual(dataframe.columns.name, NAME) @@ -197,7 +197,7 @@ def test_empty_table_multiple_labels_with_just_one(self): def test_empty_table_smart_labels(self): NAME = 'resource_type' NAMES = [NAME] - dataframe = self._callFUT([]) + dataframe = self._call_fut([]) self.assertEqual(dataframe.shape, (0, 0)) self.assertEqual(dataframe.columns.names, NAMES) self.assertEqual(dataframe.columns.name, NAME) @@ -207,20 +207,20 @@ def test_empty_table_smart_labels(self): class Test__sorted_resource_labels(unittest.TestCase): - def _callFUT(self, labels): + def _call_fut(self, labels): from google.cloud.monitoring._dataframe import _sorted_resource_labels return _sorted_resource_labels(labels) def test_empty(self): - self.assertEqual(self._callFUT([]), []) + self.assertEqual(self._call_fut([]), []) def test_sorted(self): from google.cloud.monitoring._dataframe import TOP_RESOURCE_LABELS EXPECTED = TOP_RESOURCE_LABELS + ('other-1', 'other-2') - self.assertSequenceEqual(self._callFUT(EXPECTED), EXPECTED) + self.assertSequenceEqual(self._call_fut(EXPECTED), EXPECTED) def test_reversed(self): from google.cloud.monitoring._dataframe import TOP_RESOURCE_LABELS EXPECTED = TOP_RESOURCE_LABELS + ('other-1', 'other-2') INPUT = list(reversed(EXPECTED)) - self.assertSequenceEqual(self._callFUT(INPUT), EXPECTED) + self.assertSequenceEqual(self._call_fut(INPUT), EXPECTED) diff --git a/monitoring/unit_tests/test_client.py b/monitoring/unit_tests/test_client.py index b95d1e621a18..5911924c3259 100644 --- a/monitoring/unit_tests/test_client.py +++ b/monitoring/unit_tests/test_client.py @@ -19,12 +19,13 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.client import Client return Client - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_query(self): import datetime @@ -84,7 +85,7 @@ def P(timestamp, value): RESPONSE = {'timeSeries': [SERIES1, SERIES2]} - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(RESPONSE) # A simple query. In practice, it can be very convenient to let the @@ -137,7 +138,7 @@ def test_metric_descriptor_factory(self): VALUE_TYPE = 'DOUBLE' DESCRIPTION = 'This is my metric.' - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) client.connection = _Connection() # For safety's sake. descriptor = client.metric_descriptor(TYPE, metric_kind=METRIC_KIND, @@ -163,7 +164,7 @@ def test_metric_factory(self): 'instance_name': 'my-instance' } - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) client.connection = _Connection() # For safety's sake. metric = client.metric(TYPE, LABELS) self.assertEqual(metric.type, TYPE) @@ -176,7 +177,7 @@ def test_resource_factory(self): 'zone': 'us-central1-f' } - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) client.connection = _Connection() # For safety's sake. resource = client.resource(TYPE, LABELS) self.assertEqual(resource.type, TYPE) @@ -202,7 +203,7 @@ def test_timeseries_factory_gauge(self): TIME1 = datetime.datetime.utcnow() TIME1_STR = _datetime_to_rfc3339(TIME1, ignore_zone=False) - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) client.connection = _Connection() # For safety's sake. metric = client.metric(METRIC_TYPE, METRIC_LABELS) resource = client.resource(RESOURCE_TYPE, RESOURCE_LABELS) @@ -241,7 +242,7 @@ def test_timeseries_factory_cumulative(self): 'zone': 'us-central1-f' } - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) client.connection = _Connection() # For safety's sake. resource = client.resource(RESOURCE_TYPE, RESOURCE_LABELS) @@ -295,7 +296,7 @@ def test_fetch_metric_descriptor(self): # This test is identical to TestMetricDescriptor.test_fetch() # except for the following three lines. - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(METRIC_DESCRIPTOR) descriptor = client.fetch_metric_descriptor(TYPE) @@ -339,7 +340,7 @@ def test_list_metric_descriptors(self): # This test is identical to TestMetricDescriptor.test_list() # except for the following three lines. - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(RESPONSE) descriptors = client.list_metric_descriptors() @@ -384,7 +385,7 @@ def test_fetch_resource_descriptor(self): # This test is identical to TestResourceDescriptor.test_fetch() # except for the following three lines. - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(RESOURCE_DESCRIPTOR) descriptor = client.fetch_resource_descriptor(TYPE) @@ -432,7 +433,7 @@ def test_list_resource_descriptors(self): # This test is identical to TestResourceDescriptor.test_list() # except for the following three lines. - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(RESPONSE) descriptors = client.list_resource_descriptors() @@ -459,7 +460,7 @@ def test_group(self): FILTER = 'resource.type = "gce_instance"' IS_CLUSTER = False - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) group = client.group(GROUP_ID, display_name=DISPLAY_NAME, parent_id=PARENT_ID, filter_string=FILTER, is_cluster=IS_CLUSTER) @@ -471,7 +472,7 @@ def test_group(self): self.assertEqual(group.is_cluster, IS_CLUSTER) def test_group_defaults(self): - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) group = client.group() self.assertIsNone(group.id) @@ -498,7 +499,7 @@ def test_fetch_group(self): 'isCluster': IS_CLUSTER } - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(GROUP) group = client.fetch_group(GROUP_ID) @@ -531,7 +532,7 @@ def test_list_groups(self): RESPONSE = { 'group': [GROUP], } - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) connection = client.connection = _Connection(RESPONSE) groups = client.list_groups() @@ -551,7 +552,7 @@ def test_list_groups(self): def test_write_time_series(self): PATH = '/projects/{project}/timeSeries/'.format(project=PROJECT) - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) RESOURCE_TYPE = 'gce_instance' RESOURCE_LABELS = { @@ -593,7 +594,7 @@ def test_write_time_series(self): def test_write_point(self): import datetime PATH = '/projects/{project}/timeSeries/'.format(project=PROJECT) - client = self._makeOne(project=PROJECT, credentials=_Credentials()) + client = self._make_one(project=PROJECT, credentials=_Credentials()) RESOURCE_TYPE = 'gce_instance' RESOURCE_LABELS = { diff --git a/monitoring/unit_tests/test_connection.py b/monitoring/unit_tests/test_connection.py index 65a8e5e2e980..383cbad54274 100644 --- a/monitoring/unit_tests/test_connection.py +++ b/monitoring/unit_tests/test_connection.py @@ -17,18 +17,19 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.connection import Connection return Connection - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): credentials = _Credentials() - connection = self._makeOne(credentials) + connection = self._make_one(credentials) self.assertEqual(connection.credentials._scopes, - self._getTargetClass().SCOPE) + self._get_target_class().SCOPE) class _Credentials(object): diff --git a/monitoring/unit_tests/test_group.py b/monitoring/unit_tests/test_group.py index 5a7844df167e..a7c88b317890 100644 --- a/monitoring/unit_tests/test_group.py +++ b/monitoring/unit_tests/test_group.py @@ -17,7 +17,7 @@ class Test_group_id_from_name(unittest.TestCase): - def _callFUT(self, path, project): + def _call_fut(self, path, project): from google.cloud.monitoring.group import _group_id_from_name return _group_id_from_name(path, project) @@ -25,20 +25,20 @@ def test_w_empty_name(self): PROJECT = 'my-project-1234' PATH = '' with self.assertRaises(ValueError): - self._callFUT(PATH, PROJECT) + self._call_fut(PATH, PROJECT) def test_w_simple_name(self): GROUP_ID = 'GROUP_ID' PROJECT = 'my-project-1234' PATH = 'projects/%s/groups/%s' % (PROJECT, GROUP_ID) - group_id = self._callFUT(PATH, PROJECT) + group_id = self._call_fut(PATH, PROJECT) self.assertEqual(group_id, GROUP_ID) def test_w_name_w_all_extras(self): GROUP_ID = 'GROUP_ID-part.one~part.two%part-three' PROJECT = 'my-project-1234' PATH = 'projects/%s/groups/%s' % (PROJECT, GROUP_ID) - group_id = self._callFUT(PATH, PROJECT) + group_id = self._call_fut(PATH, PROJECT) self.assertEqual(group_id, GROUP_ID) @@ -107,18 +107,19 @@ def _setUpResources(self): self.RESOURCE2 = Resource._from_dict(info2) self.MEMBERS = [info1, info2] - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.group import Group return Group - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) - def _makeOneFromJSON(self, info, client=None): - return self._getTargetClass()._from_dict(client=client, info=info) + def _make_oneFromJSON(self, info, client=None): + return self._get_target_class()._from_dict(client=client, info=info) def _validateGroup(self, actual_group, expected_group_json): - expected_group = self._makeOneFromJSON(expected_group_json) + expected_group = self._make_oneFromJSON(expected_group_json) self.assertEqual(actual_group.id, expected_group.id) self.assertEqual(actual_group.display_name, expected_group.display_name) @@ -134,7 +135,7 @@ def _validateGroupList(self, client, actual_groups, expected_groups_json): def test_constructor(self): client = _Client(project=self.PROJECT) - group = self._makeOne( + group = self._make_one( client=client, group_id=self.GROUP_ID, display_name=self.DISPLAY_NAME, @@ -155,7 +156,7 @@ def test_constructor(self): def test_constructor_defaults(self): client = _Client(project=self.PROJECT) - group = self._makeOne(client=client) + group = self._make_one(client=client) self.assertIs(group.client, client) @@ -168,17 +169,17 @@ def test_constructor_defaults(self): self.assertFalse(group.is_cluster) def test_path_no_id(self): - group = self._makeOne(client=None) + group = self._make_one(client=None) self.assertRaises(ValueError, getattr, group, 'path') def test_path_w_id(self): client = _Client(project=self.PROJECT) - group = self._makeOne(client=client, group_id=self.GROUP_ID) + group = self._make_one(client=client, group_id=self.GROUP_ID) self.assertEqual(group.path, '/%s' % self.GROUP_NAME) def test_from_dict(self): client = _Client(project=self.PROJECT) - group = self._getTargetClass()._from_dict(client, self.JSON_GROUP) + group = self._get_target_class()._from_dict(client, self.JSON_GROUP) self.assertIs(group.client, client) @@ -195,7 +196,7 @@ def test_from_dict_defaults(self): 'displayName': self.DISPLAY_NAME, 'filter': self.FILTER, } - group = self._getTargetClass()._from_dict(client, info) + group = self._get_target_class()._from_dict(client, info) self.assertIs(group.client, client) @@ -207,12 +208,12 @@ def test_from_dict_defaults(self): def test_to_dict(self): client = _Client(project=self.PROJECT) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) self.assertEqual(group._to_dict(), self.JSON_GROUP) def test_to_dict_defaults(self): client = _Client(project=self.PROJECT) - group = self._makeOne( + group = self._make_one( client=client, group_id=self.GROUP_ID, display_name=self.DISPLAY_NAME, filter_string=self.FILTER) @@ -232,7 +233,7 @@ def test_create(self): connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOne( + group = self._make_one( client=client, display_name=self.DISPLAY_NAME, parent_id=self.PARENT_ID, @@ -251,7 +252,7 @@ def test_create(self): def test_exists_hit(self): connection = _Connection(self.JSON_GROUP) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOne(client=client, group_id=self.GROUP_ID) + group = self._make_one(client=client, group_id=self.GROUP_ID) self.assertTrue(group.exists()) @@ -263,7 +264,7 @@ def test_exists_hit(self): def test_exists_miss(self): connection = _Connection() client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOne(client=client, group_id=self.GROUP_ID) + group = self._make_one(client=client, group_id=self.GROUP_ID) self.assertFalse(group.exists()) @@ -275,7 +276,7 @@ def test_exists_miss(self): def test_reload(self): connection = _Connection(self.JSON_GROUP) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOne(client, group_id=self.GROUP_ID) + group = self._make_one(client, group_id=self.GROUP_ID) group.reload() self.assertIs(group.client, client) @@ -291,7 +292,7 @@ def test_update(self): connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(REQUEST, client) + group = self._make_oneFromJSON(REQUEST, client) group.update() self._validateGroup(group, RESPONSE) @@ -304,7 +305,7 @@ def test_update(self): def test_delete(self): connection = _Connection(self.JSON_GROUP) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) group.delete() request, = connection._requested @@ -314,7 +315,7 @@ def test_delete(self): def test_fetch_parent(self): connection = _Connection(self.JSON_PARENT) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) actual_parent = group.fetch_parent() @@ -328,7 +329,7 @@ def test_fetch_parent(self): def test_fetch_parent_empty(self): connection = _Connection() client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOne(client=client) + group = self._make_one(client=client) actual_parent = group.fetch_parent() self.assertIsNone(actual_parent) @@ -341,7 +342,7 @@ def test_list(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - groups = self._getTargetClass()._list(client) + groups = self._get_target_class()._list(client) self._validateGroupList(client, groups, LIST_OF_GROUPS) request, = connection._requested @@ -364,7 +365,7 @@ def test_list_paged(self): connection = _Connection(RESPONSE1, RESPONSE2) client = _Client(project=self.PROJECT, connection=connection) - groups = self._getTargetClass()._list(client) + groups = self._get_target_class()._list(client) self._validateGroupList(client, groups, LIST_OF_GROUPS) request1, request2 = connection._requested @@ -376,7 +377,7 @@ def test_list_paged(self): self.assertEqual(request2, expected_request2) with self.assertRaises(NotFound): - self._getTargetClass()._list(client) + self._get_target_class()._list(client) def test_list_children(self): CHILDREN = [self.JSON_GROUP, self.JSON_SIBLING] @@ -385,7 +386,7 @@ def test_list_children(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - parent_group = self._makeOneFromJSON(self.JSON_PARENT, client) + parent_group = self._make_oneFromJSON(self.JSON_PARENT, client) groups = parent_group.list_children() self._validateGroupList(client, groups, CHILDREN) @@ -403,7 +404,7 @@ def test_list_ancestors(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - child_group = self._makeOneFromJSON(self.JSON_CHILD, client) + child_group = self._make_oneFromJSON(self.JSON_CHILD, client) groups = child_group.list_ancestors() self._validateGroupList(client, groups, ANCESTORS) @@ -421,7 +422,7 @@ def test_list_descendants(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - parent_group = self._makeOneFromJSON(self.JSON_PARENT, client) + parent_group = self._make_oneFromJSON(self.JSON_PARENT, client) groups = parent_group.list_descendants() self._validateGroupList(client, groups, DESCENDANTS) @@ -439,7 +440,7 @@ def test_list_members(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) members = group.list_members() self.assertEqual(members, [self.RESOURCE1, self.RESOURCE2]) @@ -464,7 +465,7 @@ def test_list_members_paged(self): connection = _Connection(RESPONSE1, RESPONSE2) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) members = group.list_members() self.assertEqual(members, [self.RESOURCE1, self.RESOURCE2]) @@ -496,7 +497,7 @@ def test_list_members_w_all_arguments(self): } connection = _Connection(RESPONSE) client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) members = group.list_members( start_time=T0, end_time=T1, filter_string=MEMBER_FILTER) @@ -520,7 +521,7 @@ def test_list_members_w_missing_end_time(self): connection = _Connection() client = _Client(project=self.PROJECT, connection=connection) - group = self._makeOneFromJSON(self.JSON_GROUP, client) + group = self._make_oneFromJSON(self.JSON_GROUP, client) with self.assertRaises(ValueError): group.list_members(start_time=T0) diff --git a/monitoring/unit_tests/test_label.py b/monitoring/unit_tests/test_label.py index e707def2766c..478b596c4d61 100644 --- a/monitoring/unit_tests/test_label.py +++ b/monitoring/unit_tests/test_label.py @@ -17,41 +17,43 @@ class TestLabelValueType(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.label import LabelValueType return LabelValueType def test_one(self): - self.assertTrue(hasattr(self._getTargetClass(), 'STRING')) + self.assertTrue(hasattr(self._get_target_class(), 'STRING')) def test_names(self): - for name in self._getTargetClass().__dict__: + for name in self._get_target_class().__dict__: if not name.startswith('_'): - self.assertEqual(getattr(self._getTargetClass(), name), name) + self.assertEqual(getattr(self._get_target_class(), name), name) class TestLabelDescriptor(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.label import LabelDescriptor return LabelDescriptor - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): KEY = 'response_code' VALUE_TYPE = 'INT64' DESCRIPTION = 'HTTP status code for the request.' - descriptor = self._makeOne(key=KEY, value_type=VALUE_TYPE, - description=DESCRIPTION) + descriptor = self._make_one(key=KEY, value_type=VALUE_TYPE, + description=DESCRIPTION) self.assertEqual(descriptor.key, KEY) self.assertEqual(descriptor.value_type, VALUE_TYPE) self.assertEqual(descriptor.description, DESCRIPTION) def test_constructor_defaults(self): KEY = 'response_code' - descriptor = self._makeOne(key=KEY) + descriptor = self._make_one(key=KEY) self.assertEqual(descriptor.key, KEY) self.assertEqual(descriptor.value_type, 'STRING') self.assertEqual(descriptor.description, '') @@ -65,7 +67,7 @@ def test_from_dict(self): 'valueType': VALUE_TYPE, 'description': DESCRIPTION, } - descriptor = self._getTargetClass()._from_dict(info) + descriptor = self._get_target_class()._from_dict(info) self.assertEqual(descriptor.key, KEY) self.assertEqual(descriptor.value_type, VALUE_TYPE) self.assertEqual(descriptor.description, DESCRIPTION) @@ -73,7 +75,7 @@ def test_from_dict(self): def test_from_dict_defaults(self): KEY = 'response_code' info = {'key': KEY} - descriptor = self._getTargetClass()._from_dict(info) + descriptor = self._get_target_class()._from_dict(info) self.assertEqual(descriptor.key, KEY) self.assertEqual(descriptor.value_type, 'STRING') self.assertEqual(descriptor.description, '') @@ -82,8 +84,8 @@ def test_to_dict(self): KEY = 'response_code' VALUE_TYPE = 'INT64' DESCRIPTION = 'HTTP status code for the request.' - descriptor = self._makeOne(key=KEY, value_type=VALUE_TYPE, - description=DESCRIPTION) + descriptor = self._make_one(key=KEY, value_type=VALUE_TYPE, + description=DESCRIPTION) expected = { 'key': KEY, 'valueType': VALUE_TYPE, @@ -93,7 +95,7 @@ def test_to_dict(self): def test_to_dict_defaults(self): KEY = 'response_code' - descriptor = self._makeOne(key=KEY) + descriptor = self._make_one(key=KEY) expected = { 'key': KEY, 'valueType': 'STRING', @@ -104,9 +106,9 @@ def test_equality(self): KEY = 'response_code' VALUE_TYPE = 'INT64' DESCRIPTION = 'HTTP status code for the request.' - descriptor1 = self._makeOne(key=KEY, value_type=VALUE_TYPE, - description=DESCRIPTION) - descriptor2 = self._makeOne(key=KEY, value_type=VALUE_TYPE, - description=DESCRIPTION) + descriptor1 = self._make_one(key=KEY, value_type=VALUE_TYPE, + description=DESCRIPTION) + descriptor2 = self._make_one(key=KEY, value_type=VALUE_TYPE, + description=DESCRIPTION) self.assertTrue(descriptor1 == descriptor2) self.assertFalse(descriptor1 != descriptor2) diff --git a/monitoring/unit_tests/test_metric.py b/monitoring/unit_tests/test_metric.py index 587aadb90799..5d4c512e0276 100644 --- a/monitoring/unit_tests/test_metric.py +++ b/monitoring/unit_tests/test_metric.py @@ -17,42 +17,45 @@ class TestMetricKind(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.metric import MetricKind return MetricKind def test_one(self): - self.assertTrue(hasattr(self._getTargetClass(), 'GAUGE')) + self.assertTrue(hasattr(self._get_target_class(), 'GAUGE')) def test_names(self): - for name in self._getTargetClass().__dict__: + for name in self._get_target_class().__dict__: if not name.startswith('_'): - self.assertEqual(getattr(self._getTargetClass(), name), name) + self.assertEqual(getattr(self._get_target_class(), name), name) class TestValueType(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.metric import ValueType return ValueType def test_one(self): - self.assertTrue(hasattr(self._getTargetClass(), 'DISTRIBUTION')) + self.assertTrue(hasattr(self._get_target_class(), 'DISTRIBUTION')) def test_names(self): - for name in self._getTargetClass().__dict__: + for name in self._get_target_class().__dict__: if not name.startswith('_'): - self.assertEqual(getattr(self._getTargetClass(), name), name) + self.assertEqual(getattr(self._get_target_class(), name), name) class TestMetricDescriptor(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.metric import MetricDescriptor return MetricDescriptor - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): from google.cloud.monitoring.label import LabelDescriptor @@ -74,7 +77,7 @@ def test_constructor(self): DISPLAY_NAME = 'Response count' client = object() - descriptor = self._makeOne( + descriptor = self._make_one( client=client, name=NAME, type_=TYPE, @@ -103,7 +106,7 @@ def test_constructor_defaults(self): TYPE = 'appengine.googleapis.com/http/server/response_count' client = object() - descriptor = self._makeOne(client=client, type_=TYPE) + descriptor = self._make_one(client=client, type_=TYPE) self.assertIs(descriptor.client, client) @@ -144,7 +147,7 @@ def test_from_dict(self): 'displayName': DISPLAY_NAME, } client = object() - descriptor = self._getTargetClass()._from_dict(client, info) + descriptor = self._get_target_class()._from_dict(client, info) self.assertIs(descriptor.client, client) @@ -176,7 +179,7 @@ def test_from_dict_defaults(self): 'valueType': VALUE_TYPE, } client = object() - descriptor = self._getTargetClass()._from_dict(client, info) + descriptor = self._get_target_class()._from_dict(client, info) self.assertIs(descriptor.client, client) @@ -215,7 +218,7 @@ def test_to_dict(self): 'displayName': DISPLAY_NAME, } client = object() - descriptor = self._getTargetClass()._from_dict(client, info) + descriptor = self._get_target_class()._from_dict(client, info) del info['name'] self.assertEqual(descriptor._to_dict(), info) @@ -233,7 +236,7 @@ def test_to_dict_defaults(self): 'valueType': VALUE_TYPE, } client = object() - descriptor = self._getTargetClass()._from_dict(client, info) + descriptor = self._get_target_class()._from_dict(client, info) del info['name'] self.assertEqual(descriptor._to_dict(), info) @@ -259,7 +262,7 @@ def test_create(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptor = self._makeOne( + descriptor = self._make_one( client=client, type_=TYPE, metric_kind=METRIC_KIND, @@ -292,7 +295,7 @@ def test_delete(self): connection = _Connection({}) client = _Client(project=PROJECT, connection=connection) - descriptor = self._makeOne( + descriptor = self._make_one( client=client, type_=TYPE, metric_kind='NOTUSED', @@ -321,7 +324,7 @@ def test_fetch(self): connection = _Connection(METRIC_DESCRIPTOR) client = _Client(project=PROJECT, connection=connection) - descriptor = self._getTargetClass()._fetch(client, TYPE) + descriptor = self._get_target_class()._fetch(client, TYPE) self.assertIs(descriptor.client, client) self.assertEqual(descriptor.name, NAME) @@ -364,7 +367,7 @@ def test_list(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client) + descriptors = self._get_target_class()._list(client) self.assertEqual(len(descriptors), 2) descriptor1, descriptor2 = descriptors @@ -423,7 +426,7 @@ def test_list_paged(self): connection = _Connection(RESPONSE1, RESPONSE2) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client) + descriptors = self._get_target_class()._list(client) self.assertEqual(len(descriptors), 2) descriptor1, descriptor2 = descriptors @@ -445,7 +448,7 @@ def test_list_paged(self): self.assertEqual(request2, expected_request2) with self.assertRaises(NotFound): - self._getTargetClass()._list(client) + self._get_target_class()._list(client) def test_list_filtered(self): PROJECT = 'my-project' @@ -459,7 +462,7 @@ def test_list_filtered(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client, FILTER) + descriptors = self._get_target_class()._list(client, FILTER) self.assertEqual(len(descriptors), 0) @@ -481,7 +484,8 @@ def test_list_filtered_by_type_prefix(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client, type_prefix=PREFIX) + descriptors = self._get_target_class()._list( + client, type_prefix=PREFIX) self.assertEqual(len(descriptors), 0) @@ -493,12 +497,13 @@ def test_list_filtered_by_type_prefix(self): class TestMetric(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.metric import Metric return Metric - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): TYPE = 'appengine.googleapis.com/http/server/response_count' @@ -506,7 +511,7 @@ def test_constructor(self): 'response_code': 200, 'loading': False, } - metric = self._makeOne(type=TYPE, labels=LABELS) + metric = self._make_one(type=TYPE, labels=LABELS) self.assertEqual(metric.type, TYPE) self.assertEqual(metric.labels, LABELS) @@ -520,21 +525,21 @@ def test_from_dict(self): 'type': TYPE, 'labels': LABELS, } - metric = self._getTargetClass()._from_dict(info) + metric = self._get_target_class()._from_dict(info) self.assertEqual(metric.type, TYPE) self.assertEqual(metric.labels, LABELS) def test_from_dict_defaults(self): TYPE = 'appengine.googleapis.com/http/server/response_count' info = {'type': TYPE} - metric = self._getTargetClass()._from_dict(info) + metric = self._get_target_class()._from_dict(info) self.assertEqual(metric.type, TYPE) self.assertEqual(metric.labels, {}) def test_to_dict(self): TYPE = 'custom.googleapis.com/my_metric' LABELS = {} - metric = self._makeOne(TYPE, LABELS) + metric = self._make_one(TYPE, LABELS) expected_dict = { 'type': TYPE, 'labels': LABELS, diff --git a/monitoring/unit_tests/test_query.py b/monitoring/unit_tests/test_query.py index 80c809a1f6ac..6354933bcf2a 100644 --- a/monitoring/unit_tests/test_query.py +++ b/monitoring/unit_tests/test_query.py @@ -42,43 +42,46 @@ class TestAligner(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.query import Aligner return Aligner def test_one(self): - self.assertTrue(hasattr(self._getTargetClass(), 'ALIGN_RATE')) + self.assertTrue(hasattr(self._get_target_class(), 'ALIGN_RATE')) def test_names(self): - for name in self._getTargetClass().__dict__: + for name in self._get_target_class().__dict__: if not name.startswith('_'): - self.assertEqual(getattr(self._getTargetClass(), name), name) + self.assertEqual(getattr(self._get_target_class(), name), name) class TestReducer(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.query import Reducer return Reducer def test_one(self): - self.assertTrue(hasattr(self._getTargetClass(), + self.assertTrue(hasattr(self._get_target_class(), 'REDUCE_PERCENTILE_99')) def test_names(self): - for name in self._getTargetClass().__dict__: + for name in self._get_target_class().__dict__: if not name.startswith('_'): - self.assertEqual(getattr(self._getTargetClass(), name), name) + self.assertEqual(getattr(self._get_target_class(), name), name) class TestQuery(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.query import Query return Query - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) @staticmethod def _make_timestamp(value): @@ -87,11 +90,11 @@ def _make_timestamp(value): def test_constructor_minimal(self): client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client) + query = self._make_one(client) self.assertEqual(query._client, client) self.assertEqual(query._filter.metric_type, - self._getTargetClass().DEFAULT_METRIC_TYPE) + self._get_target_class().DEFAULT_METRIC_TYPE) self.assertIsNone(query._start_time) self.assertIsNone(query._end_time) @@ -109,9 +112,9 @@ def test_constructor_maximal(self): T0 = T1 - datetime.timedelta(days=DAYS, hours=HOURS, minutes=MINUTES) client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE, - end_time=T1, - days=DAYS, hours=HOURS, minutes=MINUTES) + query = self._make_one(client, METRIC_TYPE, + end_time=T1, + days=DAYS, hours=HOURS, minutes=MINUTES) self.assertEqual(query._client, client) self.assertEqual(query._filter.metric_type, METRIC_TYPE) @@ -138,7 +141,7 @@ def test_constructor_default_end_time(self): client = _Client(project=PROJECT, connection=_Connection()) with _Monkey(MUT, _UTCNOW=lambda: NOW): - query = self._makeOne(client, METRIC_TYPE, minutes=MINUTES) + query = self._make_one(client, METRIC_TYPE, minutes=MINUTES) self.assertEqual(query._start_time, T0) self.assertEqual(query._end_time, T1) @@ -148,29 +151,29 @@ def test_constructor_nonzero_duration_illegal(self): T1 = datetime.datetime(2016, 4, 7, 2, 30, 30) client = _Client(project=PROJECT, connection=_Connection()) with self.assertRaises(ValueError): - self._makeOne(client, METRIC_TYPE, end_time=T1) + self._make_one(client, METRIC_TYPE, end_time=T1) def test_execution_without_interval_illegal(self): client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) with self.assertRaises(ValueError): list(query) def test_metric_type(self): client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) self.assertEqual(query.metric_type, METRIC_TYPE) def test_filter(self): client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) expected = 'metric.type = "{type}"'.format(type=METRIC_TYPE) self.assertEqual(query.filter, expected) def test_filter_by_group(self): GROUP = '1234567' client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_group(GROUP) expected = ( 'metric.type = "{type}"' @@ -181,7 +184,7 @@ def test_filter_by_group(self): def test_filter_by_projects(self): PROJECT1, PROJECT2 = 'project-1', 'project-2' client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_projects(PROJECT1, PROJECT2) expected = ( 'metric.type = "{type}"' @@ -192,7 +195,7 @@ def test_filter_by_projects(self): def test_filter_by_resources(self): ZONE_PREFIX = 'europe-' client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_resources(zone_prefix=ZONE_PREFIX) expected = ( 'metric.type = "{type}"' @@ -203,7 +206,7 @@ def test_filter_by_resources(self): def test_filter_by_metrics(self): INSTANCE = 'my-instance' client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_metrics(instance_name=INSTANCE) expected = ( 'metric.type = "{type}"' @@ -217,7 +220,7 @@ def test_request_parameters_minimal(self): T1 = datetime.datetime(2016, 4, 7, 2, 30, 0) client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(end_time=T1) actual = list(query._build_query_params()) expected = [ @@ -242,7 +245,7 @@ def test_request_parameters_maximal(self): PAGE_TOKEN = 'second-page-please' client = _Client(project=PROJECT, connection=_Connection()) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) query = query.align(ALIGNER, minutes=MINUTES, seconds=SECONDS) query = query.reduce(REDUCER, FIELD1, FIELD2) @@ -301,7 +304,7 @@ def test_iteration(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query) @@ -381,7 +384,7 @@ def test_iteration_paged(self): connection = _Connection(RESPONSE1, RESPONSE2) client = _Client(project=PROJECT, connection=connection) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query) @@ -426,7 +429,7 @@ def test_iteration_empty(self): connection = _Connection({}) client = _Client(project=PROJECT, connection=connection) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query) @@ -467,7 +470,7 @@ def test_iteration_headers_only(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - query = self._makeOne(client, METRIC_TYPE) + query = self._make_one(client, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query.iter(headers_only=True)) @@ -499,20 +502,21 @@ def test_iteration_headers_only(self): class Test_Filter(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.query import _Filter return _Filter - def _makeOne(self, metric_type): - return self._getTargetClass()(metric_type) + def _make_one(self, metric_type): + return self._get_target_class()(metric_type) def test_minimal(self): - obj = self._makeOne(METRIC_TYPE) + obj = self._make_one(METRIC_TYPE) expected = 'metric.type = "{type}"'.format(type=METRIC_TYPE) self.assertEqual(str(obj), expected) def test_maximal(self): - obj = self._makeOne(METRIC_TYPE) + obj = self._make_one(METRIC_TYPE) obj.group_id = '1234567' obj.projects = 'project-1', 'project-2' obj.select_resources(resource_type='some-resource', @@ -533,18 +537,18 @@ def test_maximal(self): class Test__build_label_filter(unittest.TestCase): - def _callFUT(self, *args, **kwargs): + def _call_fut(self, *args, **kwargs): from google.cloud.monitoring.query import _build_label_filter return _build_label_filter(*args, **kwargs) def test_no_labels(self): - self.assertEqual(self._callFUT('resource'), '') + self.assertEqual(self._call_fut('resource'), '') def test_label_is_none(self): - self.assertEqual(self._callFUT('resource', foo=None), '') + self.assertEqual(self._call_fut('resource', foo=None), '') def test_metric_labels(self): - actual = self._callFUT( + actual = self._call_fut( 'metric', alpha_prefix='a-', beta_gamma_suffix='-b', @@ -558,7 +562,7 @@ def test_metric_labels(self): self.assertEqual(actual, expected) def test_metric_label_response_code_greater_less(self): - actual = self._callFUT( + actual = self._call_fut( 'metric', response_code_greater=500, response_code_less=600) @@ -569,7 +573,7 @@ def test_metric_label_response_code_greater_less(self): self.assertEqual(actual, expected) def test_metric_label_response_code_greater_less_equal(self): - actual = self._callFUT( + actual = self._call_fut( 'metric', response_code_greaterequal=500, response_code_lessequal=600) @@ -580,7 +584,7 @@ def test_metric_label_response_code_greater_less_equal(self): self.assertEqual(actual, expected) def test_resource_labels(self): - actual = self._callFUT( + actual = self._call_fut( 'resource', alpha_prefix='a-', beta_gamma_suffix='-b', @@ -594,7 +598,7 @@ def test_resource_labels(self): self.assertEqual(actual, expected) def test_raw_label_filters(self): - actual = self._callFUT( + actual = self._call_fut( 'resource', 'resource.label.alpha = starts_with("a-")', 'resource.label.beta_gamma = ends_with("-b")', @@ -608,17 +612,17 @@ def test_raw_label_filters(self): self.assertEqual(actual, expected) def test_resource_type(self): - actual = self._callFUT('resource', resource_type='foo') + actual = self._call_fut('resource', resource_type='foo') expected = 'resource.type = "foo"' self.assertEqual(actual, expected) def test_resource_type_prefix(self): - actual = self._callFUT('resource', resource_type_prefix='foo-') + actual = self._call_fut('resource', resource_type_prefix='foo-') expected = 'resource.type = starts_with("foo-")' self.assertEqual(actual, expected) def test_resource_type_suffix(self): - actual = self._callFUT('resource', resource_type_suffix='-foo') + actual = self._call_fut('resource', resource_type_suffix='-foo') expected = 'resource.type = ends_with("-foo")' self.assertEqual(actual, expected) diff --git a/monitoring/unit_tests/test_resource.py b/monitoring/unit_tests/test_resource.py index 776a1f43d1a3..9b429dc30f8e 100644 --- a/monitoring/unit_tests/test_resource.py +++ b/monitoring/unit_tests/test_resource.py @@ -17,12 +17,13 @@ class TestResourceDescriptor(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.resource import ResourceDescriptor return ResourceDescriptor - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): from google.cloud.monitoring.label import LabelDescriptor @@ -40,7 +41,7 @@ def test_constructor(self): description='The GCE zone...'), ] - descriptor = self._makeOne( + descriptor = self._make_one( name=NAME, type_=TYPE, display_name=DISPLAY_NAME, @@ -73,7 +74,7 @@ def test_from_dict(self): 'description': DESCRIPTION, 'labels': [LABEL1, LABEL2, LABEL3], } - descriptor = self._getTargetClass()._from_dict(info) + descriptor = self._get_target_class()._from_dict(info) self.assertEqual(descriptor.name, NAME) self.assertEqual(descriptor.type, TYPE) @@ -94,7 +95,7 @@ def test_from_dict_defaults(self): 'name': NAME, 'type': TYPE, } - descriptor = self._getTargetClass()._from_dict(info) + descriptor = self._get_target_class()._from_dict(info) self.assertEqual(descriptor.name, NAME) self.assertEqual(descriptor.type, TYPE) @@ -126,7 +127,7 @@ def test_fetch(self): connection = _Connection(RESOURCE_DESCRIPTOR) client = _Client(project=PROJECT, connection=connection) - descriptor = self._getTargetClass()._fetch(client, TYPE) + descriptor = self._get_target_class()._fetch(client, TYPE) self.assertEqual(descriptor.name, NAME) self.assertEqual(descriptor.type, TYPE) @@ -173,7 +174,7 @@ def test_list(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client) + descriptors = self._get_target_class()._list(client) self.assertEqual(len(descriptors), 2) descriptor1, descriptor2 = descriptors @@ -227,7 +228,7 @@ def test_list_paged(self): connection = _Connection(RESPONSE1, RESPONSE2) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client) + descriptors = self._get_target_class()._list(client) self.assertEqual(len(descriptors), 2) descriptor1, descriptor2 = descriptors @@ -249,7 +250,7 @@ def test_list_paged(self): self.assertEqual(request2, expected_request2) with self.assertRaises(NotFound): - self._getTargetClass()._list(client) + self._get_target_class()._list(client) def test_list_filtered(self): PROJECT = 'my-project' @@ -264,7 +265,7 @@ def test_list_filtered(self): connection = _Connection(RESPONSE) client = _Client(project=PROJECT, connection=connection) - descriptors = self._getTargetClass()._list(client, FILTER) + descriptors = self._get_target_class()._list(client, FILTER) self.assertEqual(len(descriptors), 0) @@ -276,12 +277,13 @@ def test_list_filtered(self): class TestResource(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.resource import Resource return Resource - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): TYPE = 'gce_instance' @@ -290,7 +292,7 @@ def test_constructor(self): 'instance_id': '1234567890123456789', 'zone': 'us-central1-a', } - resource = self._makeOne(type=TYPE, labels=LABELS) + resource = self._make_one(type=TYPE, labels=LABELS) self.assertEqual(resource.type, TYPE) self.assertEqual(resource.labels, LABELS) @@ -305,14 +307,14 @@ def test_from_dict(self): 'type': TYPE, 'labels': LABELS, } - resource = self._getTargetClass()._from_dict(info) + resource = self._get_target_class()._from_dict(info) self.assertEqual(resource.type, TYPE) self.assertEqual(resource.labels, LABELS) def test_from_dict_defaults(self): TYPE = 'gce_instance' info = {'type': TYPE} - resource = self._getTargetClass()._from_dict(info) + resource = self._get_target_class()._from_dict(info) self.assertEqual(resource.type, TYPE) self.assertEqual(resource.labels, {}) @@ -322,7 +324,7 @@ def test_to_dict(self): 'instance_id': '1234567890123456789', 'zone': 'us-central1-a', } - resource = self._makeOne(TYPE, LABELS) + resource = self._make_one(TYPE, LABELS) expected_dict = { 'type': TYPE, 'labels': LABELS, diff --git a/monitoring/unit_tests/test_timeseries.py b/monitoring/unit_tests/test_timeseries.py index 0a806fa6bb3f..34501a3cf457 100644 --- a/monitoring/unit_tests/test_timeseries.py +++ b/monitoring/unit_tests/test_timeseries.py @@ -33,12 +33,13 @@ class TestTimeSeries(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.timeseries import TimeSeries return TimeSeries - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): from google.cloud.monitoring.metric import Metric @@ -54,11 +55,11 @@ def test_constructor(self): Point(start_time=TS1, end_time=TS2, value=VALUE), ] - series = self._makeOne(metric=METRIC, - resource=RESOURCE, - metric_kind=METRIC_KIND, - value_type=VALUE_TYPE, - points=POINTS) + series = self._make_one(metric=METRIC, + resource=RESOURCE, + metric_kind=METRIC_KIND, + value_type=VALUE_TYPE, + points=POINTS) self.assertEqual(series.metric, METRIC) self.assertEqual(series.resource, RESOURCE) @@ -86,7 +87,7 @@ def test_from_dict(self): ], } - series = self._getTargetClass()._from_dict(info) + series = self._get_target_class()._from_dict(info) self.assertEqual(series.metric.type, METRIC_TYPE) self.assertEqual(series.metric.labels, METRIC_LABELS) @@ -115,7 +116,7 @@ def test_from_dict_no_points(self): 'valueType': VALUE_TYPE, } - series = self._getTargetClass()._from_dict(info) + series = self._get_target_class()._from_dict(info) self.assertEqual(series.metric.type, METRIC_TYPE) self.assertEqual(series.metric.labels, METRIC_LABELS) @@ -135,7 +136,7 @@ def test_labels(self): 'valueType': VALUE_TYPE, } - series = self._getTargetClass()._from_dict(info) + series = self._get_target_class()._from_dict(info) labels = {'resource_type': RESOURCE_TYPE} labels.update(RESOURCE_LABELS) @@ -172,24 +173,25 @@ def test_to_dict(self): }] } - series = self._makeOne(metric=METRIC, resource=RESOURCE, - metric_kind=None, value_type=None, - points=[POINT]) + series = self._make_one(metric=METRIC, resource=RESOURCE, + metric_kind=None, value_type=None, + points=[POINT]) series_dict = series._to_dict() self.assertEqual(info, series_dict) class TestPoint(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.monitoring.timeseries import Point return Point - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): VALUE = 3.14 - point = self._makeOne(start_time=TS0, end_time=TS1, value=VALUE) + point = self._make_one(start_time=TS0, end_time=TS1, value=VALUE) self.assertEqual(point.start_time, TS0) self.assertEqual(point.end_time, TS1) self.assertEqual(point.value, VALUE) @@ -200,7 +202,7 @@ def test_from_dict(self): 'interval': {'startTime': TS0, 'endTime': TS1}, 'value': {'doubleValue': VALUE}, } - point = self._getTargetClass()._from_dict(info) + point = self._get_target_class()._from_dict(info) self.assertEqual(point.start_time, TS0) self.assertEqual(point.end_time, TS1) self.assertEqual(point.value, VALUE) @@ -211,7 +213,7 @@ def test_from_dict_defaults(self): 'interval': {'endTime': TS1}, 'value': {'doubleValue': VALUE}, } - point = self._getTargetClass()._from_dict(info) + point = self._get_target_class()._from_dict(info) self.assertIsNone(point.start_time) self.assertEqual(point.end_time, TS1) self.assertEqual(point.value, VALUE) @@ -222,7 +224,7 @@ def test_from_dict_int64(self): 'interval': {'endTime': TS1}, 'value': {'int64Value': str(VALUE)}, } - point = self._getTargetClass()._from_dict(info) + point = self._get_target_class()._from_dict(info) self.assertIsNone(point.start_time) self.assertEqual(point.end_time, TS1) self.assertEqual(point.value, VALUE) @@ -233,8 +235,8 @@ def test_to_dict_int64(self): VALUE = 42 end_time = datetime.datetime.now() end_time_str = _datetime_to_rfc3339(end_time, ignore_zone=False) - point = self._makeOne(end_time=end_time_str, start_time=None, - value=VALUE) + point = self._make_one(end_time=end_time_str, start_time=None, + value=VALUE) info = { 'interval': {'endTime': end_time_str}, 'value': {'int64Value': str(VALUE)}, @@ -252,8 +254,8 @@ def test_to_dict_float_with_start_time(self): end_time = datetime.datetime.now() end_time_str = _datetime_to_rfc3339(end_time, ignore_zone=False) - point = self._makeOne(end_time=end_time_str, start_time=start_time_str, - value=VALUE) + point = self._make_one(end_time=end_time_str, + start_time=start_time_str, value=VALUE) info = { 'interval': { 'startTime': start_time_str, diff --git a/pubsub/unit_tests/test__gax.py b/pubsub/unit_tests/test__gax.py index 4c2957df14b0..71888431d2e2 100644 --- a/pubsub/unit_tests/test__gax.py +++ b/pubsub/unit_tests/test__gax.py @@ -37,21 +37,22 @@ class _Base(object): SUB_NAME = 'sub_name' SUB_PATH = '%s/subscriptions/%s' % (TOPIC_PATH, SUB_NAME) - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) @unittest.skipUnless(_HAVE_GAX, 'No gax-python') class Test_PublisherAPI(_Base, unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._gax import _PublisherAPI return _PublisherAPI def test_ctor(self): gax_api = _GAXPublisherAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) self.assertIs(api._gax_api, gax_api) self.assertIs(api._client, client) @@ -65,7 +66,7 @@ def test_list_topics_no_paging(self): page_token=TOKEN) gax_api = _GAXPublisherAPI(_list_topics_response=response) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_topics(self.PROJECT) topics = list(iterator) @@ -94,7 +95,7 @@ def test_list_topics_with_paging(self): [_TopicPB(self.TOPIC_PATH)], page_token=NEW_TOKEN) gax_api = _GAXPublisherAPI(_list_topics_response=response) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_topics( self.PROJECT, page_size=SIZE, page_token=TOKEN) @@ -117,7 +118,7 @@ def test_topic_create(self): topic_pb = _TopicPB(self.TOPIC_PATH) gax_api = _GAXPublisherAPI(_create_topic_response=topic_pb) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) resource = api.topic_create(self.TOPIC_PATH) @@ -130,7 +131,7 @@ def test_topic_create_already_exists(self): from google.cloud.exceptions import Conflict gax_api = _GAXPublisherAPI(_create_topic_conflict=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(Conflict): api.topic_create(self.TOPIC_PATH) @@ -143,7 +144,7 @@ def test_topic_create_error(self): from google.gax.errors import GaxError gax_api = _GAXPublisherAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.topic_create(self.TOPIC_PATH) @@ -156,7 +157,7 @@ def test_topic_get_hit(self): topic_pb = _TopicPB(self.TOPIC_PATH) gax_api = _GAXPublisherAPI(_get_topic_response=topic_pb) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) resource = api.topic_get(self.TOPIC_PATH) @@ -169,7 +170,7 @@ def test_topic_get_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXPublisherAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.topic_get(self.TOPIC_PATH) @@ -182,7 +183,7 @@ def test_topic_get_error(self): from google.gax.errors import GaxError gax_api = _GAXPublisherAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.topic_get(self.TOPIC_PATH) @@ -194,7 +195,7 @@ def test_topic_get_error(self): def test_topic_delete_hit(self): gax_api = _GAXPublisherAPI(_delete_topic_ok=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) api.topic_delete(self.TOPIC_PATH) @@ -206,7 +207,7 @@ def test_topic_delete_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXPublisherAPI(_delete_topic_ok=False) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.topic_delete(self.TOPIC_PATH) @@ -219,7 +220,7 @@ def test_topic_delete_error(self): from google.gax.errors import GaxError gax_api = _GAXPublisherAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.topic_delete(self.TOPIC_PATH) @@ -237,7 +238,7 @@ def test_topic_publish_hit(self): response = _PublishResponsePB([MSGID]) gax_api = _GAXPublisherAPI(_publish_response=response) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) resource = api.topic_publish(self.TOPIC_PATH, [MESSAGE]) @@ -257,7 +258,7 @@ def test_topic_publish_miss_w_attrs_w_bytes_payload(self): MESSAGE = {'data': B64, 'attributes': {'foo': 'bar'}} gax_api = _GAXPublisherAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.topic_publish(self.TOPIC_PATH, [MESSAGE]) @@ -277,7 +278,7 @@ def test_topic_publish_error(self): MESSAGE = {'data': B64, 'attributes': {}} gax_api = _GAXPublisherAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.topic_publish(self.TOPIC_PATH, [MESSAGE]) @@ -300,7 +301,7 @@ def test_topic_list_subscriptions_no_paging(self): response = _GAXPageIterator([local_sub_path]) gax_api = _GAXPublisherAPI(_list_topic_subscriptions_response=response) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) topic = Topic(self.TOPIC_NAME, client) iterator = api.topic_list_subscriptions(topic) @@ -335,7 +336,7 @@ def test_topic_list_subscriptions_with_paging(self): [local_sub_path], page_token=NEW_TOKEN) gax_api = _GAXPublisherAPI(_list_topic_subscriptions_response=response) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) topic = Topic(self.TOPIC_NAME, client) iterator = api.topic_list_subscriptions( @@ -364,7 +365,7 @@ def test_topic_list_subscriptions_miss(self): gax_api = _GAXPublisherAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): topic = Topic(self.TOPIC_NAME, client) @@ -383,7 +384,7 @@ def test_topic_list_subscriptions_error(self): gax_api = _GAXPublisherAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): topic = Topic(self.TOPIC_NAME, client) @@ -401,14 +402,15 @@ class Test_SubscriberAPI(_Base, unittest.TestCase): PUSH_ENDPOINT = 'https://api.example.com/push' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._gax import _SubscriberAPI return _SubscriberAPI def test_ctor(self): gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) self.assertIs(api._gax_api, gax_api) self.assertIs(api._client, client) @@ -430,7 +432,7 @@ def test_list_subscriptions_no_paging(self): gax_api = _GAXSubscriberAPI(_list_subscriptions_response=response) creds = _Credentials() client = Client(project=self.PROJECT, credentials=creds) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_subscriptions(self.PROJECT) subscriptions = list(iterator) @@ -476,7 +478,7 @@ def test_list_subscriptions_with_paging(self): client = _Client(self.PROJECT) creds = _Credentials() client = Client(project=self.PROJECT, credentials=creds) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) iterator = api.list_subscriptions( self.PROJECT, page_size=SIZE, page_token=TOKEN) @@ -508,7 +510,7 @@ def test_subscription_create(self): sub_pb = Subscription(name=self.SUB_PATH, topic=self.TOPIC_PATH) gax_api = _GAXSubscriberAPI(_create_subscription_response=sub_pb) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) resource = api.subscription_create(self.SUB_PATH, self.TOPIC_PATH) @@ -530,7 +532,7 @@ def test_subscription_create_already_exists(self): DEADLINE = 600 gax_api = _GAXSubscriberAPI(_create_subscription_conflict=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(Conflict): api.subscription_create( @@ -548,7 +550,7 @@ def test_subscription_create_error(self): from google.gax.errors import GaxError gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_create(self.SUB_PATH, self.TOPIC_PATH) @@ -570,7 +572,7 @@ def test_subscription_get_hit(self): push_config=push_cfg_pb) gax_api = _GAXSubscriberAPI(_get_subscription_response=sub_pb) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) resource = api.subscription_get(self.SUB_PATH) @@ -590,7 +592,7 @@ def test_subscription_get_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_get(self.SUB_PATH) @@ -603,7 +605,7 @@ def test_subscription_get_error(self): from google.gax.errors import GaxError gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_get(self.SUB_PATH) @@ -615,7 +617,7 @@ def test_subscription_get_error(self): def test_subscription_delete_hit(self): gax_api = _GAXSubscriberAPI(_delete_subscription_ok=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) api.subscription_delete(self.TOPIC_PATH) @@ -627,7 +629,7 @@ def test_subscription_delete_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXSubscriberAPI(_delete_subscription_ok=False) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_delete(self.TOPIC_PATH) @@ -640,7 +642,7 @@ def test_subscription_delete_error(self): from google.gax.errors import GaxError gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_delete(self.TOPIC_PATH) @@ -652,7 +654,7 @@ def test_subscription_delete_error(self): def test_subscription_modify_push_config_hit(self): gax_api = _GAXSubscriberAPI(_modify_push_config_ok=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) api.subscription_modify_push_config(self.SUB_PATH, self.PUSH_ENDPOINT) @@ -665,7 +667,7 @@ def test_subscription_modify_push_config_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_modify_push_config( @@ -680,7 +682,7 @@ def test_subscription_modify_push_config_error(self): from google.gax.errors import GaxError gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_modify_push_config( @@ -716,7 +718,7 @@ def test_subscription_pull_explicit(self): response_pb = _PullResponsePB([_ReceivedMessagePB(ACK_ID, message_pb)]) gax_api = _GAXSubscriberAPI(_pull_response=response_pb) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) MAX_MESSAGES = 10 received = api.subscription_pull( @@ -734,7 +736,7 @@ def test_subscription_pull_defaults_miss(self): from google.cloud.exceptions import NotFound gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_pull(self.SUB_PATH) @@ -750,7 +752,7 @@ def test_subscription_pull_defaults_error(self): from google.gax.errors import GaxError gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_pull(self.SUB_PATH) @@ -767,7 +769,7 @@ def test_subscription_acknowledge_hit(self): ACK_ID2 = 'BEADCAFE' gax_api = _GAXSubscriberAPI(_acknowledge_ok=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) api.subscription_acknowledge(self.SUB_PATH, [ACK_ID1, ACK_ID2]) @@ -782,7 +784,7 @@ def test_subscription_acknowledge_miss(self): ACK_ID2 = 'BEADCAFE' gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_acknowledge(self.SUB_PATH, [ACK_ID1, ACK_ID2]) @@ -798,7 +800,7 @@ def test_subscription_acknowledge_error(self): ACK_ID2 = 'BEADCAFE' gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_acknowledge(self.SUB_PATH, [ACK_ID1, ACK_ID2]) @@ -814,7 +816,7 @@ def test_subscription_modify_ack_deadline_hit(self): NEW_DEADLINE = 90 gax_api = _GAXSubscriberAPI(_modify_ack_deadline_ok=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) api.subscription_modify_ack_deadline( self.SUB_PATH, [ACK_ID1, ACK_ID2], NEW_DEADLINE) @@ -833,7 +835,7 @@ def test_subscription_modify_ack_deadline_miss(self): NEW_DEADLINE = 90 gax_api = _GAXSubscriberAPI() client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(NotFound): api.subscription_modify_ack_deadline( @@ -853,7 +855,7 @@ def test_subscription_modify_ack_deadline_error(self): NEW_DEADLINE = 90 gax_api = _GAXSubscriberAPI(_random_gax_error=True) client = _Client(self.PROJECT) - api = self._makeOne(gax_api, client) + api = self._make_one(gax_api, client) with self.assertRaises(GaxError): api.subscription_modify_ack_deadline( @@ -870,7 +872,7 @@ def test_subscription_modify_ack_deadline_error(self): @unittest.skipUnless(_HAVE_GAX, 'No gax-python') class Test_make_gax_publisher_api(_Base, unittest.TestCase): - def _callFUT(self, connection): + def _call_fut(self, connection): from google.cloud.pubsub._gax import make_gax_publisher_api return make_gax_publisher_api(connection) @@ -899,7 +901,7 @@ def make_channel(*args): credentials=creds) with _Monkey(MUT, PublisherApi=mock_publisher_api, make_secure_channel=make_channel): - result = self._callFUT(connection) + result = self._call_fut(connection) self.assertIs(result, mock_result) self.assertEqual(channels, [channel_obj]) @@ -927,7 +929,7 @@ def mock_insecure_channel(host): connection = _Connection(in_emulator=True, host=host) with _Monkey(MUT, PublisherApi=mock_publisher_api, insecure_channel=mock_insecure_channel): - result = self._callFUT(connection) + result = self._call_fut(connection) self.assertIs(result, mock_result) self.assertEqual(channels, [mock_channel]) @@ -937,7 +939,7 @@ def mock_insecure_channel(host): @unittest.skipUnless(_HAVE_GAX, 'No gax-python') class Test_make_gax_subscriber_api(_Base, unittest.TestCase): - def _callFUT(self, connection): + def _call_fut(self, connection): from google.cloud.pubsub._gax import make_gax_subscriber_api return make_gax_subscriber_api(connection) @@ -966,7 +968,7 @@ def make_channel(*args): credentials=creds) with _Monkey(MUT, SubscriberApi=mock_subscriber_api, make_secure_channel=make_channel): - result = self._callFUT(connection) + result = self._call_fut(connection) self.assertIs(result, mock_result) self.assertEqual(channels, [channel_obj]) @@ -994,7 +996,7 @@ def mock_insecure_channel(host): connection = _Connection(in_emulator=True, host=host) with _Monkey(MUT, SubscriberApi=mock_subscriber_api, insecure_channel=mock_insecure_channel): - result = self._callFUT(connection) + result = self._call_fut(connection) self.assertIs(result, mock_result) self.assertEqual(channels, [mock_channel]) diff --git a/pubsub/unit_tests/test__helpers.py b/pubsub/unit_tests/test__helpers.py index 5ff47b7802ea..aaf00c651709 100644 --- a/pubsub/unit_tests/test__helpers.py +++ b/pubsub/unit_tests/test__helpers.py @@ -17,7 +17,7 @@ class Test_topic_name_from_path(unittest.TestCase): - def _callFUT(self, path, project): + def _call_fut(self, path, project): from google.cloud.pubsub._helpers import topic_name_from_path return topic_name_from_path(path, project) @@ -25,20 +25,20 @@ def test_w_simple_name(self): TOPIC_NAME = 'TOPIC_NAME' PROJECT = 'my-project-1234' PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) - topic_name = self._callFUT(PATH, PROJECT) + topic_name = self._call_fut(PATH, PROJECT) self.assertEqual(topic_name, TOPIC_NAME) def test_w_name_w_all_extras(self): TOPIC_NAME = 'TOPIC_NAME-part.one~part.two%part-three' PROJECT = 'my-project-1234' PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) - topic_name = self._callFUT(PATH, PROJECT) + topic_name = self._call_fut(PATH, PROJECT) self.assertEqual(topic_name, TOPIC_NAME) class Test_subscription_name_from_path(unittest.TestCase): - def _callFUT(self, path, project): + def _call_fut(self, path, project): from google.cloud.pubsub._helpers import subscription_name_from_path return subscription_name_from_path(path, project) @@ -46,12 +46,12 @@ def test_w_simple_name(self): SUBSCRIPTION_NAME = 'SUBSCRIPTION_NAME' PROJECT = 'my-project-1234' PATH = 'projects/%s/subscriptions/%s' % (PROJECT, SUBSCRIPTION_NAME) - subscription_name = self._callFUT(PATH, PROJECT) + subscription_name = self._call_fut(PATH, PROJECT) self.assertEqual(subscription_name, SUBSCRIPTION_NAME) def test_w_name_w_all_extras(self): SUBSCRIPTION_NAME = 'SUBSCRIPTION_NAME-part.one~part.two%part-three' PROJECT = 'my-project-1234' PATH = 'projects/%s/subscriptions/%s' % (PROJECT, SUBSCRIPTION_NAME) - topic_name = self._callFUT(PATH, PROJECT) + topic_name = self._call_fut(PATH, PROJECT) self.assertEqual(topic_name, SUBSCRIPTION_NAME) diff --git a/pubsub/unit_tests/test__http.py b/pubsub/unit_tests/test__http.py index ce6abe4553ae..f9f94fff098d 100644 --- a/pubsub/unit_tests/test__http.py +++ b/pubsub/unit_tests/test__http.py @@ -25,19 +25,20 @@ class _Base(unittest.TestCase): SUB_NAME = 'subscription_name' SUB_PATH = 'projects/%s/subscriptions/%s' % (PROJECT, SUB_NAME) - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) class TestConnection(_Base): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._http import Connection return Connection def test_default_url(self): - conn = self._makeOne() - klass = self._getTargetClass() + conn = self._make_one() + klass = self._get_target_class() self.assertEqual(conn.api_base_url, klass.API_BASE_URL) def test_custom_url_from_env(self): @@ -49,14 +50,14 @@ def test_custom_url_from_env(self): fake_environ = {PUBSUB_EMULATOR: HOST} with _Monkey(os, getenv=fake_environ.get): - conn = self._makeOne() + conn = self._make_one() - klass = self._getTargetClass() + klass = self._get_target_class() self.assertNotEqual(conn.api_base_url, klass.API_BASE_URL) self.assertEqual(conn.api_base_url, 'http://' + HOST) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, conn.API_VERSION, @@ -67,7 +68,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._makeOne() + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL) @@ -79,7 +80,7 @@ def test_build_api_url_w_extra_query_params(self): def test_build_api_url_w_base_url_override(self): base_url1 = 'api-base-url1' base_url2 = 'api-base-url2' - conn = self._makeOne() + conn = self._make_one() conn.api_base_url = base_url1 URI = '/'.join([ base_url2, @@ -92,17 +93,18 @@ def test_build_api_url_w_base_url_override(self): class Test_PublisherAPI(_Base): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._http import _PublisherAPI return _PublisherAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) self.assertIs(api._client, client) self.assertIs(api._connection, connection) @@ -112,7 +114,7 @@ def test_list_topics_no_paging(self): returned = {'topics': [{'name': self.TOPIC_PATH}]} connection = _Connection(returned) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_topics(self.PROJECT) topics = list(iterator) @@ -143,7 +145,7 @@ def test_list_topics_with_paging(self): } connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_topics( self.PROJECT, page_token=TOKEN1, page_size=SIZE) @@ -168,7 +170,7 @@ def test_list_topics_missing_key(self): returned = {} connection = _Connection(returned) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_topics(self.PROJECT) topics = list(iterator) @@ -186,7 +188,7 @@ def test_topic_create(self): RETURNED = {'name': self.TOPIC_PATH} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.topic_create(self.TOPIC_PATH) @@ -200,7 +202,7 @@ def test_topic_create_already_exists(self): connection = _Connection() connection._no_response_error = Conflict client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(Conflict): api.topic_create(self.TOPIC_PATH) @@ -213,7 +215,7 @@ def test_topic_get_hit(self): RETURNED = {'name': self.TOPIC_PATH} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.topic_get(self.TOPIC_PATH) @@ -226,7 +228,7 @@ def test_topic_get_miss(self): from google.cloud.exceptions import NotFound connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.topic_get(self.TOPIC_PATH) @@ -239,7 +241,7 @@ def test_topic_delete_hit(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) api.topic_delete(self.TOPIC_PATH) @@ -251,7 +253,7 @@ def test_topic_delete_miss(self): from google.cloud.exceptions import NotFound connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.topic_delete(self.TOPIC_PATH) @@ -270,7 +272,7 @@ def test_topic_publish_hit(self): RETURNED = {'messageIds': [MSGID]} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.topic_publish(self.TOPIC_PATH, [MESSAGE]) @@ -289,7 +291,7 @@ def test_topic_publish_miss(self): MESSAGE = {'data': PAYLOAD, 'attributes': {}} connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): api.topic_publish(self.TOPIC_PATH, [MESSAGE]) @@ -309,7 +311,7 @@ def test_topic_list_subscriptions_no_paging(self): RETURNED = {'subscriptions': [local_sub_path]} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) topic = Topic(self.TOPIC_NAME, client) iterator = api.topic_list_subscriptions(topic) @@ -345,7 +347,7 @@ def test_topic_list_subscriptions_with_paging(self): } connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) topic = Topic(self.TOPIC_NAME, client) iterator = api.topic_list_subscriptions( @@ -373,7 +375,7 @@ def test_topic_list_subscriptions_missing_key(self): connection = _Connection({}) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) topic = Topic(self.TOPIC_NAME, client) iterator = api.topic_list_subscriptions(topic) @@ -394,7 +396,7 @@ def test_topic_list_subscriptions_miss(self): connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(NotFound): topic = Topic(self.TOPIC_NAME, client) @@ -408,17 +410,18 @@ def test_topic_list_subscriptions_miss(self): class Test_SubscriberAPI(_Base): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._http import _SubscriberAPI return _SubscriberAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): connection = _Connection() client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) self.assertIs(api._connection, connection) self.assertIs(api._client, client) @@ -433,7 +436,7 @@ def test_list_subscriptions_no_paging(self): creds = _Credentials() client = Client(project=self.PROJECT, credentials=creds) client.connection = connection - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_subscriptions(self.PROJECT) subscriptions = list(iterator) @@ -476,7 +479,7 @@ def test_list_subscriptions_with_paging(self): creds = _Credentials() client = Client(project=self.PROJECT, credentials=creds) client.connection = connection - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_subscriptions( self.PROJECT, page_token=TOKEN1, page_size=SIZE) @@ -508,7 +511,7 @@ def test_list_subscriptions_missing_key(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) iterator = api.list_subscriptions(self.PROJECT) subscriptions = list(iterator) @@ -528,7 +531,7 @@ def test_subscription_create_defaults(self): RETURNED['name'] = self.SUB_PATH connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.subscription_create(self.SUB_PATH, self.TOPIC_PATH) @@ -552,7 +555,7 @@ def test_subscription_create_explicit(self): RETURNED['name'] = self.SUB_PATH connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.subscription_create( self.SUB_PATH, self.TOPIC_PATH, @@ -575,7 +578,7 @@ def test_subscription_get(self): } connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) resource = api.subscription_get(self.SUB_PATH) @@ -588,7 +591,7 @@ def test_subscription_delete(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) api.subscription_delete(self.SUB_PATH) @@ -604,7 +607,7 @@ def test_subscription_modify_push_config(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) api.subscription_modify_push_config(self.SUB_PATH, PUSH_ENDPOINT) @@ -625,7 +628,7 @@ def test_subscription_pull_defaults(self): } connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) BODY = { 'returnImmediately': False, 'maxMessages': 1, @@ -652,7 +655,7 @@ def test_subscription_pull_explicit(self): } connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) MAX_MESSAGES = 10 BODY = { 'returnImmediately': True, @@ -677,7 +680,7 @@ def test_subscription_acknowledge(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) api.subscription_acknowledge(self.SUB_PATH, [ACK_ID1, ACK_ID2]) @@ -697,7 +700,7 @@ def test_subscription_modify_ack_deadline(self): RETURNED = {} connection = _Connection(RETURNED) client = _Client(connection, self.PROJECT) - api = self._makeOne(client) + api = self._make_one(client) api.subscription_modify_ack_deadline( self.SUB_PATH, [ACK_ID1, ACK_ID2], NEW_DEADLINE) @@ -710,13 +713,14 @@ def test_subscription_modify_ack_deadline(self): class Test_IAMPolicyAPI(_Base): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub._http import _IAMPolicyAPI return _IAMPolicyAPI def test_ctor(self): connection = _Connection() - api = self._makeOne(connection) + api = self._make_one(connection) self.assertIs(api._connection, connection) def test_get_iam_policy(self): @@ -740,7 +744,7 @@ def test_get_iam_policy(self): ], } connection = _Connection(RETURNED) - api = self._makeOne(connection) + api = self._make_one(connection) policy = api.get_iam_policy(self.TOPIC_PATH) @@ -771,7 +775,7 @@ def test_set_iam_policy(self): } RETURNED = POLICY.copy() connection = _Connection(RETURNED) - api = self._makeOne(connection) + api = self._make_one(connection) policy = api.set_iam_policy(self.TOPIC_PATH, POLICY) @@ -791,7 +795,7 @@ def test_test_iam_permissions(self): ALLOWED = ALL_ROLES[1:] RETURNED = {'permissions': ALLOWED} connection = _Connection(RETURNED) - api = self._makeOne(connection) + api = self._make_one(connection) allowed = api.test_iam_permissions(self.TOPIC_PATH, ALL_ROLES) @@ -810,7 +814,7 @@ def test_test_iam_permissions_missing_key(self): ALL_ROLES = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE] RETURNED = {} connection = _Connection(RETURNED) - api = self._makeOne(connection) + api = self._make_one(connection) allowed = api.test_iam_permissions(self.TOPIC_PATH, ALL_ROLES) @@ -823,33 +827,33 @@ def test_test_iam_permissions_missing_key(self): class Test__transform_messages_base64_empty(unittest.TestCase): - def _callFUT(self, messages, transform, key=None): + def _call_fut(self, messages, transform, key=None): from google.cloud.pubsub._http import _transform_messages_base64 return _transform_messages_base64(messages, transform, key) def test__transform_messages_base64_empty_message(self): from base64 import b64decode DATA = [{'message': {}}] - self._callFUT(DATA, b64decode, 'message') + self._call_fut(DATA, b64decode, 'message') self.assertEqual(DATA, [{'message': {}}]) def test__transform_messages_base64_empty_data(self): from base64 import b64decode DATA = [{'message': {'data': b''}}] - self._callFUT(DATA, b64decode, 'message') + self._call_fut(DATA, b64decode, 'message') self.assertEqual(DATA, [{'message': {'data': b''}}]) def test__transform_messages_base64_pull(self): from base64 import b64encode DATA = [{'message': {'data': b'testing 1 2 3'}}] - self._callFUT(DATA, b64encode, 'message') + self._call_fut(DATA, b64encode, 'message') self.assertEqual(DATA[0]['message']['data'], b64encode(b'testing 1 2 3')) def test__transform_messages_base64_publish(self): from base64 import b64encode DATA = [{'data': b'testing 1 2 3'}] - self._callFUT(DATA, b64encode) + self._call_fut(DATA, b64encode) self.assertEqual(DATA[0]['data'], b64encode(b'testing 1 2 3')) diff --git a/pubsub/unit_tests/test_client.py b/pubsub/unit_tests/test_client.py index 2f2dbfec02c5..462d55abba2b 100644 --- a/pubsub/unit_tests/test_client.py +++ b/pubsub/unit_tests/test_client.py @@ -22,12 +22,13 @@ class TestClient(unittest.TestCase): SUB_NAME = 'subscription_name' SUB_PATH = 'projects/%s/subscriptions/%s' % (PROJECT, SUB_NAME) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_publisher_api_wo_gax(self): from google.cloud.pubsub._http import _PublisherAPI @@ -36,7 +37,7 @@ def test_publisher_api_wo_gax(self): creds = _Credentials() with _Monkey(MUT, _USE_GAX=False): - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) conn = client.connection = object() api = client.publisher_api @@ -54,8 +55,8 @@ def test_no_gax_ctor(self): creds = _Credentials() with _Monkey(MUT, _USE_GAX=True): - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=False) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=False) self.assertFalse(client._use_gax) api = client.publisher_api @@ -83,7 +84,7 @@ def __init__(self, _wrapped, client): with _Monkey(MUT, _USE_GAX=True, make_gax_publisher_api=_generated_api, GAXPublisherAPI=_GaxPublisherAPI): - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) api = client.publisher_api self.assertIsInstance(api, _GaxPublisherAPI) @@ -102,7 +103,7 @@ def test_subscriber_api_wo_gax(self): creds = _Credentials() with _Monkey(MUT, _USE_GAX=False): - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) conn = client.connection = object() api = client.subscriber_api @@ -135,7 +136,7 @@ def __init__(self, _wrapped, client): with _Monkey(MUT, _USE_GAX=True, make_gax_subscriber_api=_generated_api, GAXSubscriberAPI=_GaxSubscriberAPI): - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) api = client.subscriber_api self.assertIsInstance(api, _GaxSubscriberAPI) @@ -150,7 +151,7 @@ def __init__(self, _wrapped, client): def test_iam_policy_api(self): from google.cloud.pubsub._http import _IAMPolicyAPI creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) conn = client.connection = object() api = client.iam_policy_api self.assertIsInstance(api, _IAMPolicyAPI) @@ -163,7 +164,7 @@ def test_list_topics_no_paging(self): from google.cloud.pubsub.topic import Topic creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) client.connection = object() api = _FauxPublisherAPI(items=[Topic(self.TOPIC_NAME, client)]) client._publisher_api = api @@ -186,7 +187,7 @@ def test_list_topics_with_paging(self): TOKEN2 = 'TOKEN2' SIZE = 1 creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) client.connection = object() api = _FauxPublisherAPI([Topic(self.TOPIC_NAME, client)], TOKEN2) client._publisher_api = api @@ -204,7 +205,7 @@ def test_list_topics_with_paging(self): def test_list_topics_missing_key(self): creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds) + client = self._make_one(project=self.PROJECT, credentials=creds) client.connection = object() api = _FauxPublisherAPI() client._publisher_api = api @@ -224,8 +225,8 @@ def test_list_subscriptions_no_paging(self): SUB_INFO = {'name': self.SUB_PATH, 'topic': self.TOPIC_PATH} creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=False) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=False) returned = {'subscriptions': [SUB_INFO]} client.connection = _Connection(returned) @@ -262,8 +263,8 @@ def test_list_subscriptions_with_paging(self): SUB_INFO = {'name': self.SUB_PATH, 'topic': self.TOPIC_PATH} creds = _Credentials() - client = self._makeOne(project=self.PROJECT, credentials=creds, - use_gax=False) + client = self._make_one(project=self.PROJECT, credentials=creds, + use_gax=False) # Set up the mock response. ACK_DEADLINE = 42 @@ -316,7 +317,7 @@ def test_list_subscriptions_w_missing_key(self): PROJECT = 'PROJECT' creds = _Credentials() - client = self._makeOne(project=PROJECT, credentials=creds) + client = self._make_one(project=PROJECT, credentials=creds) client.connection = object() api = client._subscriber_api = _FauxSubscriberAPI() api._list_subscriptions_response = (), None @@ -334,7 +335,7 @@ def test_topic(self): TOPIC_NAME = 'TOPIC_NAME' creds = _Credentials() - client_obj = self._makeOne(project=PROJECT, credentials=creds) + client_obj = self._make_one(project=PROJECT, credentials=creds) new_topic = client_obj.topic(TOPIC_NAME) self.assertEqual(new_topic.name, TOPIC_NAME) self.assertIs(new_topic._client, client_obj) diff --git a/pubsub/unit_tests/test_iam.py b/pubsub/unit_tests/test_iam.py index 0a31697b2990..ea2703dd56b6 100644 --- a/pubsub/unit_tests/test_iam.py +++ b/pubsub/unit_tests/test_iam.py @@ -17,15 +17,16 @@ class TestPolicy(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.iam import Policy return Policy - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): - policy = self._makeOne() + policy = self._make_one() self.assertIsNone(policy.etag) self.assertIsNone(policy.version) self.assertEqual(list(policy.owners), []) @@ -37,7 +38,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): VERSION = 17 ETAG = 'ETAG' - policy = self._makeOne(ETAG, VERSION) + policy = self._make_one(ETAG, VERSION) self.assertEqual(policy.etag, ETAG) self.assertEqual(policy.version, VERSION) self.assertEqual(list(policy.owners), []) @@ -49,40 +50,40 @@ def test_ctor_explicit(self): def test_user(self): EMAIL = 'phred@example.com' MEMBER = 'user:%s' % (EMAIL,) - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.user(EMAIL), MEMBER) def test_service_account(self): EMAIL = 'phred@example.com' MEMBER = 'serviceAccount:%s' % (EMAIL,) - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.service_account(EMAIL), MEMBER) def test_group(self): EMAIL = 'phred@example.com' MEMBER = 'group:%s' % (EMAIL,) - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.group(EMAIL), MEMBER) def test_domain(self): DOMAIN = 'example.com' MEMBER = 'domain:%s' % (DOMAIN,) - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.domain(DOMAIN), MEMBER) def test_all_users(self): - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.all_users(), 'allUsers') def test_authenticated_users(self): - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.authenticated_users(), 'allAuthenticatedUsers') def test_from_api_repr_only_etag(self): RESOURCE = { 'etag': 'ACAB', } - klass = self._getTargetClass() + klass = self._get_target_class() policy = klass.from_api_repr(RESOURCE) self.assertEqual(policy.etag, 'ACAB') self.assertIsNone(policy.version) @@ -117,7 +118,7 @@ def test_from_api_repr_complete(self): {'role': PUBSUB_SUBSCRIBER_ROLE, 'members': [SUBSCRIBER]}, ], } - klass = self._getTargetClass() + klass = self._get_target_class() policy = klass.from_api_repr(RESOURCE) self.assertEqual(policy.etag, 'DEADBEEF') self.assertEqual(policy.version, 17) @@ -137,16 +138,16 @@ def test_from_api_repr_bad_role(self): {'role': 'nonesuch', 'members': [BOGUS1, BOGUS2]}, ], } - klass = self._getTargetClass() + klass = self._get_target_class() with self.assertRaises(ValueError): klass.from_api_repr(RESOURCE) def test_to_api_repr_defaults(self): - policy = self._makeOne() + policy = self._make_one() self.assertEqual(policy.to_api_repr(), {}) def test_to_api_repr_only_etag(self): - policy = self._makeOne('DEADBEEF') + policy = self._make_one('DEADBEEF') self.assertEqual(policy.to_api_repr(), {'etag': 'DEADBEEF'}) def test_to_api_repr_full(self): @@ -176,7 +177,7 @@ def test_to_api_repr_full(self): {'role': PUBSUB_SUBSCRIBER_ROLE, 'members': [SUBSCRIBER]}, ], } - policy = self._makeOne('DEADBEEF', 17) + policy = self._make_one('DEADBEEF', 17) policy.owners.add(OWNER1) policy.owners.add(OWNER2) policy.editors.add(EDITOR1) diff --git a/pubsub/unit_tests/test_message.py b/pubsub/unit_tests/test_message.py index 0d71ec9715f8..8bcbec6c87b7 100644 --- a/pubsub/unit_tests/test_message.py +++ b/pubsub/unit_tests/test_message.py @@ -17,17 +17,18 @@ class TestMessage(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.message import Message return Message - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_no_attributes(self): DATA = b'DEADBEEF' MESSAGE_ID = b'12345' - message = self._makeOne(data=DATA, message_id=MESSAGE_ID) + message = self._make_one(data=DATA, message_id=MESSAGE_ID) self.assertEqual(message.data, DATA) self.assertEqual(message.message_id, MESSAGE_ID) self.assertEqual(message.attributes, {}) @@ -37,8 +38,8 @@ def test_ctor_w_attributes(self): DATA = b'DEADBEEF' MESSAGE_ID = b'12345' ATTRS = {'a': 'b'} - message = self._makeOne(data=DATA, message_id=MESSAGE_ID, - attributes=ATTRS) + message = self._make_one(data=DATA, message_id=MESSAGE_ID, + attributes=ATTRS) self.assertEqual(message.data, DATA) self.assertEqual(message.message_id, MESSAGE_ID) self.assertEqual(message.attributes, ATTRS) @@ -47,7 +48,7 @@ def test_ctor_w_attributes(self): def test_timestamp_no_attributes(self): DATA = b'DEADBEEF' MESSAGE_ID = b'12345' - message = self._makeOne(data=DATA, message_id=MESSAGE_ID) + message = self._make_one(data=DATA, message_id=MESSAGE_ID) def _to_fail(): return message.timestamp @@ -58,8 +59,8 @@ def test_timestamp_wo_timestamp_in_attributes(self): DATA = b'DEADBEEF' MESSAGE_ID = b'12345' ATTRS = {'a': 'b'} - message = self._makeOne(data=DATA, message_id=MESSAGE_ID, - attributes=ATTRS) + message = self._make_one(data=DATA, message_id=MESSAGE_ID, + attributes=ATTRS) def _to_fail(): return message.timestamp @@ -76,14 +77,14 @@ def test_timestamp_w_timestamp_in_attributes(self): naive = datetime.strptime(TIMESTAMP, _RFC3339_MICROS) timestamp = naive.replace(tzinfo=UTC) ATTRS = {'timestamp': TIMESTAMP} - message = self._makeOne(data=DATA, message_id=MESSAGE_ID, - attributes=ATTRS) + message = self._make_one(data=DATA, message_id=MESSAGE_ID, + attributes=ATTRS) self.assertEqual(message.timestamp, timestamp) def test_from_api_repr_missing_data(self): MESSAGE_ID = '12345' api_repr = {'messageId': MESSAGE_ID} - message = self._getTargetClass().from_api_repr(api_repr) + message = self._get_target_class().from_api_repr(api_repr) self.assertEqual(message.data, b'') self.assertEqual(message.message_id, MESSAGE_ID) self.assertEqual(message.attributes, {}) @@ -98,7 +99,7 @@ def test_from_api_repr_no_attributes(self): 'messageId': MESSAGE_ID, 'publishTime': TIMESTAMP, } - message = self._getTargetClass().from_api_repr(api_repr) + message = self._get_target_class().from_api_repr(api_repr) self.assertEqual(message.data, DATA) self.assertEqual(message.message_id, MESSAGE_ID) self.assertEqual(message.attributes, {}) @@ -115,7 +116,7 @@ def test_from_api_repr_w_attributes(self): 'publishTime': TIMESTAMP, 'attributes': ATTRS, } - message = self._getTargetClass().from_api_repr(api_repr) + message = self._get_target_class().from_api_repr(api_repr) self.assertEqual(message.data, DATA) self.assertEqual(message.message_id, MESSAGE_ID) self.assertEqual(message.service_timestamp, TIMESTAMP) diff --git a/pubsub/unit_tests/test_subscription.py b/pubsub/unit_tests/test_subscription.py index 2afa45c3cc94..6d4dc1068f2a 100644 --- a/pubsub/unit_tests/test_subscription.py +++ b/pubsub/unit_tests/test_subscription.py @@ -24,17 +24,18 @@ class TestSubscription(unittest.TestCase): DEADLINE = 42 ENDPOINT = 'https://api.example.com/push' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.subscription import Subscription return Subscription - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): client = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) self.assertEqual(subscription.name, self.SUB_NAME) self.assertIs(subscription.topic, topic) self.assertIsNone(subscription.ack_deadline) @@ -43,8 +44,8 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): client = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic, - self.DEADLINE, self.ENDPOINT) + subscription = self._make_one(self.SUB_NAME, topic, + self.DEADLINE, self.ENDPOINT) self.assertEqual(subscription.name, self.SUB_NAME) self.assertIs(subscription.topic, topic) self.assertEqual(subscription.ack_deadline, self.DEADLINE) @@ -52,7 +53,7 @@ def test_ctor_explicit(self): def test_ctor_w_client_wo_topic(self): client = _Client(project=self.PROJECT) - subscription = self._makeOne(self.SUB_NAME, client=client) + subscription = self._make_one(self.SUB_NAME, client=client) self.assertEqual(subscription.name, self.SUB_NAME) self.assertIsNone(subscription.topic) @@ -61,11 +62,11 @@ def test_ctor_w_both_topic_and_client(self): client2 = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client1) with self.assertRaises(TypeError): - self._makeOne(self.SUB_NAME, topic, client=client2) + self._make_one(self.SUB_NAME, topic, client=client2) def test_ctor_w_neither_topic_nor_client(self): with self.assertRaises(TypeError): - self._makeOne(self.SUB_NAME) + self._make_one(self.SUB_NAME) def test_from_api_repr_no_topics(self): from google.cloud.pubsub.topic import Topic @@ -73,7 +74,7 @@ def test_from_api_repr_no_topics(self): 'name': self.SUB_PATH, 'ackDeadlineSeconds': self.DEADLINE, 'pushConfig': {'pushEndpoint': self.ENDPOINT}} - klass = self._getTargetClass() + klass = self._get_target_class() client = _Client(project=self.PROJECT) subscription = klass.from_api_repr(resource, client) self.assertEqual(subscription.name, self.SUB_NAME) @@ -85,12 +86,12 @@ def test_from_api_repr_no_topics(self): self.assertEqual(subscription.push_endpoint, self.ENDPOINT) def test_from_api_repr_w_deleted_topic(self): - klass = self._getTargetClass() + klass = self._get_target_class() resource = {'topic': klass._DELETED_TOPIC_PATH, 'name': self.SUB_PATH, 'ackDeadlineSeconds': self.DEADLINE, 'pushConfig': {'pushEndpoint': self.ENDPOINT}} - klass = self._getTargetClass() + klass = self._get_target_class() client = _Client(project=self.PROJECT) subscription = klass.from_api_repr(resource, client) self.assertEqual(subscription.name, self.SUB_NAME) @@ -105,7 +106,7 @@ def test_from_api_repr_w_topics_no_topic_match(self): 'ackDeadlineSeconds': self.DEADLINE, 'pushConfig': {'pushEndpoint': self.ENDPOINT}} topics = {} - klass = self._getTargetClass() + klass = self._get_target_class() client = _Client(project=self.PROJECT) subscription = klass.from_api_repr(resource, client, topics=topics) self.assertEqual(subscription.name, self.SUB_NAME) @@ -125,7 +126,7 @@ def test_from_api_repr_w_topics_w_topic_match(self): client = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client) topics = {self.TOPIC_PATH: topic} - klass = self._getTargetClass() + klass = self._get_target_class() subscription = klass.from_api_repr(resource, client, topics=topics) self.assertEqual(subscription.name, self.SUB_NAME) self.assertIs(subscription.topic, topic) @@ -139,7 +140,7 @@ def test_full_name_and_path(self): TOPIC_NAME = 'topic_name' CLIENT = _Client(project=PROJECT) topic = _Topic(TOPIC_NAME, client=CLIENT) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) self.assertEqual(subscription.full_name, SUB_FULL) self.assertEqual(subscription.path, SUB_PATH) @@ -147,7 +148,7 @@ def test_autoack_defaults(self): from google.cloud.pubsub.subscription import AutoAck client = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) auto_ack = subscription.auto_ack() self.assertIsInstance(auto_ack, AutoAck) self.assertIs(auto_ack._subscription, subscription) @@ -160,7 +161,7 @@ def test_autoack_explicit(self): client1 = _Client(project=self.PROJECT) client2 = _Client(project=self.PROJECT) topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) auto_ack = subscription.auto_ack(True, 10, client2) self.assertIsInstance(auto_ack, AutoAck) self.assertIs(auto_ack._subscription, subscription) @@ -177,7 +178,7 @@ def test_create_pull_wo_ack_deadline_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_create_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.create() @@ -196,8 +197,8 @@ def test_create_push_w_ack_deadline_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_create_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic, - self.DEADLINE, self.ENDPOINT) + subscription = self._make_one(self.SUB_NAME, topic, + self.DEADLINE, self.ENDPOINT) subscription.create(client=client2) @@ -209,7 +210,7 @@ def test_exists_miss_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.subscriber_api = _FauxSubscribererAPI() topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) self.assertFalse(subscription.exists()) @@ -222,7 +223,7 @@ def test_exists_hit_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_get_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) self.assertTrue(subscription.exists(client=client2)) @@ -239,7 +240,7 @@ def test_reload_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_get_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.reload() @@ -257,8 +258,8 @@ def test_reload_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_get_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic, - self.DEADLINE, self.ENDPOINT) + subscription = self._make_one(self.SUB_NAME, topic, + self.DEADLINE, self.ENDPOINT) subscription.reload(client=client2) @@ -272,7 +273,7 @@ def test_delete_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_delete_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.delete() @@ -285,8 +286,8 @@ def test_delete_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_delete_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic, - self.DEADLINE, self.ENDPOINT) + subscription = self._make_one(self.SUB_NAME, topic, + self.DEADLINE, self.ENDPOINT) subscription.delete(client=client2) @@ -297,7 +298,7 @@ def test_modify_push_config_w_endpoint_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_modify_push_config_response = {} topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.modify_push_configuration(push_endpoint=self.ENDPOINT) @@ -311,8 +312,8 @@ def test_modify_push_config_wo_endpoint_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_modify_push_config_response = {} topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic, - push_endpoint=self.ENDPOINT) + subscription = self._make_one(self.SUB_NAME, topic, + push_endpoint=self.ENDPOINT) subscription.modify_push_configuration(push_endpoint=None, client=client2) @@ -332,7 +333,7 @@ def test_pull_wo_return_immediately_max_messages_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_pull_response = [REC_MESSAGE] topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) pulled = subscription.pull() @@ -359,7 +360,7 @@ def test_pull_w_return_immediately_w_max_messages_w_alt_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_pull_response = [REC_MESSAGE] topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) pulled = subscription.pull(return_immediately=True, max_messages=3, client=client2) @@ -379,7 +380,7 @@ def test_pull_wo_receivedMessages(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_pull_response = {} topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) pulled = subscription.pull(return_immediately=False) @@ -394,7 +395,7 @@ def test_acknowledge_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_acknowlege_response = {} topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.acknowledge([ACK_ID1, ACK_ID2]) @@ -409,7 +410,7 @@ def test_acknowledge_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_acknowlege_response = {} topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.acknowledge([ACK_ID1, ACK_ID2], client=client2) @@ -423,7 +424,7 @@ def test_modify_ack_deadline_w_bound_client(self): api = client.subscriber_api = _FauxSubscribererAPI() api._subscription_modify_ack_deadline_response = {} topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.modify_ack_deadline([ACK_ID1, ACK_ID2], self.DEADLINE) @@ -438,7 +439,7 @@ def test_modify_ack_deadline_w_alternate_client(self): api = client2.subscriber_api = _FauxSubscribererAPI() api._subscription_modify_ack_deadline_response = {} topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) subscription.modify_ack_deadline( [ACK_ID1, ACK_ID2], self.DEADLINE, client=client2) @@ -477,7 +478,7 @@ def test_get_iam_policy_w_bound_client(self): api = client.iam_policy_api = _FauxIAMPolicy() api._get_iam_policy_response = POLICY topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) policy = subscription.get_iam_policy() @@ -499,7 +500,7 @@ def test_get_iam_policy_w_alternate_client(self): api = client2.iam_policy_api = _FauxIAMPolicy() api._get_iam_policy_response = POLICY topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) policy = subscription.get_iam_policy(client=client2) @@ -546,7 +547,7 @@ def test_set_iam_policy_w_bound_client(self): api = client.iam_policy_api = _FauxIAMPolicy() api._set_iam_policy_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) policy = Policy('DEADBEEF', 17) policy.owners.add(OWNER1) policy.owners.add(OWNER2) @@ -576,7 +577,7 @@ def test_set_iam_policy_w_alternate_client(self): api = client2.iam_policy_api = _FauxIAMPolicy() api._set_iam_policy_response = RESPONSE topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) policy = Policy() new_policy = subscription.set_iam_policy(policy, client=client2) @@ -598,7 +599,7 @@ def test_check_iam_permissions_w_bound_client(self): api = client.iam_policy_api = _FauxIAMPolicy() api._test_iam_permissions_response = ROLES[:-1] topic = _Topic(self.TOPIC_NAME, client=client) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) allowed = subscription.check_iam_permissions(ROLES) @@ -617,7 +618,7 @@ def test_check_iam_permissions_w_alternate_client(self): api = client2.iam_policy_api = _FauxIAMPolicy() api._test_iam_permissions_response = [] topic = _Topic(self.TOPIC_NAME, client=client1) - subscription = self._makeOne(self.SUB_NAME, topic) + subscription = self._make_one(self.SUB_NAME, topic) allowed = subscription.check_iam_permissions(ROLES, client=client2) @@ -671,16 +672,17 @@ def subscription_modify_ack_deadline(self, subscription_path, ack_ids, class TestAutoAck(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.subscription import AutoAck return AutoAck - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_defaults(self): subscription = _FauxSubscription(()) - auto_ack = self._makeOne(subscription) + auto_ack = self._make_one(subscription) self.assertEqual(auto_ack._return_immediately, False) self.assertEqual(auto_ack._max_messages, 1) self.assertIsNone(auto_ack._client) @@ -688,7 +690,7 @@ def test_ctor_defaults(self): def test_ctor_explicit(self): CLIENT = object() subscription = _FauxSubscription(()) - auto_ack = self._makeOne( + auto_ack = self._make_one( subscription, return_immediately=True, max_messages=10, client=CLIENT) self.assertIs(auto_ack._subscription, subscription) @@ -698,7 +700,7 @@ def test_ctor_explicit(self): def test___enter___w_defaults(self): subscription = _FauxSubscription(()) - auto_ack = self._makeOne(subscription) + auto_ack = self._make_one(subscription) with auto_ack as returned: pass @@ -711,7 +713,7 @@ def test___enter___w_defaults(self): def test___enter___w_explicit(self): CLIENT = object() subscription = _FauxSubscription(()) - auto_ack = self._makeOne( + auto_ack = self._make_one( subscription, return_immediately=True, max_messages=10, client=CLIENT) @@ -734,7 +736,7 @@ def test___exit___(self): (ACK_ID3, MESSAGE3), ] subscription = _FauxSubscription(ITEMS) - auto_ack = self._makeOne(subscription, client=CLIENT) + auto_ack = self._make_one(subscription, client=CLIENT) with auto_ack: for ack_id, message in list(auto_ack.items()): if message.fail: diff --git a/pubsub/unit_tests/test_topic.py b/pubsub/unit_tests/test_topic.py index b67d6ac3ce66..8f4838237fd7 100644 --- a/pubsub/unit_tests/test_topic.py +++ b/pubsub/unit_tests/test_topic.py @@ -20,18 +20,19 @@ class TestTopic(unittest.TestCase): TOPIC_NAME = 'topic_name' TOPIC_PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.topic import Topic return Topic - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_w_explicit_timestamp(self): client = _Client(project=self.PROJECT) - topic = self._makeOne(self.TOPIC_NAME, - client=client, - timestamp_messages=True) + topic = self._make_one(self.TOPIC_NAME, + client=client, + timestamp_messages=True) self.assertEqual(topic.name, self.TOPIC_NAME) self.assertEqual(topic.project, self.PROJECT) self.assertEqual(topic.full_name, self.TOPIC_PATH) @@ -40,7 +41,7 @@ def test_ctor_w_explicit_timestamp(self): def test_from_api_repr(self): client = _Client(project=self.PROJECT) resource = {'name': self.TOPIC_PATH} - klass = self._getTargetClass() + klass = self._get_target_class() topic = klass.from_api_repr(resource, client=client) self.assertEqual(topic.name, self.TOPIC_NAME) self.assertIs(topic._client, client) @@ -53,7 +54,7 @@ def test_from_api_repr_with_bad_client(self): client = _Client(project=PROJECT1) PATH = 'projects/%s/topics/%s' % (PROJECT2, self.TOPIC_NAME) resource = {'name': PATH} - klass = self._getTargetClass() + klass = self._get_target_class() self.assertRaises(ValueError, klass.from_api_repr, resource, client=client) @@ -61,7 +62,7 @@ def test_create_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_create_response = {'name': self.TOPIC_PATH} - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) topic.create() @@ -72,7 +73,7 @@ def test_create_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.publisher_api = _FauxPublisherAPI() api._topic_create_response = {'name': self.TOPIC_PATH} - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) topic.create(client=client2) @@ -81,7 +82,7 @@ def test_create_w_alternate_client(self): def test_exists_miss_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) self.assertFalse(topic.exists()) @@ -92,7 +93,7 @@ def test_exists_hit_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.publisher_api = _FauxPublisherAPI() api._topic_get_response = {'name': self.TOPIC_PATH} - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) self.assertTrue(topic.exists(client=client2)) @@ -102,7 +103,7 @@ def test_delete_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_delete_response = {} - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) topic.delete() @@ -113,7 +114,7 @@ def test_delete_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.publisher_api = _FauxPublisherAPI() api._topic_delete_response = {} - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) topic.delete(client=client2) @@ -126,7 +127,7 @@ def test_publish_single_bytes_wo_attrs_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) msgid = topic.publish(PAYLOAD) @@ -154,8 +155,8 @@ def _utcnow(): api = client2.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client1, - timestamp_messages=True) + topic = self._make_one(self.TOPIC_NAME, client=client1, + timestamp_messages=True) with _Monkey(MUT, _NOW=_utcnow): msgid = topic.publish(PAYLOAD, client=client2) @@ -171,8 +172,8 @@ def test_publish_single_bytes_w_add_timestamp_w_ts_in_attrs(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client, - timestamp_messages=True) + topic = self._make_one(self.TOPIC_NAME, client=client, + timestamp_messages=True) msgid = topic.publish(PAYLOAD, timestamp=OVERRIDE) @@ -187,7 +188,7 @@ def test_publish_single_w_attrs(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) msgid = topic.publish(PAYLOAD, attr1='value1', attr2='value2') @@ -201,7 +202,7 @@ def test_publish_with_gax(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) msgid = topic.publish(PAYLOAD) self.assertEqual(msgid, MSGID) @@ -214,7 +215,7 @@ def test_publish_without_gax(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) msgid = topic.publish(PAYLOAD) self.assertEqual(msgid, MSGID) @@ -231,7 +232,7 @@ def test_publish_multiple_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID1, MSGID2] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) with topic.batch() as batch: batch.publish(PAYLOAD1) @@ -246,7 +247,7 @@ def test_publish_w_no_messages(self): client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) with topic.batch() as batch: pass @@ -268,7 +269,7 @@ def test_publish_multiple_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID1, MSGID2] - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) with topic.batch(client=client2) as batch: batch.publish(PAYLOAD1) @@ -284,7 +285,7 @@ def test_publish_multiple_error(self): PAYLOAD2 = b'This is the second message text' client = _Client(project=self.PROJECT) api = client.publisher_api = _FauxPublisherAPI() - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) try: with topic.batch() as batch: @@ -300,7 +301,7 @@ def test_publish_multiple_error(self): def test_subscription(self): from google.cloud.pubsub.subscription import Subscription client = _Client(project=self.PROJECT) - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) SUBSCRIPTION_NAME = 'subscription_name' subscription = topic.subscription(SUBSCRIPTION_NAME) @@ -331,7 +332,7 @@ def test_list_subscriptions_no_paging(self): } client.connection = _Connection(returned) - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) iterator = topic.list_subscriptions() page = six.next(iterator.pages) @@ -381,7 +382,7 @@ def test_list_subscriptions_with_paging(self): } client.connection = _Connection(returned) - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) iterator = topic.list_subscriptions( page_size=PAGE_SIZE, page_token=TOKEN) @@ -416,7 +417,7 @@ def test_list_subscriptions_missing_key(self): client = Client(project=self.PROJECT, credentials=object(), use_gax=False) client.connection = _Connection({}) - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) iterator = topic.list_subscriptions() subscriptions = list(iterator) @@ -463,7 +464,7 @@ def test_get_iam_policy_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.iam_policy_api = _FauxIAMPolicy() api._get_iam_policy_response = POLICY - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) policy = topic.get_iam_policy() @@ -485,7 +486,7 @@ def test_get_iam_policy_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.iam_policy_api = _FauxIAMPolicy() api._get_iam_policy_response = POLICY - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) policy = topic.get_iam_policy(client=client2) @@ -537,7 +538,7 @@ def test_set_iam_policy_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.iam_policy_api = _FauxIAMPolicy() api._set_iam_policy_response = RESPONSE - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) policy = Policy('DEADBEEF', 17) policy.owners.add(OWNER1) policy.owners.add(OWNER2) @@ -567,7 +568,7 @@ def test_set_iam_policy_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.iam_policy_api = _FauxIAMPolicy() api._set_iam_policy_response = RESPONSE - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) policy = Policy() new_policy = topic.set_iam_policy(policy, client=client2) @@ -589,7 +590,7 @@ def test_check_iam_permissions_w_bound_client(self): client = _Client(project=self.PROJECT) api = client.iam_policy_api = _FauxIAMPolicy() api._test_iam_permissions_response = ROLES[:-1] - topic = self._makeOne(self.TOPIC_NAME, client=client) + topic = self._make_one(self.TOPIC_NAME, client=client) allowed = topic.check_iam_permissions(ROLES) @@ -607,7 +608,7 @@ def test_check_iam_permissions_w_alternate_client(self): client2 = _Client(project=self.PROJECT) api = client2.iam_policy_api = _FauxIAMPolicy() api._test_iam_permissions_response = [] - topic = self._makeOne(self.TOPIC_NAME, client=client1) + topic = self._make_one(self.TOPIC_NAME, client=client1) allowed = topic.check_iam_permissions(ROLES, client=client2) @@ -619,17 +620,18 @@ def test_check_iam_permissions_w_alternate_client(self): class TestBatch(unittest.TestCase): PROJECT = 'PROJECT' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.pubsub.topic import Batch return Batch - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_ctor_defaults(self): topic = _Topic() client = _Client(project=self.PROJECT) - batch = self._makeOne(topic, client) + batch = self._make_one(topic, client) self.assertIs(batch.topic, topic) self.assertIs(batch.client, client) self.assertEqual(len(batch.messages), 0) @@ -638,13 +640,13 @@ def test_ctor_defaults(self): def test___iter___empty(self): topic = _Topic() client = object() - batch = self._makeOne(topic, client) + batch = self._make_one(topic, client) self.assertEqual(list(batch), []) def test___iter___non_empty(self): topic = _Topic() client = object() - batch = self._makeOne(topic, client) + batch = self._make_one(topic, client) batch.message_ids[:] = ['ONE', 'TWO', 'THREE'] self.assertEqual(list(batch), ['ONE', 'TWO', 'THREE']) @@ -654,7 +656,7 @@ def test_publish_bytes_wo_attrs(self): 'attributes': {}} client = _Client(project=self.PROJECT) topic = _Topic() - batch = self._makeOne(topic, client=client) + batch = self._make_one(topic, client=client) batch.publish(PAYLOAD) self.assertEqual(batch.messages, [MESSAGE]) @@ -664,7 +666,7 @@ def test_publish_bytes_w_add_timestamp(self): 'attributes': {'timestamp': 'TIMESTAMP'}} client = _Client(project=self.PROJECT) topic = _Topic(timestamp_messages=True) - batch = self._makeOne(topic, client=client) + batch = self._make_one(topic, client=client) batch.publish(PAYLOAD) self.assertEqual(batch.messages, [MESSAGE]) @@ -681,7 +683,7 @@ def test_commit_w_bound_client(self): api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID1, MSGID2] topic = _Topic() - batch = self._makeOne(topic, client=client) + batch = self._make_one(topic, client=client) batch.publish(PAYLOAD1) batch.publish(PAYLOAD2, attr1='value1', attr2='value2') @@ -705,7 +707,7 @@ def test_commit_w_alternate_client(self): api = client2.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID1, MSGID2] topic = _Topic() - batch = self._makeOne(topic, client=client1) + batch = self._make_one(topic, client=client1) batch.publish(PAYLOAD1) batch.publish(PAYLOAD2, attr1='value1', attr2='value2') @@ -728,7 +730,7 @@ def test_context_mgr_success(self): api = client.publisher_api = _FauxPublisherAPI() api._topic_publish_response = [MSGID1, MSGID2] topic = _Topic() - batch = self._makeOne(topic, client=client) + batch = self._make_one(topic, client=client) with batch as other: batch.publish(PAYLOAD1) @@ -749,7 +751,7 @@ def test_context_mgr_failure(self): client = _Client(project='PROJECT') api = client.publisher_api = _FauxPublisherAPI() topic = _Topic() - batch = self._makeOne(topic, client=client) + batch = self._make_one(topic, client=client) try: with batch as other: diff --git a/resource_manager/unit_tests/test_client.py b/resource_manager/unit_tests/test_client.py index dd40f8b6877f..9e73075d5681 100644 --- a/resource_manager/unit_tests/test_client.py +++ b/resource_manager/unit_tests/test_client.py @@ -17,19 +17,20 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.resource_manager.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor(self): from google.cloud.resource_manager.connection import Connection http = object() credentials = _Credentials() - client = self._makeOne(credentials=credentials, http=http) + client = self._make_one(credentials=credentials, http=http) self.assertIsInstance(client.connection, Connection) self.assertEqual(client.connection._credentials, credentials) self.assertEqual(client.connection._http, http) @@ -38,7 +39,7 @@ def test_new_project_factory(self): from google.cloud.resource_manager.project import Project credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) project_id = 'project_id' name = object() labels = object() @@ -66,7 +67,7 @@ def test_fetch_project(self): } credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) # Patch the connection with one we can easily control. client.connection = _Connection(project_resource) @@ -81,7 +82,7 @@ def test_list_projects_return_type(self): from google.cloud.iterator import HTTPIterator credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) # Patch the connection with one we can easily control. client.connection = _Connection({}) @@ -90,7 +91,7 @@ def test_list_projects_return_type(self): def test_list_projects_no_paging(self): credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) PROJECT_ID = 'project-id' PROJECT_NUMBER = 1 @@ -118,7 +119,7 @@ def test_list_projects_no_paging(self): def test_list_projects_with_paging(self): credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) PROJECT_ID1 = 'project-id' PROJECT_NUMBER1 = 1 @@ -181,7 +182,7 @@ def test_list_projects_with_paging(self): def test_list_projects_with_filter(self): credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) PROJECT_ID = 'project-id' PROJECT_NUMBER = 1 @@ -220,7 +221,7 @@ def test_page_empty_response(self): from google.cloud.iterator import Page credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) iterator = client.list_projects() page = Page(iterator, (), None) iterator._page = page @@ -246,7 +247,7 @@ def test_page_non_empty_response(self): } response = {'projects': [api_resource]} credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) def dummy_response(): return response diff --git a/resource_manager/unit_tests/test_connection.py b/resource_manager/unit_tests/test_connection.py index 3b5ff2953ef6..41fef83b585b 100644 --- a/resource_manager/unit_tests/test_connection.py +++ b/resource_manager/unit_tests/test_connection.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.resource_manager.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, conn.API_VERSION, @@ -36,7 +37,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._makeOne() + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL) diff --git a/resource_manager/unit_tests/test_project.py b/resource_manager/unit_tests/test_project.py index e6dc45086202..e80b51d8a78d 100644 --- a/resource_manager/unit_tests/test_project.py +++ b/resource_manager/unit_tests/test_project.py @@ -17,17 +17,18 @@ class TestProject(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.resource_manager.project import Project return Project - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_constructor_defaults(self): client = object() PROJECT_ID = 'project-id' - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) self.assertEqual(project.project_id, PROJECT_ID) self.assertEqual(project._client, client) self.assertIsNone(project.name) @@ -40,8 +41,8 @@ def test_constructor_explicit(self): PROJECT_ID = 'project-id' DISPLAY_NAME = 'name' LABELS = {'foo': 'bar'} - project = self._makeOne(PROJECT_ID, client, - name=DISPLAY_NAME, labels=LABELS) + project = self._make_one(PROJECT_ID, client, + name=DISPLAY_NAME, labels=LABELS) self.assertEqual(project.project_id, PROJECT_ID) self.assertEqual(project._client, client) self.assertEqual(project.name, DISPLAY_NAME) @@ -61,7 +62,7 @@ def test_from_api_repr(self): 'projectNumber': PROJECT_NUMBER, 'labels': PROJECT_LABELS, 'lifecycleState': PROJECT_LIFECYCLE_STATE} - project = self._getTargetClass().from_api_repr(resource, client) + project = self._get_target_class().from_api_repr(resource, client) self.assertEqual(project.project_id, PROJECT_ID) self.assertEqual(project._client, client) self.assertEqual(project.name, PROJECT_NAME) @@ -71,17 +72,17 @@ def test_from_api_repr(self): def test_full_name(self): PROJECT_ID = 'project-id' - project = self._makeOne(PROJECT_ID, None) + project = self._make_one(PROJECT_ID, None) self.assertEqual('projects/%s' % PROJECT_ID, project.full_name) def test_full_name_missing_id(self): - project = self._makeOne(None, None) + project = self._make_one(None, None) with self.assertRaises(ValueError): self.assertIsNone(project.full_name) def test_path(self): PROJECT_ID = 'project-id' - project = self._makeOne(PROJECT_ID, None) + project = self._make_one(PROJECT_ID, None) self.assertEqual('/projects/%s' % PROJECT_ID, project.path) def test_create(self): @@ -96,7 +97,7 @@ def test_create(self): } connection = _Connection(PROJECT_RESOURCE) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) self.assertIsNone(project.number) project.create() self.assertEqual(project.number, PROJECT_NUMBER) @@ -125,7 +126,7 @@ def test_reload(self): } connection = _Connection(PROJECT_RESOURCE) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) self.assertIsNone(project.number) self.assertIsNone(project.name) self.assertEqual(project.labels, {}) @@ -148,19 +149,19 @@ def test_exists(self): PROJECT_ID = 'project-id' connection = _Connection({'projectId': PROJECT_ID}) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) self.assertTrue(project.exists()) def test_exists_with_explicitly_passed_client(self): PROJECT_ID = 'project-id' connection = _Connection({'projectId': PROJECT_ID}) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, None) + project = self._make_one(PROJECT_ID, None) self.assertTrue(project.exists(client=client)) def test_exists_with_missing_client(self): PROJECT_ID = 'project-id' - project = self._makeOne(PROJECT_ID, None) + project = self._make_one(PROJECT_ID, None) with self.assertRaises(AttributeError): project.exists() @@ -168,7 +169,7 @@ def test_exists_not_found(self): PROJECT_ID = 'project-id' connection = _Connection() client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) self.assertFalse(project.exists()) def test_update(self): @@ -185,7 +186,7 @@ def test_update(self): } connection = _Connection(PROJECT_RESOURCE) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) project.name = PROJECT_NAME project.labels = LABELS project.update() @@ -213,7 +214,7 @@ def test_delete_without_reload_data(self): } connection = _Connection(PROJECT_RESOURCE) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) project.delete(reload_data=False) request, = connection._requested @@ -239,7 +240,7 @@ def test_delete_with_reload_data(self): connection = _Connection(PROJECT_RESOURCE, DELETING_PROJECT) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) project.delete(reload_data=True) self.assertEqual(project.status, NEW_STATE) @@ -270,7 +271,7 @@ def test_undelete_without_reload_data(self): } connection = _Connection(PROJECT_RESOURCE) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) project.undelete(reload_data=False) request, = connection._requested @@ -296,7 +297,7 @@ def test_undelete_with_reload_data(self): connection = _Connection(PROJECT_RESOURCE, UNDELETED_PROJECT) client = _Client(connection=connection) - project = self._makeOne(PROJECT_ID, client) + project = self._make_one(PROJECT_ID, client) project.undelete(reload_data=True) self.assertEqual(project.status, NEW_STATE) diff --git a/runtimeconfig/unit_tests/test__helpers.py b/runtimeconfig/unit_tests/test__helpers.py index 936326c90b87..3c274532f08b 100644 --- a/runtimeconfig/unit_tests/test__helpers.py +++ b/runtimeconfig/unit_tests/test__helpers.py @@ -17,7 +17,7 @@ class Test_config_name_from_full_name(unittest.TestCase): - def _callFUT(self, full_name): + def _call_fut(self, full_name): from google.cloud.runtimeconfig._helpers import ( config_name_from_full_name) return config_name_from_full_name(full_name) @@ -26,25 +26,25 @@ def test_w_simple_name(self): CONFIG_NAME = 'CONFIG_NAME' PROJECT = 'my-project-1234' PATH = 'projects/%s/configs/%s' % (PROJECT, CONFIG_NAME) - config_name = self._callFUT(PATH) + config_name = self._call_fut(PATH) self.assertEqual(config_name, CONFIG_NAME) def test_w_name_w_all_extras(self): CONFIG_NAME = 'CONFIG_NAME-part.one~part.two%part-three' PROJECT = 'my-project-1234' PATH = 'projects/%s/configs/%s' % (PROJECT, CONFIG_NAME) - config_name = self._callFUT(PATH) + config_name = self._call_fut(PATH) self.assertEqual(config_name, CONFIG_NAME) def test_w_bad_format(self): PATH = 'definitley/not/a/resource-name' with self.assertRaises(ValueError): - self._callFUT(PATH) + self._call_fut(PATH) class Test_variable_name_from_full_name(unittest.TestCase): - def _callFUT(self, full_name): + def _call_fut(self, full_name): from google.cloud.runtimeconfig._helpers import ( variable_name_from_full_name) return variable_name_from_full_name(full_name) @@ -55,7 +55,7 @@ def test_w_simple_name(self): PROJECT = 'my-project-1234' PATH = 'projects/%s/configs/%s/variables/%s' % ( PROJECT, CONFIG_NAME, VARIABLE_NAME) - variable_name = self._callFUT(PATH) + variable_name = self._call_fut(PATH) self.assertEqual(variable_name, VARIABLE_NAME) def test_w_name_w_all_extras(self): @@ -64,10 +64,10 @@ def test_w_name_w_all_extras(self): PROJECT = 'my-project-1234' PATH = 'projects/%s/configs/%s/variables/%s' % ( PROJECT, CONFIG_NAME, VARIABLE_NAME) - variable_name = self._callFUT(PATH) + variable_name = self._call_fut(PATH) self.assertEqual(variable_name, VARIABLE_NAME) def test_w_bad_format(self): PATH = 'definitley/not/a/resource/name/for/a/variable' with self.assertRaises(ValueError): - self._callFUT(PATH) + self._call_fut(PATH) diff --git a/runtimeconfig/unit_tests/test_client.py b/runtimeconfig/unit_tests/test_client.py index 943385230e8b..2f2be64ebe18 100644 --- a/runtimeconfig/unit_tests/test_client.py +++ b/runtimeconfig/unit_tests/test_client.py @@ -17,19 +17,20 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.runtimeconfig.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_config(self): PROJECT = 'PROJECT' CONFIG_NAME = 'config_name' creds = _Credentials() - client_obj = self._makeOne(project=PROJECT, credentials=creds) + client_obj = self._make_one(project=PROJECT, credentials=creds) new_config = client_obj.config(CONFIG_NAME) self.assertEqual(new_config.name, CONFIG_NAME) self.assertIs(new_config._client, client_obj) diff --git a/runtimeconfig/unit_tests/test_config.py b/runtimeconfig/unit_tests/test_config.py index d58184bd58b6..615a61ee1568 100644 --- a/runtimeconfig/unit_tests/test_config.py +++ b/runtimeconfig/unit_tests/test_config.py @@ -20,12 +20,13 @@ class TestConfig(unittest.TestCase): CONFIG_NAME = 'config_name' CONFIG_PATH = 'projects/%s/configs/%s' % (PROJECT, CONFIG_NAME) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.runtimeconfig.config import Config return Config - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _verifyResourceProperties(self, config, resource): from google.cloud.runtimeconfig._helpers import ( @@ -41,22 +42,22 @@ def _verifyResourceProperties(self, config, resource): def test_ctor(self): client = _Client(project=self.PROJECT) - config = self._makeOne(name=self.CONFIG_NAME, - client=client) + config = self._make_one(name=self.CONFIG_NAME, + client=client) self.assertEqual(config.name, self.CONFIG_NAME) self.assertEqual(config.project, self.PROJECT) self.assertEqual(config.full_name, self.CONFIG_PATH) def test_ctor_w_no_name(self): client = _Client(project=self.PROJECT) - config = self._makeOne(name=None, client=client) + config = self._make_one(name=None, client=client) with self.assertRaises(ValueError): getattr(config, 'full_name') def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(client=client, name=self.CONFIG_NAME) + config = self._make_one(client=client, name=self.CONFIG_NAME) self.assertFalse(config.exists()) @@ -71,7 +72,7 @@ def test_exists_hit_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection({}) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - config = self._makeOne(client=CLIENT1, name=self.CONFIG_NAME) + config = self._make_one(client=CLIENT1, name=self.CONFIG_NAME) self.assertTrue(config.exists(client=CLIENT2)) @@ -86,7 +87,7 @@ def test_reload_w_empty_resource(self): RESOURCE = {} conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) config.reload() @@ -102,7 +103,7 @@ def test_reload_w_bound_client(self): RESOURCE = {'name': self.CONFIG_PATH, 'description': 'hello'} conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) config.reload() @@ -118,7 +119,7 @@ def test_reload_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - config = self._makeOne(name=self.CONFIG_NAME, client=CLIENT1) + config = self._make_one(name=self.CONFIG_NAME, client=CLIENT1) config.reload(client=CLIENT2) @@ -134,7 +135,7 @@ def test_variable(self): VARIABLE_PATH = '%s/variables/%s' % (self.CONFIG_PATH, VARIABLE_NAME) conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) variable = config.variable(VARIABLE_NAME) @@ -155,7 +156,7 @@ def test_get_variable_w_bound_client(self): } conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) variable = config.get_variable(VARIABLE_NAME) @@ -175,7 +176,7 @@ def test_get_variable_w_notfound(self): VARIABLE_NAME = 'my-variable/abcd' conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) variable = config.get_variable(VARIABLE_NAME) self.assertIsNone(variable) @@ -194,7 +195,7 @@ def test_get_variable_w_alternate_client(self): CLIENT1 = _Client(project=self.PROJECT, connection=conn1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - config = self._makeOne(client=CLIENT1, name=self.CONFIG_NAME) + config = self._make_one(client=CLIENT1, name=self.CONFIG_NAME) variable = config.get_variable(VARIABLE_NAME, client=CLIENT2) @@ -216,7 +217,7 @@ def test_list_variables_empty(self): conn = _Connection({}) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) iterator = config.list_variables() page = six.next(iterator.pages) @@ -254,7 +255,7 @@ def test_list_variables_defaults(self): conn = _Connection(DATA) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) iterator = config.list_variables() page = six.next(iterator.pages) @@ -297,7 +298,7 @@ def test_list_variables_explicit(self): conn = _Connection(DATA) client = _Client(project=self.PROJECT, connection=conn) - config = self._makeOne(name=self.CONFIG_NAME, client=client) + config = self._make_one(name=self.CONFIG_NAME, client=client) iterator = config.list_variables( page_size=3, diff --git a/runtimeconfig/unit_tests/test_connection.py b/runtimeconfig/unit_tests/test_connection.py index efba72635615..3d5d8277bd16 100644 --- a/runtimeconfig/unit_tests/test_connection.py +++ b/runtimeconfig/unit_tests/test_connection.py @@ -17,17 +17,18 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.runtimeconfig.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_default_url(self): creds = _Credentials() - conn = self._makeOne(creds) - klass = self._getTargetClass() + conn = self._make_one(creds) + klass = self._get_target_class() self.assertEqual(conn.credentials._scopes, klass.SCOPE) diff --git a/runtimeconfig/unit_tests/test_variable.py b/runtimeconfig/unit_tests/test_variable.py index dc5df9a0d716..ad51cba666b4 100644 --- a/runtimeconfig/unit_tests/test_variable.py +++ b/runtimeconfig/unit_tests/test_variable.py @@ -22,12 +22,13 @@ class TestVariable(unittest.TestCase): PATH = 'projects/%s/configs/%s/variables/%s' % ( PROJECT, CONFIG_NAME, VARIABLE_NAME) - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.runtimeconfig.variable import Variable return Variable - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _verifyResourceProperties(self, variable, resource): import base64 @@ -57,7 +58,7 @@ def test_ctor(self): client = _Client(project=self.PROJECT) config = Config(name=self.CONFIG_NAME, client=client) - variable = self._makeOne(name=self.VARIABLE_NAME, config=config) + variable = self._make_one(name=self.VARIABLE_NAME, config=config) self.assertEqual(variable.name, self.VARIABLE_NAME) self.assertEqual(variable.full_name, self.PATH) self.assertEqual(variable.path, '/%s' % (self.PATH,)) @@ -68,7 +69,7 @@ def test_ctor_w_no_name(self): client = _Client(project=self.PROJECT) config = Config(name=self.CONFIG_NAME, client=client) - variable = self._makeOne(name=None, config=config) + variable = self._make_one(name=None, config=config) with self.assertRaises(ValueError): getattr(variable, 'full_name') @@ -78,7 +79,7 @@ def test_exists_miss_w_bound_client(self): conn = _Connection() client = _Client(project=self.PROJECT, connection=conn) config = Config(name=self.CONFIG_NAME, client=client) - variable = self._makeOne(name=self.VARIABLE_NAME, config=config) + variable = self._make_one(name=self.VARIABLE_NAME, config=config) self.assertFalse(variable.exists()) @@ -96,7 +97,7 @@ def test_exists_hit_w_alternate_client(self): CONFIG1 = Config(name=self.CONFIG_NAME, client=CLIENT1) conn2 = _Connection({}) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - variable = self._makeOne(name=self.VARIABLE_NAME, config=CONFIG1) + variable = self._make_one(name=self.VARIABLE_NAME, config=CONFIG1) self.assertTrue(variable.exists(client=CLIENT2)) @@ -119,7 +120,7 @@ def test_reload_w_bound_client(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) config = Config(name=self.CONFIG_NAME, client=client) - variable = self._makeOne(name=self.VARIABLE_NAME, config=config) + variable = self._make_one(name=self.VARIABLE_NAME, config=config) variable.reload() @@ -136,7 +137,7 @@ def test_reload_w_empty_resource(self): conn = _Connection(RESOURCE) client = _Client(project=self.PROJECT, connection=conn) config = Config(name=self.CONFIG_NAME, client=client) - variable = self._makeOne(name=self.VARIABLE_NAME, config=config) + variable = self._make_one(name=self.VARIABLE_NAME, config=config) variable.reload() @@ -163,7 +164,7 @@ def test_reload_w_alternate_client(self): CONFIG1 = Config(name=self.CONFIG_NAME, client=CLIENT1) conn2 = _Connection(RESOURCE) CLIENT2 = _Client(project=self.PROJECT, connection=conn2) - variable = self._makeOne(name=self.VARIABLE_NAME, config=CONFIG1) + variable = self._make_one(name=self.VARIABLE_NAME, config=CONFIG1) variable.reload(client=CLIENT2) diff --git a/speech/unit_tests/test__gax.py b/speech/unit_tests/test__gax.py index 31af01178613..2a5b908f5c63 100644 --- a/speech/unit_tests/test__gax.py +++ b/speech/unit_tests/test__gax.py @@ -18,13 +18,14 @@ class TestGAPICSpeechAPI(unittest.TestCase): SAMPLE_RATE = 16000 - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech._gax import GAPICSpeechAPI return GAPICSpeechAPI - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_use_bytes_instead_of_file_like_object(self): from google.cloud import speech @@ -38,7 +39,7 @@ def test_use_bytes_instead_of_file_like_object(self): sample = Sample(content=b'', encoding=speech.Encoding.FLAC, sample_rate=self.SAMPLE_RATE) - api = self._makeOne(client) + api = self._make_one(client) with self.assertRaises(ValueError): api.streaming_recognize(sample) self.assertEqual(client.connection._requested, []) @@ -49,9 +50,9 @@ class TestSpeechGAXMakeRequests(unittest.TestCase): HINTS = ['hi'] AUDIO_CONTENT = b'/9j/4QNURXhpZgAASUkq' - def _callFUT(self, sample, language_code, max_alternatives, - profanity_filter, speech_context, single_utterance, - interim_results): + def _call_fut(self, sample, language_code, max_alternatives, + profanity_filter, speech_context, single_utterance, + interim_results): from google.cloud.speech._gax import _make_streaming_request return _make_streaming_request(sample=sample, language_code=language_code, @@ -83,10 +84,10 @@ def test_ctor(self): single_utterance = True interim_results = False - streaming_request = self._callFUT(sample, language_code, - max_alternatives, profanity_filter, - speech_context, single_utterance, - interim_results) + streaming_request = self._call_fut(sample, language_code, + max_alternatives, profanity_filter, + speech_context, single_utterance, + interim_results) self.assertIsInstance(streaming_request, StreamingRecognizeRequest) # This isn't set by _make_streaming_request(). @@ -114,9 +115,9 @@ class TestSpeechGAXMakeRequestsStream(unittest.TestCase): HINTS = ['hi'] AUDIO_CONTENT = b'/9j/4QNURXhpZgAASUkq' - def _callFUT(self, sample, language_code, max_alternatives, - profanity_filter, speech_context, single_utterance, - interim_results): + def _call_fut(self, sample, language_code, max_alternatives, + profanity_filter, speech_context, single_utterance, + interim_results): from google.cloud.speech._gax import _stream_requests return _stream_requests(sample=sample, language_code=language_code, @@ -146,10 +147,10 @@ def test_stream_requests(self): speech_context = SpeechContext(phrases=self.HINTS) single_utterance = True interim_results = False - streaming_requests = self._callFUT(sample, language_code, - max_alternatives, profanity_filter, - speech_context, single_utterance, - interim_results) + streaming_requests = self._call_fut(sample, language_code, + max_alternatives, profanity_filter, + speech_context, single_utterance, + interim_results) all_requests = [] for streaming_request in streaming_requests: self.assertIsInstance(streaming_request, StreamingRecognizeRequest) diff --git a/speech/unit_tests/test_alternative.py b/speech/unit_tests/test_alternative.py index ac6d9f56fcfb..c6a8ada6bb8b 100644 --- a/speech/unit_tests/test_alternative.py +++ b/speech/unit_tests/test_alternative.py @@ -17,28 +17,29 @@ class TestAlternative(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech.alternative import Alternative return Alternative - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): text = 'hello goodbye upstairs' confidence = 0.5546875 - alternative = self._makeOne(text, confidence) + alternative = self._make_one(text, confidence) self.assertEqual(alternative._transcript, text) self.assertEqual(alternative._confidence, confidence) def test_transcript_property(self): text = 'is this thing on?' - alternative = self._makeOne(text, None) + alternative = self._make_one(text, None) self.assertEqual(alternative.transcript, text) def test_confidence_property(self): confidence = 0.412109375 - alternative = self._makeOne(None, confidence) + alternative = self._make_one(None, confidence) self.assertEqual(alternative.confidence, confidence) def test_from_api_repr_with_no_confidence(self): @@ -46,7 +47,7 @@ def test_from_api_repr_with_no_confidence(self): 'transcript': 'testing 1 2 3', } - klass = self._getTargetClass() + klass = self._get_target_class() alternative = klass.from_api_repr(data) self.assertEqual(alternative.transcript, data['transcript']) self.assertIsNone(alternative.confidence) @@ -59,7 +60,7 @@ def test_from_pb_with_no_confidence(self): transcript=text) self.assertEqual(pb_value.confidence, 0.0) - klass = self._getTargetClass() + klass = self._get_target_class() alternative = klass.from_pb(pb_value) self.assertEqual(alternative.transcript, text) self.assertIsNone(alternative.confidence) diff --git a/speech/unit_tests/test_client.py b/speech/unit_tests/test_client.py index b108fcaab579..8291540e0e4f 100644 --- a/speech/unit_tests/test_client.py +++ b/speech/unit_tests/test_client.py @@ -66,20 +66,21 @@ class TestClient(unittest.TestCase): AUDIO_SOURCE_URI = 'gs://sample-bucket/sample-recording.flac' AUDIO_CONTENT = '/9j/4QNURXhpZgAASUkq' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from google.cloud.speech.connection import Connection creds = _Credentials() http = object() - client = self._makeOne(credentials=creds, http=http) + client = self._make_one(credentials=creds, http=http) self.assertIsInstance(client.connection, Connection) self.assertTrue(client.connection.credentials is creds) self.assertTrue(client.connection.http is http) @@ -87,7 +88,7 @@ def test_ctor(self): def test_ctor_use_gax_preset(self): creds = _Credentials() http = object() - client = self._makeOne(credentials=creds, http=http, use_gax=True) + client = self._make_one(credentials=creds, http=http, use_gax=True) self.assertTrue(client._use_gax) def test_create_sample_from_client(self): @@ -95,7 +96,7 @@ def test_create_sample_from_client(self): from google.cloud.speech.sample import Sample credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, @@ -144,7 +145,7 @@ def test_sync_recognize_content_with_optional_params_no_gax(self): } } credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=False) + client = self._make_one(credentials=credentials, use_gax=False) client.connection = _Connection(RETURNED) encoding = speech.Encoding.FLAC @@ -189,7 +190,7 @@ def test_sync_recognize_source_uri_without_optional_params_no_gax(self): } } credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=False) + client = self._make_one(credentials=credentials, use_gax=False) client.connection = _Connection(RETURNED) encoding = speech.Encoding.FLAC @@ -219,7 +220,7 @@ def test_sync_recognize_with_empty_results_no_gax(self): from unit_tests._fixtures import SYNC_RECOGNIZE_EMPTY_RESPONSE credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=False) + client = self._make_one(credentials=credentials, use_gax=False) client.connection = _Connection(SYNC_RECOGNIZE_EMPTY_RESPONSE) sample = Sample(source_uri=self.AUDIO_SOURCE_URI, @@ -237,7 +238,7 @@ def test_sync_recognize_with_empty_results_gax(self): from google.cloud.speech.sample import Sample credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=True) + client = self._make_one(credentials=credentials, use_gax=True) client.connection = _Connection() client.connection.credentials = credentials @@ -280,7 +281,7 @@ def test_sync_recognize_with_gax(self): from google.cloud.speech import _gax creds = _Credentials() - client = self._makeOne(credentials=creds, use_gax=True) + client = self._make_one(credentials=creds, use_gax=True) client.connection = _Connection() client.connection.credentials = creds client._speech_api = None @@ -341,7 +342,7 @@ def test_async_supported_encodings(self): from google.cloud.speech.sample import Sample credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) client.connection = _Connection({}) sample = Sample(source_uri=self.AUDIO_SOURCE_URI, @@ -359,7 +360,7 @@ def test_async_recognize_no_gax(self): RETURNED = ASYNC_RECOGNIZE_RESPONSE credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=False) + client = self._make_one(credentials=credentials, use_gax=False) client.connection = _Connection(RETURNED) sample = Sample(source_uri=self.AUDIO_SOURCE_URI, @@ -381,8 +382,8 @@ def test_async_recognize_with_gax(self): from google.cloud.speech.operation import Operation credentials = _Credentials() - client = self._makeOne(credentials=credentials, - use_gax=True) + client = self._make_one(credentials=credentials, + use_gax=True) client.connection = _Connection() client.connection.credentials = credentials @@ -423,7 +424,7 @@ def test_streaming_depends_on_gax(self): from google.cloud._testing import _Monkey credentials = _Credentials() - client = self._makeOne(credentials=credentials, use_gax=False) + client = self._make_one(credentials=credentials, use_gax=False) client.connection = _Connection() with self.assertRaises(EnvironmentError): @@ -439,7 +440,7 @@ def test_streaming_closed_stream(self): stream = BytesIO(b'Some audio data...') credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) client.connection = _Connection() client.connection.credentials = credentials @@ -479,7 +480,7 @@ def test_stream_recognize_interim_results(self): stream = BytesIO(b'Some audio data...') credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) client.connection = _Connection() client.connection.credentials = credentials @@ -541,7 +542,7 @@ def test_stream_recognize(self): stream = BytesIO(b'Some audio data...') credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) client.connection = _Connection() client.connection.credentials = credentials @@ -597,7 +598,7 @@ def test_stream_recognize_no_results(self): stream = BytesIO(b'Some audio data...') credentials = _Credentials() - client = self._makeOne(credentials=credentials) + client = self._make_one(credentials=credentials) client.connection = _Connection() client.connection.credentials = credentials @@ -633,7 +634,7 @@ def test_speech_api_with_gax(self): from google.cloud.speech import _gax creds = _Credentials() - client = self._makeOne(credentials=creds, use_gax=True) + client = self._make_one(credentials=creds, use_gax=True) client.connection = _Connection() client.connection.credentials = creds @@ -666,14 +667,14 @@ def test_speech_api_without_gax(self): from google.cloud.speech.client import _JSONSpeechAPI creds = _Credentials() - client = self._makeOne(credentials=creds, use_gax=False) + client = self._make_one(credentials=creds, use_gax=False) self.assertIsNone(client._speech_api) self.assertIsInstance(client.speech_api, _JSONSpeechAPI) self.assertIsInstance(client.speech_api.connection, Connection) def test_speech_api_preset(self): creds = _Credentials() - client = self._makeOne(credentials=creds) + client = self._make_one(credentials=creds) fake_api = object() client._speech_api = fake_api diff --git a/speech/unit_tests/test_connection.py b/speech/unit_tests/test_connection.py index 0de94cb1d7c1..48b2e8577080 100644 --- a/speech/unit_tests/test_connection.py +++ b/speech/unit_tests/test_connection.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url(self): - conn = self._makeOne() + conn = self._make_one() method = 'speech:syncrecognize' uri = '/'.join([ conn.API_BASE_URL, diff --git a/speech/unit_tests/test_operation.py b/speech/unit_tests/test_operation.py index dd0dbd4a1d72..d1388a15f919 100644 --- a/speech/unit_tests/test_operation.py +++ b/speech/unit_tests/test_operation.py @@ -19,16 +19,17 @@ class TestOperation(unittest.TestCase): OPERATION_NAME = '123456789' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech.operation import Operation return Operation - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) + def _make_one(self, *args, **kwargs): + return self._get_target_class()(*args, **kwargs) def test_constructor(self): client = object() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client) self.assertEqual(operation.name, self.OPERATION_NAME) self.assertIs(operation.client, client) @@ -74,7 +75,7 @@ def _make_operation_pb(self, *results): def test__update_state_no_response(self): client = object() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client) operation_pb = self._make_operation_pb() @@ -86,7 +87,7 @@ def test__update_state_with_response(self): from google.cloud.speech.alternative import Alternative client = object() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client) text = 'hi mom' @@ -104,7 +105,7 @@ def test__update_state_with_response(self): def test__update_state_bad_response(self): client = object() - operation = self._makeOne( + operation = self._make_one( self.OPERATION_NAME, client) result1 = self._make_result('is this ok?', 0.625) diff --git a/speech/unit_tests/test_sample.py b/speech/unit_tests/test_sample.py index 54f23963ceff..15f3604dfffd 100644 --- a/speech/unit_tests/test_sample.py +++ b/speech/unit_tests/test_sample.py @@ -19,59 +19,60 @@ class TestSample(unittest.TestCase): SAMPLE_RATE = 16000 AUDIO_SOURCE_URI = 'gs://sample-bucket/sample-recording.flac' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.speech.sample import Sample return Sample - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_initialize_sample(self): from google.cloud.speech.encoding import Encoding - sample = self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - encoding=Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, + encoding=Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) self.assertEqual(sample.source_uri, self.AUDIO_SOURCE_URI) self.assertEqual(sample.encoding, Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) def test_content_and_source_uri(self): with self.assertRaises(ValueError): - self._makeOne(content='awefawagaeragere', - source_uri=self.AUDIO_SOURCE_URI) + self._make_one(content='awefawagaeragere', + source_uri=self.AUDIO_SOURCE_URI) def test_sample_rates(self): from google.cloud.speech.encoding import Encoding with self.assertRaises(ValueError): - self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=7999) + self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=7999) with self.assertRaises(ValueError): - self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=48001) + self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=48001) - sample = self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding=Encoding.FLAC) + sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=self.SAMPLE_RATE, + encoding=Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) self.assertEqual(sample.encoding, Encoding.FLAC) - sample = self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - encoding=Encoding.FLAC) + sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, + encoding=Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) def test_encoding(self): from google.cloud.speech.encoding import Encoding with self.assertRaises(ValueError): - self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding='OGG') + self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=self.SAMPLE_RATE, + encoding='OGG') with self.assertRaises(ValueError): - self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE) - sample = self._makeOne(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding=Encoding.FLAC) + self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=self.SAMPLE_RATE) + sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, + sample_rate=self.SAMPLE_RATE, + encoding=Encoding.FLAC) self.assertEqual(sample.encoding, Encoding.FLAC) diff --git a/storage/unit_tests/test__helpers.py b/storage/unit_tests/test__helpers.py index f80a7207a7d5..039c29c64128 100644 --- a/storage/unit_tests/test__helpers.py +++ b/storage/unit_tests/test__helpers.py @@ -17,16 +17,17 @@ class Test_PropertyMixin(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage._helpers import _PropertyMixin return _PropertyMixin - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def _derivedClass(self, path=None): - class Derived(self._getTargetClass()): + class Derived(self._get_target_class()): client = None @@ -37,11 +38,11 @@ def path(self): return Derived def test_path_is_abstract(self): - mixin = self._makeOne() + mixin = self._make_one() self.assertRaises(NotImplementedError, lambda: mixin.path) def test_client_is_abstract(self): - mixin = self._makeOne() + mixin = self._make_one() self.assertRaises(NotImplementedError, lambda: mixin.client) def test_reload(self): @@ -61,7 +62,7 @@ def test_reload(self): self.assertEqual(derived._changes, set()) def test__set_properties(self): - mixin = self._makeOne() + mixin = self._make_one() self.assertEqual(mixin._properties, {}) VALUE = object() mixin._set_properties(VALUE) @@ -96,7 +97,7 @@ def test_patch(self): class Test__scalar_property(unittest.TestCase): - def _callFUT(self, fieldName): + def _call_fut(self, fieldName): from google.cloud.storage._helpers import _scalar_property return _scalar_property(fieldName) @@ -105,7 +106,7 @@ def test_getter(self): class Test(object): def __init__(self, **kw): self._properties = kw.copy() - do_re_mi = self._callFUT('solfege') + do_re_mi = self._call_fut('solfege') test = Test(solfege='Latido') self.assertEqual(test.do_re_mi, 'Latido') @@ -115,7 +116,7 @@ def test_setter(self): class Test(object): def _patch_property(self, name, value): self._patched = (name, value) - do_re_mi = self._callFUT('solfege') + do_re_mi = self._call_fut('solfege') test = Test() test.do_re_mi = 'Latido' @@ -124,7 +125,7 @@ def _patch_property(self, name, value): class Test__base64_md5hash(unittest.TestCase): - def _callFUT(self, bytes_to_sign): + def _call_fut(self, bytes_to_sign): from google.cloud.storage._helpers import _base64_md5hash return _base64_md5hash(bytes_to_sign) @@ -135,7 +136,7 @@ def test_it(self): BUFFER.write(BYTES_TO_SIGN) BUFFER.seek(0) - SIGNED_CONTENT = self._callFUT(BUFFER) + SIGNED_CONTENT = self._call_fut(BUFFER) self.assertEqual(SIGNED_CONTENT, b'kBiQqOnIz21aGlQrIp/r/w==') def test_it_with_stubs(self): @@ -159,7 +160,7 @@ def read(self, block_size): MD5 = _MD5(DIGEST_VAL) with _Monkey(MUT, base64=BASE64, md5=MD5): - SIGNED_CONTENT = self._callFUT(BUFFER) + SIGNED_CONTENT = self._call_fut(BUFFER) self.assertEqual(BUFFER._block_sizes, [8192, 8192]) self.assertIs(SIGNED_CONTENT, DIGEST_VAL) diff --git a/storage/unit_tests/test__http.py b/storage/unit_tests/test__http.py index e2034a6758f9..73763bd0e660 100644 --- a/storage/unit_tests/test__http.py +++ b/storage/unit_tests/test__http.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage._http import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, 'storage', @@ -37,7 +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._makeOne() + conn = self._make_one() uri = conn.build_api_url('/foo', {'bar': 'baz'}) scheme, netloc, path, qs, _ = urlsplit(uri) self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL) diff --git a/storage/unit_tests/test_acl.py b/storage/unit_tests/test_acl.py index a24628f642b8..e58138b32c31 100644 --- a/storage/unit_tests/test_acl.py +++ b/storage/unit_tests/test_acl.py @@ -17,16 +17,17 @@ class Test_ACLEntity(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.acl import _ACLEntity return _ACLEntity - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_default_identifier(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) self.assertEqual(entity.type, TYPE) self.assertIsNone(entity.identifier) self.assertEqual(entity.get_roles(), set()) @@ -34,26 +35,26 @@ def test_ctor_default_identifier(self): def test_ctor_w_identifier(self): TYPE = 'type' ID = 'id' - entity = self._makeOne(TYPE, ID) + entity = self._make_one(TYPE, ID) self.assertEqual(entity.type, TYPE) self.assertEqual(entity.identifier, ID) self.assertEqual(entity.get_roles(), set()) def test___str__no_identifier(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) self.assertEqual(str(entity), TYPE) def test___str__w_identifier(self): TYPE = 'type' ID = 'id' - entity = self._makeOne(TYPE, ID) + entity = self._make_one(TYPE, ID) self.assertEqual(str(entity), '%s-%s' % (TYPE, ID)) def test_grant_simple(self): TYPE = 'type' ROLE = 'role' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(ROLE) self.assertEqual(entity.get_roles(), set([ROLE])) @@ -61,7 +62,7 @@ def test_grant_duplicate(self): TYPE = 'type' ROLE1 = 'role1' ROLE2 = 'role2' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(ROLE1) entity.grant(ROLE2) entity.grant(ROLE1) @@ -70,7 +71,7 @@ def test_grant_duplicate(self): def test_revoke_miss(self): TYPE = 'type' ROLE = 'nonesuch' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.revoke(ROLE) self.assertEqual(entity.get_roles(), set()) @@ -78,7 +79,7 @@ def test_revoke_hit(self): TYPE = 'type' ROLE1 = 'role1' ROLE2 = 'role2' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(ROLE1) entity.grant(ROLE2) entity.revoke(ROLE1) @@ -86,39 +87,39 @@ def test_revoke_hit(self): def test_grant_read(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant_read() self.assertEqual(entity.get_roles(), set([entity.READER_ROLE])) def test_grant_write(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant_write() self.assertEqual(entity.get_roles(), set([entity.WRITER_ROLE])) def test_grant_owner(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant_owner() self.assertEqual(entity.get_roles(), set([entity.OWNER_ROLE])) def test_revoke_read(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(entity.READER_ROLE) entity.revoke_read() self.assertEqual(entity.get_roles(), set()) def test_revoke_write(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(entity.WRITER_ROLE) entity.revoke_write() self.assertEqual(entity.get_roles(), set()) def test_revoke_owner(self): TYPE = 'type' - entity = self._makeOne(TYPE) + entity = self._make_one(TYPE) entity.grant(entity.OWNER_ROLE) entity.revoke_owner() self.assertEqual(entity.get_roles(), set()) @@ -126,20 +127,21 @@ def test_revoke_owner(self): class Test_ACL(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.acl import ACL return ACL - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): - acl = self._makeOne() + acl = self._make_one() self.assertEqual(acl.entities, {}) self.assertFalse(acl.loaded) def test__ensure_loaded(self): - acl = self._makeOne() + acl = self._make_one() def _reload(): acl._really_loaded = True @@ -149,13 +151,13 @@ def _reload(): self.assertTrue(acl._really_loaded) def test_client_is_abstract(self): - acl = self._makeOne() + acl = self._make_one() self.assertRaises(NotImplementedError, lambda: acl.client) def test_reset(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True acl.entity(TYPE, ID) acl.reset() @@ -163,12 +165,12 @@ def test_reset(self): self.assertFalse(acl.loaded) def test___iter___empty_eager(self): - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertEqual(list(acl), []) def test___iter___empty_lazy(self): - acl = self._makeOne() + acl = self._make_one() def _reload(): acl.loaded = True @@ -180,7 +182,7 @@ def _reload(): def test___iter___non_empty_no_roles(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True acl.entity(TYPE, ID) self.assertEqual(list(acl), []) @@ -189,7 +191,7 @@ def test___iter___non_empty_w_roles(self): TYPE = 'type' ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) entity.grant(ROLE) @@ -199,7 +201,7 @@ def test___iter___non_empty_w_roles(self): def test___iter___non_empty_w_empty_role(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) entity.grant('') @@ -207,7 +209,7 @@ def test___iter___non_empty_w_empty_role(self): def test_entity_from_dict_allUsers_eager(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity_from_dict({'entity': 'allUsers', 'role': ROLE}) self.assertEqual(entity.type, 'allUsers') @@ -219,7 +221,7 @@ def test_entity_from_dict_allUsers_eager(self): def test_entity_from_dict_allAuthenticatedUsers(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity_from_dict({'entity': 'allAuthenticatedUsers', 'role': ROLE}) @@ -232,7 +234,7 @@ def test_entity_from_dict_allAuthenticatedUsers(self): def test_entity_from_dict_string_w_hyphen(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity_from_dict({'entity': 'type-id', 'role': ROLE}) self.assertEqual(entity.type, 'type') @@ -244,7 +246,7 @@ def test_entity_from_dict_string_w_hyphen(self): def test_entity_from_dict_string_wo_hyphen(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertRaises(ValueError, acl.entity_from_dict, @@ -252,12 +254,12 @@ def test_entity_from_dict_string_wo_hyphen(self): self.assertEqual(list(acl.get_entities()), []) def test_has_entity_miss_str_eager(self): - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertFalse(acl.has_entity('nonesuch')) def test_has_entity_miss_str_lazy(self): - acl = self._makeOne() + acl = self._make_one() def _reload(): acl.loaded = True @@ -271,14 +273,14 @@ def test_has_entity_miss_entity(self): TYPE = 'type' ID = 'id' entity = _ACLEntity(TYPE, ID) - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertFalse(acl.has_entity(entity)) def test_has_entity_hit_str(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True acl.entity(TYPE, ID) self.assertTrue(acl.has_entity('%s-%s' % (TYPE, ID))) @@ -286,18 +288,18 @@ def test_has_entity_hit_str(self): def test_has_entity_hit_entity(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) self.assertTrue(acl.has_entity(entity)) def test_get_entity_miss_str_no_default_eager(self): - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertIsNone(acl.get_entity('nonesuch')) def test_get_entity_miss_str_no_default_lazy(self): - acl = self._makeOne() + acl = self._make_one() def _reload(): acl.loaded = True @@ -311,13 +313,13 @@ def test_get_entity_miss_entity_no_default(self): TYPE = 'type' ID = 'id' entity = _ACLEntity(TYPE, ID) - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertIsNone(acl.get_entity(entity)) def test_get_entity_miss_str_w_default(self): DEFAULT = object() - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertIs(acl.get_entity('nonesuch', DEFAULT), DEFAULT) @@ -327,14 +329,14 @@ def test_get_entity_miss_entity_w_default(self): TYPE = 'type' ID = 'id' entity = _ACLEntity(TYPE, ID) - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertIs(acl.get_entity(entity, DEFAULT), DEFAULT) def test_get_entity_hit_str(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True acl.entity(TYPE, ID) self.assertTrue(acl.has_entity('%s-%s' % (TYPE, ID))) @@ -342,7 +344,7 @@ def test_get_entity_hit_str(self): def test_get_entity_hit_entity(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) self.assertTrue(acl.has_entity(entity)) @@ -354,7 +356,7 @@ def test_add_entity_miss_eager(self): ROLE = 'role' entity = _ACLEntity(TYPE, ID) entity.grant(ROLE) - acl = self._makeOne() + acl = self._make_one() acl.loaded = True acl.add_entity(entity) self.assertTrue(acl.loaded) @@ -369,7 +371,7 @@ def test_add_entity_miss_lazy(self): ROLE = 'role' entity = _ACLEntity(TYPE, ID) entity.grant(ROLE) - acl = self._makeOne() + acl = self._make_one() def _reload(): acl.loaded = True @@ -390,7 +392,7 @@ def test_add_entity_hit(self): ROLE = 'role' entity = _ACLEntity(TYPE, ID) entity.grant(ROLE) - acl = self._makeOne() + acl = self._make_one() acl.loaded = True before = acl.entity(TYPE, ID) acl.add_entity(entity) @@ -405,7 +407,7 @@ def test_entity_miss(self): TYPE = 'type' ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) self.assertTrue(acl.loaded) @@ -418,7 +420,7 @@ def test_entity_hit(self): TYPE = 'type' ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True before = acl.entity(TYPE, ID) before.grant(ROLE) @@ -431,7 +433,7 @@ def test_entity_hit(self): def test_user(self): ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.user(ID) entity.grant(ROLE) @@ -443,7 +445,7 @@ def test_user(self): def test_group(self): ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.group(ID) entity.grant(ROLE) @@ -455,7 +457,7 @@ def test_group(self): def test_domain(self): ID = 'id' ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.domain(ID) entity.grant(ROLE) @@ -466,7 +468,7 @@ def test_domain(self): def test_all(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.all() entity.grant(ROLE) @@ -477,7 +479,7 @@ def test_all(self): def test_all_authenticated(self): ROLE = 'role' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.all_authenticated() entity.grant(ROLE) @@ -487,12 +489,12 @@ def test_all_authenticated(self): [{'entity': 'allAuthenticatedUsers', 'role': ROLE}]) def test_get_entities_empty_eager(self): - acl = self._makeOne() + acl = self._make_one() acl.loaded = True self.assertEqual(acl.get_entities(), []) def test_get_entities_empty_lazy(self): - acl = self._makeOne() + acl = self._make_one() def _reload(): acl.loaded = True @@ -504,7 +506,7 @@ def _reload(): def test_get_entities_nonempty(self): TYPE = 'type' ID = 'id' - acl = self._makeOne() + acl = self._make_one() acl.loaded = True entity = acl.entity(TYPE, ID) self.assertEqual(acl.get_entities(), [entity]) @@ -514,7 +516,7 @@ def test_reload_missing(self): ROLE = 'role' connection = _Connection({}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.reload_path = '/testing/acl' acl.loaded = True acl.entity('allUsers', ROLE) @@ -529,7 +531,7 @@ def test_reload_empty_result_clears_local(self): ROLE = 'role' connection = _Connection({'items': []}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.reload_path = '/testing/acl' acl.loaded = True acl.entity('allUsers', ROLE) @@ -546,7 +548,7 @@ def test_reload_nonempty_result(self): connection = _Connection( {'items': [{'entity': 'allUsers', 'role': ROLE}]}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.reload_path = '/testing/acl' acl.loaded = True acl.reload(client=client) @@ -560,7 +562,7 @@ def test_reload_nonempty_result(self): def test_save_none_set_none_passed(self): connection = _Connection() client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.save(client=client) kw = connection._requested @@ -569,7 +571,7 @@ def test_save_none_set_none_passed(self): def test_save_existing_missing_none_passed(self): connection = _Connection({}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.save(client=client) @@ -586,7 +588,7 @@ def test_save_no_acl(self): AFTER = [{'entity': 'allUsers', 'role': ROLE}] connection = _Connection({'acl': AFTER}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.entity('allUsers').grant(ROLE) @@ -606,7 +608,7 @@ def test_save_w_acl(self): new_acl = [{'entity': 'allUsers', 'role': ROLE1}] connection = _Connection({'acl': [STICKY] + new_acl}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.save(new_acl, client=client) @@ -624,7 +626,7 @@ def test_save_w_acl(self): def test_save_prefefined_invalid(self): connection = _Connection() client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True with self.assertRaises(ValueError): @@ -634,7 +636,7 @@ def test_save_predefined_valid(self): PREDEFINED = 'private' connection = _Connection({'acl': []}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.save_predefined(PREDEFINED, client=client) @@ -653,7 +655,7 @@ def test_save_predefined_w_XML_alias(self): PREDEFINED_JSON = 'projectPrivate' connection = _Connection({'acl': []}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.save_predefined(PREDEFINED_XML, client=client) @@ -673,7 +675,7 @@ def test_save_predefined_valid_w_alternate_query_param(self): PREDEFINED = 'publicRead' connection = _Connection({'acl': []}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl._PREDEFINED_QUERY_PARAM = 'alternate' @@ -694,7 +696,7 @@ def test_clear(self): STICKY = {'entity': 'allUsers', 'role': ROLE2} connection = _Connection({'acl': [STICKY]}) client = _Client(connection) - acl = self._makeOne() + acl = self._make_one() acl.save_path = '/testing' acl.loaded = True acl.entity('allUsers', ROLE1) @@ -710,17 +712,18 @@ def test_clear(self): class Test_BucketACL(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.acl import BucketACL return BucketACL - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): NAME = 'name' bucket = _Bucket(NAME) - acl = self._makeOne(bucket) + acl = self._make_one(bucket) self.assertEqual(acl.entities, {}) self.assertFalse(acl.loaded) self.assertIs(acl.bucket, bucket) @@ -730,17 +733,18 @@ def test_ctor(self): class Test_DefaultObjectACL(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.acl import DefaultObjectACL return DefaultObjectACL - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): NAME = 'name' bucket = _Bucket(NAME) - acl = self._makeOne(bucket) + acl = self._make_one(bucket) self.assertEqual(acl.entities, {}) self.assertFalse(acl.loaded) self.assertIs(acl.bucket, bucket) @@ -750,19 +754,20 @@ def test_ctor(self): class Test_ObjectACL(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.acl import ObjectACL return ObjectACL - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): NAME = 'name' BLOB_NAME = 'blob-name' bucket = _Bucket(NAME) blob = _Blob(bucket, BLOB_NAME) - acl = self._makeOne(blob) + acl = self._make_one(blob) self.assertEqual(acl.entities, {}) self.assertFalse(acl.loaded) self.assertIs(acl.blob, blob) diff --git a/storage/unit_tests/test_batch.py b/storage/unit_tests/test_batch.py index 5540533412c7..a340fe253d37 100644 --- a/storage/unit_tests/test_batch.py +++ b/storage/unit_tests/test_batch.py @@ -17,12 +17,13 @@ class TestMIMEApplicationHTTP(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.batch import MIMEApplicationHTTP return MIMEApplicationHTTP - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_body_None(self): METHOD = 'DELETE' @@ -31,7 +32,7 @@ def test_ctor_body_None(self): "DELETE /path/to/api HTTP/1.1", "", ] - mah = self._makeOne(METHOD, PATH, {}, None) + mah = self._make_one(METHOD, PATH, {}, None) self.assertEqual(mah.get_content_type(), 'application/http') self.assertEqual(mah.get_payload().splitlines(), LINES) @@ -47,7 +48,7 @@ def test_ctor_body_str(self): "", "ABC", ] - mah = self._makeOne(METHOD, PATH, HEADERS, BODY) + mah = self._make_one(METHOD, PATH, HEADERS, BODY) self.assertEqual(mah.get_payload().splitlines(), LINES) def test_ctor_body_dict(self): @@ -62,24 +63,25 @@ def test_ctor_body_dict(self): '', '{"foo": "bar"}', ] - mah = self._makeOne(METHOD, PATH, HEADERS, BODY) + mah = self._make_one(METHOD, PATH, HEADERS, BODY) self.assertEqual(mah.get_payload().splitlines(), LINES) class TestBatch(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.batch import Batch return Batch - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): http = _HTTP() connection = _Connection(http=http) client = _Client(connection) - batch = self._makeOne(client) + batch = self._make_one(client) self.assertIs(batch._client, client) self.assertEqual(len(batch._requests), 0) self.assertEqual(len(batch._target_objects), 0) @@ -89,13 +91,13 @@ def test_current(self): project = 'PROJECT' credentials = _Credentials() client = Client(project=project, credentials=credentials) - batch1 = self._makeOne(client) + batch1 = self._make_one(client) self.assertIsNone(batch1.current()) client._push_batch(batch1) self.assertIs(batch1.current(), batch1) - batch2 = self._makeOne(client) + batch2 = self._make_one(client) client._push_batch(batch2) self.assertIs(batch1.current(), batch2) @@ -105,7 +107,7 @@ def test__make_request_GET_normal(self): expected = _Response() http = _HTTP((expected, '')) connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) target = _MockObject() response, content = batch._make_request('GET', URL, target_object=target) @@ -130,7 +132,7 @@ def test__make_request_POST_normal(self): URL = 'http://example.com/api' http = _HTTP() # no requests expected connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) target = _MockObject() response, content = batch._make_request('POST', URL, data={'foo': 1}, target_object=target) @@ -155,7 +157,7 @@ def test__make_request_PATCH_normal(self): URL = 'http://example.com/api' http = _HTTP() # no requests expected connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) target = _MockObject() response, content = batch._make_request('PATCH', URL, data={'foo': 1}, target_object=target) @@ -180,7 +182,7 @@ def test__make_request_DELETE_normal(self): URL = 'http://example.com/api' http = _HTTP() # no requests expected connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) target = _MockObject() response, content = batch._make_request('DELETE', URL, target_object=target) @@ -204,7 +206,7 @@ def test__make_request_POST_too_many_requests(self): URL = 'http://example.com/api' http = _HTTP() # no requests expected connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) batch._MAX_BATCH_SIZE = 1 batch._requests.append(('POST', URL, {}, {'bar': 2})) self.assertRaises(ValueError, @@ -214,7 +216,7 @@ def test__make_request_POST_too_many_requests(self): def test_finish_empty(self): http = _HTTP() # no requests expected connection = _Connection(http=http) - batch = self._makeOne(connection) + batch = self._make_one(connection) self.assertRaises(ValueError, batch.finish) self.assertIs(connection.http, http) @@ -259,7 +261,7 @@ def test_finish_nonempty(self): http = _HTTP((expected, _THREE_PART_MIME_RESPONSE)) connection = _Connection(http=http) client = _Client(connection) - batch = self._makeOne(client) + batch = self._make_one(client) batch.API_BASE_URL = 'http://api.example.com' batch._do_request('POST', URL, {}, {'foo': 1, 'bar': 2}, None) batch._do_request('PATCH', URL, {}, {'bar': 3}, None) @@ -309,7 +311,7 @@ def test_finish_responses_mismatch(self): http = _HTTP((expected, _TWO_PART_MIME_RESPONSE_WITH_FAIL)) connection = _Connection(http=http) client = _Client(connection) - batch = self._makeOne(client) + batch = self._make_one(client) batch.API_BASE_URL = 'http://api.example.com' batch._requests.append(('GET', URL, {}, None)) self.assertRaises(ValueError, batch.finish) @@ -322,7 +324,7 @@ def test_finish_nonempty_with_status_failure(self): http = _HTTP((expected, _TWO_PART_MIME_RESPONSE_WITH_FAIL)) connection = _Connection(http=http) client = _Client(connection) - batch = self._makeOne(client) + batch = self._make_one(client) batch.API_BASE_URL = 'http://api.example.com' target1 = _MockObject() target2 = _MockObject() @@ -363,7 +365,7 @@ def test_finish_nonempty_non_multipart_response(self): http = _HTTP((expected, 'NOT A MIME_RESPONSE')) connection = _Connection(http=http) client = _Client(connection) - batch = self._makeOne(client) + batch = self._make_one(client) batch._requests.append(('POST', URL, {}, {'foo': 1, 'bar': 2})) batch._requests.append(('PATCH', URL, {}, {'bar': 3})) batch._requests.append(('DELETE', URL, {}, None)) @@ -385,7 +387,7 @@ def test_as_context_mgr_wo_error(self): target1 = _MockObject() target2 = _MockObject() target3 = _MockObject() - with self._makeOne(client) as batch: + with self._make_one(client) as batch: self.assertEqual(list(client._batch_stack), [batch]) batch._make_request('POST', URL, {'foo': 1, 'bar': 2}, target_object=target1) @@ -422,7 +424,7 @@ def test_as_context_mgr_w_error(self): target2 = _MockObject() target3 = _MockObject() try: - with self._makeOne(client) as batch: + with self._make_one(client) as batch: self.assertEqual(list(client._batch_stack), [batch]) batch._make_request('POST', URL, {'foo': 1, 'bar': 2}, target_object=target1) @@ -446,13 +448,13 @@ def test_as_context_mgr_w_error(self): class Test__unpack_batch_response(unittest.TestCase): - def _callFUT(self, response, content): + def _call_fut(self, response, content): from google.cloud.storage.batch import _unpack_batch_response return _unpack_batch_response(response, content) def _unpack_helper(self, response, content): import httplib2 - result = list(self._callFUT(response, content)) + result = list(self._call_fut(response, content)) self.assertEqual(len(result), 3) response0 = httplib2.Response({ 'content-length': '20', @@ -537,23 +539,23 @@ def test_unicode(self): class Test__FutureDict(unittest.TestCase): - def _makeOne(self, *args, **kw): + def _make_one(self, *args, **kw): from google.cloud.storage.batch import _FutureDict return _FutureDict(*args, **kw) def test_get(self): - future = self._makeOne() + future = self._make_one() self.assertRaises(KeyError, future.get, None) def test___getitem__(self): - future = self._makeOne() + future = self._make_one() value = orig_value = object() with self.assertRaises(KeyError): value = future[None] self.assertIs(value, orig_value) def test___setitem__(self): - future = self._makeOne() + future = self._make_one() with self.assertRaises(KeyError): future[None] = None diff --git a/storage/unit_tests/test_blob.py b/storage/unit_tests/test_blob.py index 0658e8677c37..281584170896 100644 --- a/storage/unit_tests/test_blob.py +++ b/storage/unit_tests/test_blob.py @@ -17,7 +17,7 @@ class Test_Blob(unittest.TestCase): - def _makeOne(self, *args, **kw): + def _make_one(self, *args, **kw): from google.cloud.storage.blob import Blob properties = kw.pop('properties', None) blob = Blob(*args, **kw) @@ -28,7 +28,7 @@ def test_ctor_wo_encryption_key(self): BLOB_NAME = 'blob-name' bucket = _Bucket() properties = {'key': 'value'} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertIs(blob.bucket, bucket) self.assertEqual(blob.name, BLOB_NAME) self.assertEqual(blob._properties, properties) @@ -40,7 +40,7 @@ def test_ctor_w_encryption_key(self): KEY = b'01234567890123456789012345678901' # 32 bytes BLOB_NAME = 'blob-name' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket, encryption_key=KEY) + blob = self._make_one(BLOB_NAME, bucket=bucket, encryption_key=KEY) self.assertEqual(blob._encryption_key, KEY) def test_chunk_size_ctor(self): @@ -48,13 +48,13 @@ def test_chunk_size_ctor(self): BLOB_NAME = 'blob-name' BUCKET = object() chunk_size = 10 * Blob._CHUNK_SIZE_MULTIPLE - blob = self._makeOne(BLOB_NAME, bucket=BUCKET, chunk_size=chunk_size) + blob = self._make_one(BLOB_NAME, bucket=BUCKET, chunk_size=chunk_size) self.assertEqual(blob._chunk_size, chunk_size) def test_chunk_size_getter(self): BLOB_NAME = 'blob-name' BUCKET = object() - blob = self._makeOne(BLOB_NAME, bucket=BUCKET) + blob = self._make_one(BLOB_NAME, bucket=BUCKET) self.assertIsNone(blob.chunk_size) VALUE = object() blob._chunk_size = VALUE @@ -63,7 +63,7 @@ def test_chunk_size_getter(self): def test_chunk_size_setter(self): BLOB_NAME = 'blob-name' BUCKET = object() - blob = self._makeOne(BLOB_NAME, bucket=BUCKET) + blob = self._make_one(BLOB_NAME, bucket=BUCKET) self.assertIsNone(blob._chunk_size) blob._CHUNK_SIZE_MULTIPLE = 10 blob.chunk_size = 20 @@ -72,7 +72,7 @@ def test_chunk_size_setter(self): def test_chunk_size_setter_bad_value(self): BLOB_NAME = 'blob-name' BUCKET = object() - blob = self._makeOne(BLOB_NAME, bucket=BUCKET) + blob = self._make_one(BLOB_NAME, bucket=BUCKET) self.assertIsNone(blob._chunk_size) blob._CHUNK_SIZE_MULTIPLE = 10 with self.assertRaises(ValueError): @@ -81,7 +81,7 @@ def test_chunk_size_setter_bad_value(self): def test_acl_property(self): from google.cloud.storage.acl import ObjectACL FAKE_BUCKET = _Bucket() - blob = self._makeOne(None, bucket=FAKE_BUCKET) + blob = self._make_one(None, bucket=FAKE_BUCKET) acl = blob.acl self.assertIsInstance(acl, ObjectACL) self.assertIs(acl, blob._acl) @@ -89,30 +89,30 @@ def test_acl_property(self): def test_path_no_bucket(self): FAKE_BUCKET = object() NAME = 'blob-name' - blob = self._makeOne(NAME, bucket=FAKE_BUCKET) + blob = self._make_one(NAME, bucket=FAKE_BUCKET) self.assertRaises(AttributeError, getattr, blob, 'path') def test_path_no_name(self): bucket = _Bucket() - blob = self._makeOne(None, bucket=bucket) + blob = self._make_one(None, bucket=bucket) self.assertRaises(ValueError, getattr, blob, 'path') def test_path_normal(self): BLOB_NAME = 'blob-name' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertEqual(blob.path, '/b/name/o/%s' % BLOB_NAME) def test_path_w_slash_in_name(self): BLOB_NAME = 'parent/child' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertEqual(blob.path, '/b/name/o/parent%2Fchild') def test_public_url(self): BLOB_NAME = 'blob-name' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertEqual(blob.public_url, 'https://storage.googleapis.com/name/%s' % BLOB_NAME) @@ -120,7 +120,7 @@ def test_public_url(self): def test_public_url_w_slash_in_name(self): BLOB_NAME = 'parent/child' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertEqual( blob.public_url, 'https://storage.googleapis.com/name/parent%2Fchild') @@ -134,7 +134,7 @@ def _basic_generate_signed_url_helper(self, credentials=None): connection = _Connection() client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) URI = ('http://example.com/abucket/a-blob-name?Signature=DEADBEEF' '&Expiration=2014-10-16T20:34:37.000Z') @@ -173,7 +173,7 @@ def test_generate_signed_url_w_content_type(self): connection = _Connection() client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) URI = ('http://example.com/abucket/a-blob-name?Signature=DEADBEEF' '&Expiration=2014-10-16T20:34:37.000Z') @@ -211,7 +211,7 @@ def test_generate_signed_url_w_slash_in_name(self): connection = _Connection() client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) URI = ('http://example.com/abucket/a-blob-name?Signature=DEADBEEF' '&Expiration=2014-10-16T20:34:37.000Z') @@ -242,7 +242,7 @@ def test_generate_signed_url_w_method_arg(self): connection = _Connection() client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) URI = ('http://example.com/abucket/a-blob-name?Signature=DEADBEEF' '&Expiration=2014-10-16T20:34:37.000Z') @@ -272,7 +272,7 @@ def test_exists_miss(self): connection = _Connection(not_found_response) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(NONESUCH, bucket=bucket) + blob = self._make_one(NONESUCH, bucket=bucket) self.assertFalse(blob.exists()) def test_exists_hit(self): @@ -282,7 +282,7 @@ def test_exists_hit(self): connection = _Connection(found_response) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) bucket._blobs[BLOB_NAME] = 1 self.assertTrue(blob.exists()) @@ -293,7 +293,7 @@ def test_delete(self): connection = _Connection(not_found_response) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) bucket._blobs[BLOB_NAME] = 1 blob.delete() self.assertFalse(blob.exists()) @@ -319,7 +319,7 @@ def test_download_to_file_wo_media_link(self): connection._responses = [(reload_response, {"mediaLink": MEDIA_LINK})] client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) fh = BytesIO() blob.download_to_file(fh) self.assertEqual(fh.getvalue(), b'abcdef') @@ -342,7 +342,7 @@ def _download_to_file_helper(self, chunk_size=None): bucket = _Bucket(client) MEDIA_LINK = 'http://example.com/media/' properties = {'mediaLink': MEDIA_LINK} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) if chunk_size is not None: blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = chunk_size @@ -377,7 +377,7 @@ def test_download_to_filename(self): MEDIA_LINK = 'http://example.com/media/' properties = {'mediaLink': MEDIA_LINK, 'updated': '2014-12-06T13:13:50.690Z'} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 3 @@ -415,8 +415,8 @@ def test_download_to_filename_w_key(self): MEDIA_LINK = 'http://example.com/media/' properties = {'mediaLink': MEDIA_LINK, 'updated': '2014-12-06T13:13:50.690Z'} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties, - encryption_key=KEY) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties, + encryption_key=KEY) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 3 @@ -453,7 +453,7 @@ def test_download_as_string(self): bucket = _Bucket(client) MEDIA_LINK = 'http://example.com/media/' properties = {'mediaLink': MEDIA_LINK} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 3 fetched = blob.download_as_string() @@ -464,7 +464,7 @@ def test_upload_from_file_size_failure(self): connection = _Connection() client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) file_obj = object() with self.assertRaises(ValueError): blob.upload_from_file(file_obj, size=None) @@ -489,7 +489,7 @@ def _upload_from_file_simple_test_helper(self, properties=None, ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = chunk_size @@ -537,7 +537,7 @@ def test_upload_from_file_stream(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -670,7 +670,7 @@ def test_upload_from_file_resumable(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -747,7 +747,7 @@ def test_upload_from_file_resumable_w_error(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -805,7 +805,7 @@ def test_upload_from_file_w_slash_in_name(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -860,8 +860,8 @@ def test_upload_from_filename_w_key(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket, - properties=properties, encryption_key=KEY) + blob = self._make_one(BLOB_NAME, bucket=bucket, + properties=properties, encryption_key=KEY) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -913,8 +913,8 @@ def _upload_from_filename_test_helper(self, properties=None, ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket, - properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, + properties=properties) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 @@ -982,7 +982,7 @@ def test_upload_from_string_w_bytes(self): ) client = _Client(connection) bucket = _Bucket(client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 blob.upload_from_string(DATA) @@ -1022,7 +1022,7 @@ def test_upload_from_string_w_text(self): ) client = _Client(connection) bucket = _Bucket(client=client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 blob.upload_from_string(DATA) @@ -1065,7 +1065,7 @@ def test_upload_from_string_text_w_key(self): ) client = _Client(connection) bucket = _Bucket(client=client) - blob = self._makeOne(BLOB_NAME, bucket=bucket, encryption_key=KEY) + blob = self._make_one(BLOB_NAME, bucket=bucket, encryption_key=KEY) blob._CHUNK_SIZE_MULTIPLE = 1 blob.chunk_size = 5 blob.upload_from_string(DATA) @@ -1099,7 +1099,7 @@ def test_make_public(self): connection = _Connection(after) client = _Client(connection) bucket = _Bucket(client=client) - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) blob.acl.loaded = True blob.make_public() self.assertEqual(list(blob.acl), permissive) @@ -1117,9 +1117,9 @@ def test_compose_wo_content_type_set(self): connection = _Connection() client = _Client(connection) bucket = _Bucket(client=client) - source_1 = self._makeOne(SOURCE_1, bucket=bucket) - source_2 = self._makeOne(SOURCE_2, bucket=bucket) - destination = self._makeOne(DESTINATION, bucket=bucket) + source_1 = self._make_one(SOURCE_1, bucket=bucket) + source_2 = self._make_one(SOURCE_2, bucket=bucket) + destination = self._make_one(DESTINATION, bucket=bucket) with self.assertRaises(ValueError): destination.compose(sources=[source_1, source_2]) @@ -1136,9 +1136,9 @@ def test_compose_minimal(self): connection = _Connection(after) client = _Client(connection) bucket = _Bucket(client=client) - source_1 = self._makeOne(SOURCE_1, bucket=bucket) - source_2 = self._makeOne(SOURCE_2, bucket=bucket) - destination = self._makeOne(DESTINATION, bucket=bucket) + source_1 = self._make_one(SOURCE_1, bucket=bucket) + source_2 = self._make_one(SOURCE_2, bucket=bucket) + destination = self._make_one(DESTINATION, bucket=bucket) destination.content_type = 'text/plain' destination.compose(sources=[source_1, source_2]) @@ -1172,9 +1172,9 @@ def test_compose_w_additional_property_changes(self): connection = _Connection(after) client = _Client(connection) bucket = _Bucket(client=client) - source_1 = self._makeOne(SOURCE_1, bucket=bucket) - source_2 = self._makeOne(SOURCE_2, bucket=bucket) - destination = self._makeOne(DESTINATION, bucket=bucket) + source_1 = self._make_one(SOURCE_1, bucket=bucket) + source_2 = self._make_one(SOURCE_2, bucket=bucket) + destination = self._make_one(DESTINATION, bucket=bucket) destination.content_type = 'text/plain' destination.content_language = 'en-US' destination.metadata = {'my-key': 'my-value'} @@ -1219,9 +1219,9 @@ def test_rewrite_other_bucket_other_name_no_encryption_partial(self): connection = _Connection(response) client = _Client(connection) source_bucket = _Bucket(client=client) - source_blob = self._makeOne(SOURCE_BLOB, bucket=source_bucket) + source_blob = self._make_one(SOURCE_BLOB, bucket=source_bucket) dest_bucket = _Bucket(client=client, name=DEST_BUCKET) - dest_blob = self._makeOne(DEST_BLOB, bucket=dest_bucket) + dest_blob = self._make_one(DEST_BLOB, bucket=dest_bucket) token, rewritten, size = dest_blob.rewrite(source_blob) @@ -1267,8 +1267,9 @@ def test_rewrite_same_name_no_old_key_new_key_done(self): connection = _Connection(response) client = _Client(connection) bucket = _Bucket(client=client) - plain = self._makeOne(BLOB_NAME, bucket=bucket) - encrypted = self._makeOne(BLOB_NAME, bucket=bucket, encryption_key=KEY) + plain = self._make_one(BLOB_NAME, bucket=bucket) + encrypted = self._make_one(BLOB_NAME, bucket=bucket, + encryption_key=KEY) token, rewritten, size = encrypted.rewrite(plain) @@ -1320,9 +1321,10 @@ def test_rewrite_same_name_no_key_new_key_w_token(self): connection = _Connection(response) client = _Client(connection) bucket = _Bucket(client=client) - source = self._makeOne( + source = self._make_one( BLOB_NAME, bucket=bucket, encryption_key=SOURCE_KEY) - dest = self._makeOne(BLOB_NAME, bucket=bucket, encryption_key=DEST_KEY) + dest = self._make_one(BLOB_NAME, bucket=bucket, + encryption_key=DEST_KEY) token, rewritten, size = dest.rewrite(source, token=TOKEN) @@ -1360,14 +1362,14 @@ def test_cache_control_getter(self): bucket = _Bucket() CACHE_CONTROL = 'no-cache' properties = {'cacheControl': CACHE_CONTROL} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.cache_control, CACHE_CONTROL) def test_cache_control_setter(self): BLOB_NAME = 'blob-name' CACHE_CONTROL = 'no-cache' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.cache_control) blob.cache_control = CACHE_CONTROL self.assertEqual(blob.cache_control, CACHE_CONTROL) @@ -1375,19 +1377,19 @@ def test_cache_control_setter(self): def test_component_count(self): BUCKET = object() COMPONENT_COUNT = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'componentCount': COMPONENT_COUNT}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'componentCount': COMPONENT_COUNT}) self.assertEqual(blob.component_count, COMPONENT_COUNT) def test_component_count_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.component_count) def test_component_count_string_val(self): BUCKET = object() COMPONENT_COUNT = 42 - blob = self._makeOne( + blob = self._make_one( 'blob-name', bucket=BUCKET, properties={'componentCount': str(COMPONENT_COUNT)}) self.assertEqual(blob.component_count, COMPONENT_COUNT) @@ -1397,14 +1399,14 @@ def test_content_disposition_getter(self): bucket = _Bucket() CONTENT_DISPOSITION = 'Attachment; filename=example.jpg' properties = {'contentDisposition': CONTENT_DISPOSITION} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.content_disposition, CONTENT_DISPOSITION) def test_content_disposition_setter(self): BLOB_NAME = 'blob-name' CONTENT_DISPOSITION = 'Attachment; filename=example.jpg' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.content_disposition) blob.content_disposition = CONTENT_DISPOSITION self.assertEqual(blob.content_disposition, CONTENT_DISPOSITION) @@ -1414,14 +1416,14 @@ def test_content_encoding_getter(self): bucket = _Bucket() CONTENT_ENCODING = 'gzip' properties = {'contentEncoding': CONTENT_ENCODING} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.content_encoding, CONTENT_ENCODING) def test_content_encoding_setter(self): BLOB_NAME = 'blob-name' CONTENT_ENCODING = 'gzip' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.content_encoding) blob.content_encoding = CONTENT_ENCODING self.assertEqual(blob.content_encoding, CONTENT_ENCODING) @@ -1431,14 +1433,14 @@ def test_content_language_getter(self): bucket = _Bucket() CONTENT_LANGUAGE = 'pt-BR' properties = {'contentLanguage': CONTENT_LANGUAGE} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.content_language, CONTENT_LANGUAGE) def test_content_language_setter(self): BLOB_NAME = 'blob-name' CONTENT_LANGUAGE = 'pt-BR' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.content_language) blob.content_language = CONTENT_LANGUAGE self.assertEqual(blob.content_language, CONTENT_LANGUAGE) @@ -1448,14 +1450,14 @@ def test_content_type_getter(self): bucket = _Bucket() CONTENT_TYPE = 'image/jpeg' properties = {'contentType': CONTENT_TYPE} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.content_type, CONTENT_TYPE) def test_content_type_setter(self): BLOB_NAME = 'blob-name' CONTENT_TYPE = 'image/jpeg' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.content_type) blob.content_type = CONTENT_TYPE self.assertEqual(blob.content_type, CONTENT_TYPE) @@ -1465,14 +1467,14 @@ def test_crc32c_getter(self): bucket = _Bucket() CRC32C = 'DEADBEEF' properties = {'crc32c': CRC32C} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.crc32c, CRC32C) def test_crc32c_setter(self): BLOB_NAME = 'blob-name' CRC32C = 'DEADBEEF' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.crc32c) blob.crc32c = CRC32C self.assertEqual(blob.crc32c, CRC32C) @@ -1482,26 +1484,26 @@ def test_etag(self): bucket = _Bucket() ETAG = 'ETAG' properties = {'etag': ETAG} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.etag, ETAG) def test_generation(self): BUCKET = object() GENERATION = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'generation': GENERATION}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'generation': GENERATION}) self.assertEqual(blob.generation, GENERATION) def test_generation_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.generation) def test_generation_string_val(self): BUCKET = object() GENERATION = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'generation': str(GENERATION)}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'generation': str(GENERATION)}) self.assertEqual(blob.generation, GENERATION) def test_id(self): @@ -1509,7 +1511,7 @@ def test_id(self): bucket = _Bucket() ID = 'ID' properties = {'id': ID} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.id, ID) def test_md5_hash_getter(self): @@ -1517,14 +1519,14 @@ def test_md5_hash_getter(self): bucket = _Bucket() MD5_HASH = 'DEADBEEF' properties = {'md5Hash': MD5_HASH} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.md5_hash, MD5_HASH) def test_md5_hash_setter(self): BLOB_NAME = 'blob-name' MD5_HASH = 'DEADBEEF' bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.md5_hash) blob.md5_hash = MD5_HASH self.assertEqual(blob.md5_hash, MD5_HASH) @@ -1534,7 +1536,7 @@ def test_media_link(self): bucket = _Bucket() MEDIA_LINK = 'http://example.com/media/' properties = {'mediaLink': MEDIA_LINK} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.media_link, MEDIA_LINK) def test_metadata_getter(self): @@ -1542,14 +1544,14 @@ def test_metadata_getter(self): bucket = _Bucket() METADATA = {'foo': 'Foo'} properties = {'metadata': METADATA} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.metadata, METADATA) def test_metadata_setter(self): BLOB_NAME = 'blob-name' METADATA = {'foo': 'Foo'} bucket = _Bucket() - blob = self._makeOne(BLOB_NAME, bucket=bucket) + blob = self._make_one(BLOB_NAME, bucket=bucket) self.assertIsNone(blob.metadata) blob.metadata = METADATA self.assertEqual(blob.metadata, METADATA) @@ -1557,19 +1559,19 @@ def test_metadata_setter(self): def test_metageneration(self): BUCKET = object() METAGENERATION = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'metageneration': METAGENERATION}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'metageneration': METAGENERATION}) self.assertEqual(blob.metageneration, METAGENERATION) def test_metageneration_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.metageneration) def test_metageneration_string_val(self): BUCKET = object() METAGENERATION = 42 - blob = self._makeOne( + blob = self._make_one( 'blob-name', bucket=BUCKET, properties={'metageneration': str(METAGENERATION)}) self.assertEqual(blob.metageneration, METAGENERATION) @@ -1579,7 +1581,7 @@ def test_owner(self): bucket = _Bucket() OWNER = {'entity': 'project-owner-12345', 'entityId': '23456'} properties = {'owner': OWNER} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) owner = blob.owner self.assertEqual(owner['entity'], 'project-owner-12345') self.assertEqual(owner['entityId'], '23456') @@ -1589,26 +1591,26 @@ def test_self_link(self): bucket = _Bucket() SELF_LINK = 'http://example.com/self/' properties = {'selfLink': SELF_LINK} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.self_link, SELF_LINK) def test_size(self): BUCKET = object() SIZE = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'size': SIZE}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'size': SIZE}) self.assertEqual(blob.size, SIZE) def test_size_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.size) def test_size_string_val(self): BUCKET = object() SIZE = 42 - blob = self._makeOne('blob-name', bucket=BUCKET, - properties={'size': str(SIZE)}) + blob = self._make_one('blob-name', bucket=BUCKET, + properties={'size': str(SIZE)}) self.assertEqual(blob.size, SIZE) def test_storage_class(self): @@ -1616,7 +1618,7 @@ def test_storage_class(self): bucket = _Bucket() STORAGE_CLASS = 'http://example.com/self/' properties = {'storageClass': STORAGE_CLASS} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.storage_class, STORAGE_CLASS) def test_time_deleted(self): @@ -1628,12 +1630,12 @@ def test_time_deleted(self): TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC) TIME_DELETED = TIMESTAMP.strftime(_RFC3339_MICROS) properties = {'timeDeleted': TIME_DELETED} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.time_deleted, TIMESTAMP) def test_time_deleted_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.time_deleted) def test_updated(self): @@ -1645,12 +1647,12 @@ def test_updated(self): TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC) UPDATED = TIMESTAMP.strftime(_RFC3339_MICROS) properties = {'updated': UPDATED} - blob = self._makeOne(BLOB_NAME, bucket=bucket, properties=properties) + blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties) self.assertEqual(blob.updated, TIMESTAMP) def test_updated_unset(self): BUCKET = object() - blob = self._makeOne('blob-name', bucket=BUCKET) + blob = self._make_one('blob-name', bucket=BUCKET) self.assertIsNone(blob.updated) diff --git a/storage/unit_tests/test_bucket.py b/storage/unit_tests/test_bucket.py index 53a79884f0b6..2ca921d850ec 100644 --- a/storage/unit_tests/test_bucket.py +++ b/storage/unit_tests/test_bucket.py @@ -17,7 +17,7 @@ class Test_Bucket(unittest.TestCase): - def _makeOne(self, client=None, name=None, properties=None): + def _make_one(self, client=None, name=None, properties=None): from google.cloud.storage.bucket import Bucket if client is None: connection = _Connection() @@ -29,7 +29,7 @@ def _makeOne(self, client=None, name=None, properties=None): def test_ctor(self): NAME = 'name' properties = {'key': 'value'} - bucket = self._makeOne(name=NAME, properties=properties) + bucket = self._make_one(name=NAME, properties=properties) self.assertEqual(bucket.name, NAME) self.assertEqual(bucket._properties, properties) self.assertFalse(bucket._acl.loaded) @@ -45,7 +45,7 @@ def test_blob(self): CHUNK_SIZE = 1024 * 1024 KEY = b'01234567890123456789012345678901' # 32 bytes - bucket = self._makeOne(name=BUCKET_NAME) + bucket = self._make_one(name=BUCKET_NAME) blob = bucket.blob( BLOB_NAME, chunk_size=CHUNK_SIZE, encryption_key=KEY) self.assertIsInstance(blob, Blob) @@ -68,7 +68,7 @@ def api_request(cls, *args, **kwargs): raise NotFound(args) BUCKET_NAME = 'bucket-name' - bucket = self._makeOne(name=BUCKET_NAME) + bucket = self._make_one(name=BUCKET_NAME) client = _Client(_FakeConnection) self.assertFalse(bucket.exists(client=client)) expected_called_kwargs = { @@ -94,7 +94,7 @@ def api_request(cls, *args, **kwargs): return object() BUCKET_NAME = 'bucket-name' - bucket = self._makeOne(name=BUCKET_NAME) + bucket = self._make_one(name=BUCKET_NAME) client = _Client(_FakeConnection) self.assertTrue(bucket.exists(client=client)) expected_called_kwargs = { @@ -114,7 +114,7 @@ def test_create_hit(self): connection = _Connection(DATA) PROJECT = 'PROJECT' client = _Client(connection, project=PROJECT) - bucket = self._makeOne(client=client, name=BUCKET_NAME) + bucket = self._make_one(client=client, name=BUCKET_NAME) bucket.create() kw, = connection._requested @@ -148,7 +148,7 @@ def test_create_w_extra_properties(self): } connection = _Connection(DATA) client = _Client(connection, project=PROJECT) - bucket = self._makeOne(client=client, name=BUCKET_NAME) + bucket = self._make_one(client=client, name=BUCKET_NAME) bucket.cors = CORS bucket.lifecycle_rules = LIFECYCLE_RULES bucket.location = LOCATION @@ -164,25 +164,25 @@ def test_create_w_extra_properties(self): def test_acl_property(self): from google.cloud.storage.acl import BucketACL - bucket = self._makeOne() + bucket = self._make_one() acl = bucket.acl self.assertIsInstance(acl, BucketACL) self.assertIs(acl, bucket._acl) def test_default_object_acl_property(self): from google.cloud.storage.acl import DefaultObjectACL - bucket = self._makeOne() + bucket = self._make_one() acl = bucket.default_object_acl self.assertIsInstance(acl, DefaultObjectACL) self.assertIs(acl, bucket._default_object_acl) def test_path_no_name(self): - bucket = self._makeOne() + bucket = self._make_one() self.assertRaises(ValueError, getattr, bucket, 'path') def test_path_w_name(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertEqual(bucket.path, '/b/%s' % NAME) def test_get_blob_miss(self): @@ -190,7 +190,7 @@ def test_get_blob_miss(self): NONESUCH = 'nonesuch' connection = _Connection() client = _Client(connection) - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) result = bucket.get_blob(NONESUCH, client=client) self.assertIsNone(result) kw, = connection._requested @@ -202,7 +202,7 @@ def test_get_blob_hit(self): BLOB_NAME = 'blob-name' connection = _Connection({'name': BLOB_NAME}) client = _Client(connection) - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) blob = bucket.get_blob(BLOB_NAME, client=client) self.assertIs(blob.bucket, bucket) self.assertEqual(blob.name, BLOB_NAME) @@ -214,7 +214,7 @@ def test_list_blobs_defaults(self): NAME = 'name' connection = _Connection({'items': []}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) iterator = bucket.list_blobs() blobs = list(iterator) self.assertEqual(blobs, []) @@ -243,7 +243,7 @@ def test_list_blobs_w_all_arguments(self): } connection = _Connection({'items': []}) client = _Client(connection) - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) iterator = bucket.list_blobs( max_results=MAX_RESULTS, page_token=PAGE_TOKEN, @@ -265,7 +265,7 @@ def test_list_blobs(self): NAME = 'name' connection = _Connection({'items': []}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) iterator = bucket.list_blobs() blobs = list(iterator) self.assertEqual(blobs, []) @@ -279,7 +279,7 @@ def test_delete_miss(self): NAME = 'name' connection = _Connection() client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) self.assertRaises(NotFound, bucket.delete) expected_cw = [{ 'method': 'DELETE', @@ -294,7 +294,7 @@ def test_delete_hit(self): connection = _Connection(GET_BLOBS_RESP) connection._delete_bucket = True client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) result = bucket.delete(force=True) self.assertIsNone(result) expected_cw = [{ @@ -319,7 +319,7 @@ def test_delete_force_delete_blobs(self): DELETE_BLOB2_RESP) connection._delete_bucket = True client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) result = bucket.delete(force=True) self.assertIsNone(result) expected_cw = [{ @@ -337,7 +337,7 @@ def test_delete_force_miss_blobs(self): connection = _Connection(GET_BLOBS_RESP) connection._delete_bucket = True client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) result = bucket.delete(force=True) self.assertIsNone(result) expected_cw = [{ @@ -360,7 +360,7 @@ def test_delete_too_many(self): connection = _Connection(GET_BLOBS_RESP) connection._delete_bucket = True client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) # Make the Bucket refuse to delete with 2 objects. bucket._MAX_OBJECTS_FOR_ITERATION = 1 @@ -373,7 +373,7 @@ def test_delete_blob_miss(self): NONESUCH = 'nonesuch' connection = _Connection() client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) self.assertRaises(NotFound, bucket.delete_blob, NONESUCH) kw, = connection._requested self.assertEqual(kw['method'], 'DELETE') @@ -384,7 +384,7 @@ def test_delete_blob_hit(self): BLOB_NAME = 'blob-name' connection = _Connection({}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) result = bucket.delete_blob(BLOB_NAME) self.assertIsNone(result) kw, = connection._requested @@ -395,7 +395,7 @@ def test_delete_blobs_empty(self): NAME = 'name' connection = _Connection() client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.delete_blobs([]) self.assertEqual(connection._requested, []) @@ -404,7 +404,7 @@ def test_delete_blobs_hit(self): BLOB_NAME = 'blob-name' connection = _Connection({}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.delete_blobs([BLOB_NAME]) kw = connection._requested self.assertEqual(len(kw), 1) @@ -418,7 +418,7 @@ def test_delete_blobs_miss_no_on_error(self): NONESUCH = 'nonesuch' connection = _Connection({}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) self.assertRaises(NotFound, bucket.delete_blobs, [BLOB_NAME, NONESUCH]) kw = connection._requested self.assertEqual(len(kw), 2) @@ -433,7 +433,7 @@ def test_delete_blobs_miss_w_on_error(self): NONESUCH = 'nonesuch' connection = _Connection({}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) errors = [] bucket.delete_blobs([BLOB_NAME, NONESUCH], errors.append) self.assertEqual(errors, [NONESUCH]) @@ -455,8 +455,8 @@ class _Blob(object): connection = _Connection({}) client = _Client(connection) - source = self._makeOne(client=client, name=SOURCE) - dest = self._makeOne(client=client, name=DEST) + source = self._make_one(client=client, name=SOURCE) + dest = self._make_one(client=client, name=DEST) blob = _Blob() new_blob = source.copy_blob(blob, dest) self.assertIs(new_blob.bucket, dest) @@ -484,8 +484,8 @@ class _Blob(object): connection = _Connection({}, {}) client = _Client(connection) - source = self._makeOne(client=client, name=SOURCE) - dest = self._makeOne(client=client, name=DEST) + source = self._make_one(client=client, name=SOURCE) + dest = self._make_one(client=client, name=DEST) blob = _Blob() new_blob = source.copy_blob(blob, dest, NEW_NAME, client=client, preserve_acl=False) @@ -511,8 +511,8 @@ class _Blob(object): connection = _Connection({}) client = _Client(connection) - source = self._makeOne(client=client, name=SOURCE) - dest = self._makeOne(client=client, name=DEST) + source = self._make_one(client=client, name=SOURCE) + dest = self._make_one(client=client, name=DEST) blob = _Blob() new_blob = source.copy_blob(blob, dest, NEW_NAME) self.assertIs(new_blob.bucket, dest) @@ -531,7 +531,7 @@ def test_rename_blob(self): DATA = {'name': NEW_BLOB_NAME} connection = _Connection(DATA) client = _Client(connection) - bucket = self._makeOne(client=client, name=BUCKET_NAME) + bucket = self._make_one(client=client, name=BUCKET_NAME) class _Blob(object): @@ -552,24 +552,24 @@ def delete(self, client=None): def test_etag(self): ETAG = 'ETAG' properties = {'etag': ETAG} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.etag, ETAG) def test_id(self): ID = 'ID' properties = {'id': ID} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.id, ID) def test_location_getter(self): NAME = 'name' before = {'location': 'AS'} - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) self.assertEqual(bucket.location, 'AS') def test_location_setter(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertIsNone(bucket.location) bucket.location = 'AS' self.assertEqual(bucket.location, 'AS') @@ -580,7 +580,7 @@ def test_lifecycle_rules_getter(self): LC_RULE = {'action': {'type': 'Delete'}, 'condition': {'age': 42}} rules = [LC_RULE] properties = {'lifecycle': {'rule': rules}} - bucket = self._makeOne(name=NAME, properties=properties) + bucket = self._make_one(name=NAME, properties=properties) self.assertEqual(bucket.lifecycle_rules, rules) # Make sure it's a copy self.assertIsNot(bucket.lifecycle_rules, rules) @@ -589,7 +589,7 @@ def test_lifecycle_rules_setter(self): NAME = 'name' LC_RULE = {'action': {'type': 'Delete'}, 'condition': {'age': 42}} rules = [LC_RULE] - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertEqual(bucket.lifecycle_rules, []) bucket.lifecycle_rules = rules self.assertEqual(bucket.lifecycle_rules, rules) @@ -604,7 +604,7 @@ def test_cors_getter(self): 'responseHeader': ['Content-Type'], } properties = {'cors': [CORS_ENTRY, {}]} - bucket = self._makeOne(name=NAME, properties=properties) + bucket = self._make_one(name=NAME, properties=properties) entries = bucket.cors self.assertEqual(len(entries), 2) self.assertEqual(entries[0], CORS_ENTRY) @@ -620,7 +620,7 @@ def test_cors_setter(self): 'origin': ['127.0.0.1'], 'responseHeader': ['Content-Type'], } - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertEqual(bucket.cors, []) bucket.cors = [CORS_ENTRY] @@ -637,7 +637,7 @@ def test_get_logging_w_prefix(self): 'logObjectPrefix': LOG_PREFIX, }, } - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) info = bucket.get_logging() self.assertEqual(info['logBucket'], LOG_BUCKET) self.assertEqual(info['logObjectPrefix'], LOG_PREFIX) @@ -646,7 +646,7 @@ def test_enable_logging_defaults(self): NAME = 'name' LOG_BUCKET = 'logs' before = {'logging': None} - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) self.assertIsNone(bucket.get_logging()) bucket.enable_logging(LOG_BUCKET) info = bucket.get_logging() @@ -658,7 +658,7 @@ def test_enable_logging(self): LOG_BUCKET = 'logs' LOG_PFX = 'pfx' before = {'logging': None} - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) self.assertIsNone(bucket.get_logging()) bucket.enable_logging(LOG_BUCKET, LOG_PFX) info = bucket.get_logging() @@ -668,7 +668,7 @@ def test_enable_logging(self): def test_disable_logging(self): NAME = 'name' before = {'logging': {'logBucket': 'logs', 'logObjectPrefix': 'pfx'}} - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) self.assertIsNotNone(bucket.get_logging()) bucket.disable_logging() self.assertIsNone(bucket.get_logging()) @@ -676,23 +676,23 @@ def test_disable_logging(self): def test_metageneration(self): METAGENERATION = 42 properties = {'metageneration': METAGENERATION} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.metageneration, METAGENERATION) def test_metageneration_unset(self): - bucket = self._makeOne() + bucket = self._make_one() self.assertIsNone(bucket.metageneration) def test_metageneration_string_val(self): METAGENERATION = 42 properties = {'metageneration': str(METAGENERATION)} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.metageneration, METAGENERATION) def test_owner(self): OWNER = {'entity': 'project-owner-12345', 'entityId': '23456'} properties = {'owner': OWNER} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) owner = bucket.owner self.assertEqual(owner['entity'], 'project-owner-12345') self.assertEqual(owner['entityId'], '23456') @@ -700,76 +700,76 @@ def test_owner(self): def test_project_number(self): PROJECT_NUMBER = 12345 properties = {'projectNumber': PROJECT_NUMBER} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.project_number, PROJECT_NUMBER) def test_project_number_unset(self): - bucket = self._makeOne() + bucket = self._make_one() self.assertIsNone(bucket.project_number) def test_project_number_string_val(self): PROJECT_NUMBER = 12345 properties = {'projectNumber': str(PROJECT_NUMBER)} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.project_number, PROJECT_NUMBER) def test_self_link(self): SELF_LINK = 'http://example.com/self/' properties = {'selfLink': SELF_LINK} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.self_link, SELF_LINK) def test_storage_class_getter(self): STORAGE_CLASS = 'http://example.com/self/' properties = {'storageClass': STORAGE_CLASS} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.storage_class, STORAGE_CLASS) def test_storage_class_setter_invalid(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) with self.assertRaises(ValueError): bucket.storage_class = 'BOGUS' self.assertFalse('storageClass' in bucket._changes) def test_storage_class_setter_STANDARD(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'STANDARD' self.assertEqual(bucket.storage_class, 'STANDARD') self.assertTrue('storageClass' in bucket._changes) def test_storage_class_setter_NEARLINE(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'NEARLINE' self.assertEqual(bucket.storage_class, 'NEARLINE') self.assertTrue('storageClass' in bucket._changes) def test_storage_class_setter_COLDLINE(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'COLDLINE' self.assertEqual(bucket.storage_class, 'COLDLINE') self.assertTrue('storageClass' in bucket._changes) def test_storage_class_setter_MULTI_REGIONAL(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'MULTI_REGIONAL' self.assertEqual(bucket.storage_class, 'MULTI_REGIONAL') self.assertTrue('storageClass' in bucket._changes) def test_storage_class_setter_REGIONAL(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'REGIONAL' self.assertEqual(bucket.storage_class, 'REGIONAL') self.assertTrue('storageClass' in bucket._changes) def test_storage_class_setter_DURABLE_REDUCED_AVAILABILITY(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.storage_class = 'DURABLE_REDUCED_AVAILABILITY' self.assertEqual(bucket.storage_class, 'DURABLE_REDUCED_AVAILABILITY') self.assertTrue('storageClass' in bucket._changes) @@ -781,27 +781,27 @@ def test_time_created(self): TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC) TIME_CREATED = TIMESTAMP.strftime(_RFC3339_MICROS) properties = {'timeCreated': TIME_CREATED} - bucket = self._makeOne(properties=properties) + bucket = self._make_one(properties=properties) self.assertEqual(bucket.time_created, TIMESTAMP) def test_time_created_unset(self): - bucket = self._makeOne() + bucket = self._make_one() self.assertIsNone(bucket.time_created) def test_versioning_enabled_getter_missing(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertEqual(bucket.versioning_enabled, False) def test_versioning_enabled_getter(self): NAME = 'name' before = {'versioning': {'enabled': True}} - bucket = self._makeOne(name=NAME, properties=before) + bucket = self._make_one(name=NAME, properties=before) self.assertEqual(bucket.versioning_enabled, True) def test_versioning_enabled_setter(self): NAME = 'name' - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) self.assertFalse(bucket.versioning_enabled) bucket.versioning_enabled = True self.assertTrue(bucket.versioning_enabled) @@ -810,7 +810,7 @@ def test_configure_website_defaults(self): NAME = 'name' UNSET = {'website': {'mainPageSuffix': None, 'notFoundPage': None}} - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.configure_website() self.assertEqual(bucket._properties, UNSET) @@ -818,7 +818,7 @@ def test_configure_website(self): NAME = 'name' WEBSITE_VAL = {'website': {'mainPageSuffix': 'html', 'notFoundPage': '404.html'}} - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.configure_website('html', '404.html') self.assertEqual(bucket._properties, WEBSITE_VAL) @@ -826,7 +826,7 @@ def test_disable_website(self): NAME = 'name' UNSET = {'website': {'mainPageSuffix': None, 'notFoundPage': None}} - bucket = self._makeOne(name=NAME) + bucket = self._make_one(name=NAME) bucket.disable_website() self.assertEqual(bucket._properties, UNSET) @@ -837,7 +837,7 @@ def test_make_public_defaults(self): after = {'acl': permissive, 'defaultObjectAcl': []} connection = _Connection(after) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.acl.loaded = True bucket.default_object_acl.loaded = True bucket.make_public() @@ -865,7 +865,7 @@ def _make_public_w_future_helper(self, default_object_acl_loaded=True): # to consume. connection = _Connection(after1, after1, after2) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.acl.loaded = True bucket.default_object_acl.loaded = default_object_acl_loaded bucket.make_public(future=True) @@ -930,7 +930,7 @@ def item_to_blob(self, item): after = {'acl': permissive, 'defaultObjectAcl': []} connection = _Connection(after, {'items': [{'name': BLOB_NAME}]}) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.acl.loaded = True bucket.default_object_acl.loaded = True @@ -968,7 +968,7 @@ def test_make_public_recursive_too_many(self): } connection = _Connection(AFTER, GET_BLOBS_RESP) client = _Client(connection) - bucket = self._makeOne(client=client, name=NAME) + bucket = self._make_one(client=client, name=NAME) bucket.acl.loaded = True bucket.default_object_acl.loaded = True @@ -982,7 +982,7 @@ def test_page_empty_response(self): connection = _Connection() client = _Client(connection) name = 'name' - bucket = self._makeOne(client=client, name=name) + bucket = self._make_one(client=client, name=name) iterator = bucket.list_blobs() page = Page(iterator, (), None) iterator._page = page @@ -999,7 +999,7 @@ def test_page_non_empty_response(self): connection = _Connection() client = _Client(connection) name = 'name' - bucket = self._makeOne(client=client, name=name) + bucket = self._make_one(client=client, name=name) def dummy_response(): return response @@ -1033,7 +1033,7 @@ def test_cumulative_prefixes(self): connection = _Connection() client = _Client(connection) name = 'name' - bucket = self._makeOne(client=client, name=name) + bucket = self._make_one(client=client, name=name) responses = [response1, response2] def dummy_response(): diff --git a/storage/unit_tests/test_client.py b/storage/unit_tests/test_client.py index 6807771e5628..db15395ae103 100644 --- a/storage/unit_tests/test_client.py +++ b/storage/unit_tests/test_client.py @@ -17,12 +17,13 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.storage.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor_connection_type(self): from google.cloud.storage._http import Connection @@ -30,7 +31,7 @@ def test_ctor_connection_type(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) self.assertEqual(client.project, PROJECT) self.assertIsInstance(client.connection, Connection) self.assertIs(client.connection.credentials, CREDENTIALS) @@ -43,7 +44,7 @@ def test__push_batch_and__pop_batch(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) batch1 = Batch(client) batch2 = Batch(client) client._push_batch(batch1) @@ -61,7 +62,7 @@ def test__push_batch_and__pop_batch(self): def test_connection_setter(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) client._connection = None # Unset the value from the constructor client.connection = connection = object() self.assertIs(client._connection, connection) @@ -69,13 +70,13 @@ def test_connection_setter(self): def test_connection_setter_when_set(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) self.assertRaises(ValueError, setattr, client, 'connection', None) def test_connection_getter_no_batch(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) self.assertIs(client.connection, client._connection) self.assertIsNone(client.current_batch) @@ -83,7 +84,7 @@ def test_connection_getter_with_batch(self): from google.cloud.storage.batch import Batch PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) batch = Batch(client) client._push_batch(batch) self.assertIsNot(client.connection, client._connection) @@ -97,7 +98,7 @@ def test_bucket(self): CREDENTIALS = _Credentials() BUCKET_NAME = 'BUCKET_NAME' - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) bucket = client.bucket(BUCKET_NAME) self.assertIsInstance(bucket, Bucket) self.assertIs(bucket.client, client) @@ -109,7 +110,7 @@ def test_batch(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) batch = client.batch() self.assertIsInstance(batch, Batch) self.assertIs(batch._client, client) @@ -119,7 +120,7 @@ def test_get_bucket_miss(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) NONESUCH = 'nonesuch' URI = '/'.join([ @@ -142,7 +143,7 @@ def test_get_bucket_hit(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) BLOB_NAME = 'blob-name' URI = '/'.join([ @@ -166,7 +167,7 @@ def test_get_bucket_hit(self): def test_lookup_bucket_miss(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) NONESUCH = 'nonesuch' URI = '/'.join([ @@ -190,7 +191,7 @@ def test_lookup_bucket_hit(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) BLOB_NAME = 'blob-name' URI = '/'.join([ @@ -216,7 +217,7 @@ def test_create_bucket_conflict(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) BLOB_NAME = 'blob-name' URI = '/'.join([ @@ -239,7 +240,7 @@ def test_create_bucket_success(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) BLOB_NAME = 'blob-name' URI = '/'.join([ @@ -265,7 +266,7 @@ def test_list_buckets_empty(self): PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) EXPECTED_QUERY = { 'project': [PROJECT], @@ -297,7 +298,7 @@ def test_list_buckets_non_empty(self): from six.moves.urllib.parse import urlparse PROJECT = 'PROJECT' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) BUCKET_NAME = 'bucket-name' query_params = urlencode({'project': PROJECT, 'projection': 'noAcl'}) @@ -326,7 +327,7 @@ def test_list_buckets_all_arguments(self): PROJECT = 'foo-bar' CREDENTIALS = _Credentials() - client = self._makeOne(project=PROJECT, credentials=CREDENTIALS) + client = self._make_one(project=PROJECT, credentials=CREDENTIALS) MAX_RESULTS = 10 PAGE_TOKEN = 'ABCD' @@ -374,7 +375,7 @@ def test_page_empty_response(self): project = 'PROJECT' credentials = _Credentials() - client = self._makeOne(project=project, credentials=credentials) + client = self._make_one(project=project, credentials=credentials) iterator = client.list_buckets() page = Page(iterator, (), None) iterator._page = page @@ -386,7 +387,7 @@ def test_page_non_empty_response(self): project = 'PROJECT' credentials = _Credentials() - client = self._makeOne(project=project, credentials=credentials) + client = self._make_one(project=project, credentials=credentials) blob_name = 'blob-name' response = {'items': [{'name': blob_name}]} diff --git a/translate/unit_tests/test_client.py b/translate/unit_tests/test_client.py index fe1481c42a4f..f28f2b0c16d6 100644 --- a/translate/unit_tests/test_client.py +++ b/translate/unit_tests/test_client.py @@ -19,19 +19,20 @@ class TestClient(unittest.TestCase): KEY = 'abc-123-my-key' - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.translate.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): from google.cloud.translate.connection import Connection from google.cloud.translate.client import ENGLISH_ISO_639 http = object() - client = self._makeOne(self.KEY, http=http) + client = self._make_one(self.KEY, http=http) self.assertIsInstance(client.connection, Connection) self.assertIsNone(client.connection.credentials) self.assertIs(client.connection.http, http) @@ -42,7 +43,7 @@ def test_ctor_non_default(self): http = object() target = 'es' - client = self._makeOne(self.KEY, http=http, target_language=target) + client = self._make_one(self.KEY, http=http, target_language=target) self.assertIsInstance(client.connection, Connection) self.assertIsNone(client.connection.credentials) self.assertIs(client.connection.http, http) @@ -51,7 +52,7 @@ def test_ctor_non_default(self): def test_get_languages(self): from google.cloud.translate.client import ENGLISH_ISO_639 - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) supported = [ {'language': 'en', 'name': 'English'}, {'language': 'af', 'name': 'Afrikaans'}, @@ -76,7 +77,7 @@ def test_get_languages(self): {'key': self.KEY, 'target': ENGLISH_ISO_639}) def test_get_languages_no_target(self): - client = self._makeOne(self.KEY, target_language=None) + client = self._make_one(self.KEY, target_language=None) supported = [ {'language': 'en'}, {'language': 'af'}, @@ -100,7 +101,7 @@ def test_get_languages_no_target(self): self.assertEqual(req['query_params'], {'key': self.KEY}) def test_get_languages_explicit_target(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) target_language = 'en' supported = [ {'language': 'en', 'name': 'Spanish'}, @@ -126,7 +127,7 @@ def test_get_languages_explicit_target(self): {'key': self.KEY, 'target': target_language}) def test_detect_language_bad_result(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'takoy' conn = client.connection = _Connection({}) @@ -145,7 +146,7 @@ def test_detect_language_bad_result(self): self.assertEqual(req['query_params'], query_params) def test_detect_language_single_value(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'takoy' detection = { 'confidence': 1.0, @@ -175,7 +176,7 @@ def test_detect_language_single_value(self): self.assertEqual(req['query_params'], query_params) def test_detect_language_multiple_values(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value1 = u'fa\xe7ade' # facade (with a cedilla) detection1 = { 'confidence': 0.6166008, @@ -216,7 +217,7 @@ def test_detect_language_multiple_values(self): self.assertEqual(req['query_params'], query_params) def test_detect_language_multiple_results(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'soy' detection1 = { 'confidence': 0.81496066, @@ -241,7 +242,7 @@ def test_detect_language_multiple_results(self): client.detect_language(value) def test_translate_bad_result(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'hvala ti' conn = client.connection = _Connection({}) @@ -261,7 +262,7 @@ def test_translate_bad_result(self): self.assertEqual(req['query_params'], query_params) def test_translate_defaults(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'hvala ti' translation = { 'detectedSourceLanguage': 'hr', @@ -291,7 +292,7 @@ def test_translate_defaults(self): self.assertEqual(req['query_params'], query_params) def test_translate_multiple(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value1 = 'hvala ti' translation1 = { 'detectedSourceLanguage': 'hr', @@ -328,7 +329,7 @@ def test_translate_multiple(self): self.assertEqual(req['query_params'], query_params) def test_translate_explicit(self): - client = self._makeOne(self.KEY) + client = self._make_one(self.KEY) value = 'thank you' target_language = 'eo' source_language = 'en' diff --git a/translate/unit_tests/test_connection.py b/translate/unit_tests/test_connection.py index 02c6283dcd2f..5875d4c64df0 100644 --- a/translate/unit_tests/test_connection.py +++ b/translate/unit_tests/test_connection.py @@ -17,15 +17,16 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.translate.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_build_api_url_no_extra_query_params(self): - conn = self._makeOne() + conn = self._make_one() URI = '/'.join([ conn.API_BASE_URL, 'language', @@ -38,7 +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._makeOne() + conn = self._make_one() query_params = [('q', 'val1'), ('q', 'val2')] uri = conn.build_api_url('/foo', query_params=query_params) scheme, netloc, path, qs, _ = urlsplit(uri) diff --git a/vision/unit_tests/test_client.py b/vision/unit_tests/test_client.py index aef60e74c490..55667e4d434c 100644 --- a/vision/unit_tests/test_client.py +++ b/vision/unit_tests/test_client.py @@ -26,16 +26,17 @@ class TestClient(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.client import Client return Client - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_ctor(self): creds = _Credentials() - client = self._makeOne(project=PROJECT, credentials=creds) + client = self._make_one(project=PROJECT, credentials=creds) self.assertEqual(client.project, PROJECT) def test_face_annotation(self): @@ -59,7 +60,7 @@ def test_face_annotation(self): ] } credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) features = [Feature(feature_type=FeatureTypes.FACE_DETECTION, @@ -75,8 +76,8 @@ def test_image_with_client(self): from google.cloud.vision.image import Image credentials = _Credentials() - client = self._makeOne(project=PROJECT, - credentials=credentials) + client = self._make_one(project=PROJECT, + credentials=credentials) image = client.image(source_uri=IMAGE_SOURCE) self.assertIsInstance(image, Image) @@ -85,7 +86,7 @@ def test_face_detection_from_source(self): from unit_tests._fixtures import FACE_DETECTION_RESPONSE RETURNED = FACE_DETECTION_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -102,7 +103,7 @@ def test_face_detection_from_content(self): from unit_tests._fixtures import FACE_DETECTION_RESPONSE RETURNED = FACE_DETECTION_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(content=IMAGE_CONTENT) @@ -121,7 +122,7 @@ def test_label_detection_from_source(self): LABEL_DETECTION_RESPONSE as RETURNED) credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -143,7 +144,7 @@ def test_landmark_detection_from_source(self): LANDMARK_DETECTION_RESPONSE as RETURNED) credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -165,7 +166,7 @@ def test_landmark_detection_from_content(self): LANDMARK_DETECTION_RESPONSE as RETURNED) credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(content=IMAGE_CONTENT) @@ -182,7 +183,7 @@ def test_logo_detection_from_source(self): from unit_tests._fixtures import LOGO_DETECTION_RESPONSE RETURNED = LOGO_DETECTION_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -199,7 +200,7 @@ def test_logo_detection_from_content(self): from unit_tests._fixtures import LOGO_DETECTION_RESPONSE RETURNED = LOGO_DETECTION_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(content=IMAGE_CONTENT) @@ -217,7 +218,7 @@ def test_text_detection_from_source(self): TEXT_DETECTION_RESPONSE as RETURNED) credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -239,7 +240,7 @@ def test_safe_search_detection_from_source(self): RETURNED = SAFE_SEARCH_DETECTION_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -259,7 +260,7 @@ def test_image_properties_detection_from_source(self): RETURNED = IMAGE_PROPERTIES_RESPONSE credentials = _Credentials() - client = self._makeOne(project=PROJECT, credentials=credentials) + client = self._make_one(project=PROJECT, credentials=credentials) client.connection = _Connection(RETURNED) image = client.image(source_uri=IMAGE_SOURCE) @@ -278,26 +279,27 @@ def test_image_properties_detection_from_source(self): class TestVisionRequest(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.client import VisionRequest return VisionRequest - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_make_vision_request(self): from google.cloud.vision.feature import Feature, FeatureTypes feature = Feature(feature_type=FeatureTypes.FACE_DETECTION, max_results=3) - vision_request = self._makeOne(IMAGE_CONTENT, feature) + vision_request = self._make_one(IMAGE_CONTENT, feature) self.assertEqual(IMAGE_CONTENT, vision_request.image) self.assertEqual(FeatureTypes.FACE_DETECTION, vision_request.features[0].feature_type) def test_make_vision_request_with_bad_feature(self): with self.assertRaises(TypeError): - self._makeOne(IMAGE_CONTENT, 'nonsensefeature') + self._make_one(IMAGE_CONTENT, 'nonsensefeature') class _Credentials(object): diff --git a/vision/unit_tests/test_connection.py b/vision/unit_tests/test_connection.py index e9f6e5bc761f..0a7643fc83d2 100644 --- a/vision/unit_tests/test_connection.py +++ b/vision/unit_tests/test_connection.py @@ -17,17 +17,18 @@ class TestConnection(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.connection import Connection return Connection - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_default_url(self): creds = _Credentials() - conn = self._makeOne(creds) - klass = self._getTargetClass() + conn = self._make_one(creds) + klass = self._get_target_class() self.assertEqual(conn.credentials._scopes, klass.SCOPE) diff --git a/vision/unit_tests/test_entity.py b/vision/unit_tests/test_entity.py index 7efb1f78b97c..7ead8388ad27 100644 --- a/vision/unit_tests/test_entity.py +++ b/vision/unit_tests/test_entity.py @@ -16,7 +16,8 @@ class TestEntityAnnotation(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.entity import EntityAnnotation return EntityAnnotation @@ -24,7 +25,7 @@ def test_logo_annotation(self): from unit_tests._fixtures import LOGO_DETECTION_RESPONSE LOGO = LOGO_DETECTION_RESPONSE['responses'][0]['logoAnnotations'][0] - entity_class = self._getTargetClass() + entity_class = self._get_target_class() logo = entity_class.from_api_repr(LOGO) self.assertEqual('/m/05b5c', logo.mid) diff --git a/vision/unit_tests/test_face.py b/vision/unit_tests/test_face.py index 775effd1fc6a..e37da8c42452 100644 --- a/vision/unit_tests/test_face.py +++ b/vision/unit_tests/test_face.py @@ -16,14 +16,15 @@ class TestFace(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.face import Face return Face def setUp(self): from unit_tests._fixtures import FACE_DETECTION_RESPONSE self.FACE_ANNOTATIONS = FACE_DETECTION_RESPONSE['responses'][0] - self.face_class = self._getTargetClass() + self.face_class = self._get_target_class() self.face = self.face_class.from_api_repr( self.FACE_ANNOTATIONS['faceAnnotations'][0]) diff --git a/vision/unit_tests/test_feature.py b/vision/unit_tests/test_feature.py index f2de07f2e632..736f2519fe1b 100644 --- a/vision/unit_tests/test_feature.py +++ b/vision/unit_tests/test_feature.py @@ -16,26 +16,27 @@ class TestFeature(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.feature import Feature return Feature - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_construct_feature(self): from google.cloud.vision.feature import FeatureTypes - feature = self._makeOne(FeatureTypes.LABEL_DETECTION) + feature = self._make_one(FeatureTypes.LABEL_DETECTION) self.assertEqual(1, feature.max_results) self.assertEqual('LABEL_DETECTION', feature.feature_type) - feature = self._makeOne(FeatureTypes.FACE_DETECTION, 3) + feature = self._make_one(FeatureTypes.FACE_DETECTION, 3) self.assertEqual(3, feature.max_results) self.assertEqual('FACE_DETECTION', feature.feature_type) def test_feature_as_dict(self): from google.cloud.vision.feature import FeatureTypes - feature = self._makeOne(FeatureTypes.FACE_DETECTION, max_results=5) + feature = self._make_one(FeatureTypes.FACE_DETECTION, max_results=5) EXPECTED = { 'type': 'FACE_DETECTION', 'maxResults': 5 @@ -44,5 +45,5 @@ def test_feature_as_dict(self): def test_bad_feature_type(self): with self.assertRaises(AttributeError): - self._makeOne('something_not_feature_type', - max_results=5) + self._make_one('something_not_feature_type', + max_results=5) diff --git a/vision/unit_tests/test_image.py b/vision/unit_tests/test_image.py index b8a3202e728c..756e1f517e5a 100644 --- a/vision/unit_tests/test_image.py +++ b/vision/unit_tests/test_image.py @@ -25,15 +25,16 @@ class TestVisionImage(unittest.TestCase): - def _getTargetClass(self): + @staticmethod + def _get_target_class(): from google.cloud.vision.image import Image return Image - def _makeOne(self, *args, **kw): - return self._getTargetClass()(*args, **kw) + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) def test_image_source_type_content(self): - image = self._makeOne(CLIENT_MOCK, content=IMAGE_CONTENT) + image = self._make_one(CLIENT_MOCK, content=IMAGE_CONTENT) _AS_DICT = { 'content': B64_IMAGE_CONTENT @@ -44,7 +45,7 @@ def test_image_source_type_content(self): self.assertEqual(_AS_DICT, image.as_dict()) def test_image_source_type_google_cloud_storage(self): - image = self._makeOne(CLIENT_MOCK, source_uri=IMAGE_SOURCE) + image = self._make_one(CLIENT_MOCK, source_uri=IMAGE_SOURCE) _AS_DICT = { 'source': { @@ -57,13 +58,13 @@ def test_image_source_type_google_cloud_storage(self): self.assertEqual(_AS_DICT, image.as_dict()) def test_cannot_set_both_source_and_content(self): - image = self._makeOne(CLIENT_MOCK, content=IMAGE_CONTENT) + image = self._make_one(CLIENT_MOCK, content=IMAGE_CONTENT) self.assertEqual(B64_IMAGE_CONTENT, image.content) with self.assertRaises(AttributeError): image.source = IMAGE_SOURCE - image = self._makeOne(CLIENT_MOCK, source_uri=IMAGE_SOURCE) + image = self._make_one(CLIENT_MOCK, source_uri=IMAGE_SOURCE) self.assertEqual(IMAGE_SOURCE, image.source) with self.assertRaises(AttributeError): image.content = IMAGE_CONTENT