Ejemplo n.º 1
0
    def test_ctor_w_implicit_inputs(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT
        from google.cloud import client as _base_client

        OTHER = 'other'
        creds = object()
        default_called = []

        def fallback_mock(project):
            default_called.append(project)
            return project or OTHER

        klass = self._getTargetClass()
        with _Monkey(_MUT, _determine_default_project=fallback_mock):
            with _Monkey(_base_client, get_credentials=lambda: creds):
                client = klass()
        self.assertEqual(client.project, OTHER)
        self.assertEqual(client.namespace, None)
        self.assertTrue(isinstance(client.connection, _MockConnection))
        self.assertTrue(client.connection.credentials is creds)
        self.assertTrue(client.connection.http is None)
        self.assertTrue(client.current_batch is None)
        self.assertTrue(client.current_transaction is None)
        self.assertEqual(default_called, [None])
Ejemplo n.º 2
0
    def test_ctor_w_implicit_inputs(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT
        from google.cloud import client as _base_client

        OTHER = 'other'
        creds = object()
        default_called = []

        def fallback_mock(project):
            default_called.append(project)
            return project or OTHER

        klass = self._getTargetClass()
        with _Monkey(_MUT,
                     _determine_default_project=fallback_mock):
            with _Monkey(_base_client,
                         get_credentials=lambda: creds):
                client = klass()
        self.assertEqual(client.project, OTHER)
        self.assertEqual(client.namespace, None)
        self.assertTrue(isinstance(client.connection, _MockConnection))
        self.assertTrue(client.connection.credentials is creds)
        self.assertTrue(client.connection.http is None)
        self.assertTrue(client.current_batch is None)
        self.assertTrue(client.current_transaction is None)
        self.assertEqual(default_called, [None])
Ejemplo n.º 3
0
    def test_gae(self):
        from google.cloud import _helpers as MUT
        from unit_tests._testing import _Monkey

        with _Monkey(os, name='not-nt'):
            with _Monkey(MUT, _USER_ROOT=None):
                result = self._callFUT()

        self.assertIsNone(result)
    def test_gae(self):
        from google.cloud import _helpers as MUT
        from unit_tests._testing import _Monkey

        with _Monkey(os, name='not-nt'):
            with _Monkey(MUT, _USER_ROOT=None):
                result = self._callFUT()

        self.assertIsNone(result)
    def test_it(self):
        from google.cloud import _helpers as MUT
        from unit_tests._testing import _Monkey

        appdata_dir = 'a'
        environ = {'APPDATA': appdata_dir}
        config_file = 'b'
        with _Monkey(os, getenv=environ.get):
            with _Monkey(MUT, _GCLOUD_CONFIG_FILE=config_file):
                result = self._callFUT()

        expected = os.path.join(appdata_dir, config_file)
        self.assertEqual(result, expected)
Ejemplo n.º 6
0
    def test_it(self):
        from google.cloud import _helpers as MUT
        from unit_tests._testing import _Monkey

        appdata_dir = 'a'
        environ = {'APPDATA': appdata_dir}
        config_file = 'b'
        with _Monkey(os, getenv=environ.get):
            with _Monkey(MUT, _GCLOUD_CONFIG_FILE=config_file):
                result = self._callFUT()

        expected = os.path.join(appdata_dir, config_file)
        self.assertEqual(result, expected)
Ejemplo n.º 7
0
    def test_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.pubsub import _gax as MUT

        channels = []
        mock_result = object()
        insecure_args = []
        mock_channel = object()

        def mock_subscriber_api(channel):
            channels.append(channel)
            return mock_result

        def mock_insecure_channel(host):
            insecure_args.append(host)
            return mock_channel

        host = 'CURR_HOST:1234'
        connection = _Connection(in_emulator=True, host=host)
        with _Monkey(MUT,
                     SubscriberApi=mock_subscriber_api,
                     insecure_channel=mock_insecure_channel):
            result = self._callFUT(connection)

        self.assertIs(result, mock_result)
        self.assertEqual(channels, [mock_channel])
        self.assertEqual(insecure_args, [host])
Ejemplo n.º 8
0
    def test_logging_api_w_gax(self):
        from google.cloud.logging import client as MUT
        from unit_tests._testing import _Monkey

        wrapped = object()
        _called_with = []

        def _generated_api(*args, **kw):
            _called_with.append((args, kw))
            return wrapped

        class _GaxLoggingAPI(object):
            def __init__(self, _wrapped):
                self._wrapped = _wrapped

        creds = _Credentials()
        client = self._makeOne(project=self.PROJECT, credentials=creds)

        with _Monkey(MUT,
                     _USE_GAX=True,
                     GeneratedLoggingAPI=_generated_api,
                     GAXLoggingAPI=_GaxLoggingAPI):
            api = client.logging_api

        self.assertIsInstance(api, _GaxLoggingAPI)
        self.assertTrue(api._wrapped is wrapped)
        # API instance is cached
        again = client.logging_api
        self.assertTrue(again is api)
Ejemplo n.º 9
0
    def test_it_with_stubs(self):
        from unit_tests._testing import _Monkey
        from google.cloud.storage import _helpers as MUT

        class _Buffer(object):
            def __init__(self, return_vals):
                self.return_vals = return_vals
                self._block_sizes = []

            def read(self, block_size):
                self._block_sizes.append(block_size)
                return self.return_vals.pop()

        BASE64 = _Base64()
        DIGEST_VAL = object()
        BYTES_TO_SIGN = b'BYTES_TO_SIGN'
        BUFFER = _Buffer([b'', BYTES_TO_SIGN])
        MD5 = _MD5(DIGEST_VAL)

        with _Monkey(MUT, base64=BASE64, md5=MD5):
            SIGNED_CONTENT = self._callFUT(BUFFER)

        self.assertEqual(BUFFER._block_sizes, [8192, 8192])
        self.assertIs(SIGNED_CONTENT, DIGEST_VAL)
        self.assertEqual(BASE64._called_b64encode, [DIGEST_VAL])
        self.assertEqual(MD5._called, [None])
        self.assertEqual(MD5.hash_obj.num_digest_calls, 1)
        self.assertEqual(MD5.hash_obj._blocks, [BYTES_TO_SIGN])
Ejemplo n.º 10
0
    def test_without_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import client as MUT

        credentials = _Credentials()
        user_agent = 'you-sir-age-int'
        client = _Client(credentials, user_agent)

        fake_stub = object()
        make_secure_stub_args = []

        def mock_make_secure_stub(*args):
            make_secure_stub_args.append(args)
            return fake_stub

        with _Monkey(MUT, make_secure_stub=mock_make_secure_stub):
            result = self._callFUT(client)

        self.assertIs(result, fake_stub)
        self.assertEqual(make_secure_stub_args, [
            (
                client.credentials,
                client.user_agent,
                MUT.bigtable_instance_admin_pb2.BigtableInstanceAdminStub,
                MUT.INSTANCE_ADMIN_HOST,
            ),
        ])
Ejemplo n.º 11
0
    def test_without_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import client as MUT

        credentials = _Credentials()
        user_agent = 'you-sir-age-int'
        client = _Client(credentials, user_agent)

        fake_stub = object()
        make_secure_stub_args = []

        def mock_make_secure_stub(*args):
            make_secure_stub_args.append(args)
            return fake_stub

        with _Monkey(MUT, make_secure_stub=mock_make_secure_stub):
            result = self._callFUT(client)

        self.assertIs(result, fake_stub)
        self.assertEqual(make_secure_stub_args, [
            (
                client.credentials,
                client.user_agent,
                MUT.operations_grpc_pb2.OperationsStub,
                MUT.OPERATIONS_API_HOST,
            ),
        ])
Ejemplo n.º 12
0
    def test_w_exceptions_lt_max_retries(self):
        from google.cloud.streaming.exceptions import RetryAfterError
        from google.cloud.streaming import http_wrapper as MUT
        from unit_tests._testing import _Monkey

        HTTP, RESPONSE = object(), object()
        REQUEST = _Request()
        _created, _checked = [], []
        _counter = [None] * 4

        def _wo_exception(*args, **kw):
            _created.append((args, kw))
            if _counter:
                _counter.pop()
                raise RetryAfterError(RESPONSE, '', REQUEST.url, 0.1)
            return RESPONSE

        with _Monkey(MUT,
                     _make_api_request_no_retry=_wo_exception,
                     _check_response=_checked.append):
            response = self._callFUT(HTTP, REQUEST, retries=5)

        self.assertIs(response, RESPONSE)
        self.assertEqual(len(_created), 5)
        expected_kw = {'redirections': MUT._REDIRECTIONS}
        for attempt in _created:
            self.assertEqual(attempt, ((HTTP, REQUEST), expected_kw))
        self.assertEqual(_checked, [])  # not called by '_wo_exception'
Ejemplo n.º 13
0
    def test_w_exceptions_lt_max_retries(self):
        from google.cloud.streaming.exceptions import RetryAfterError
        from google.cloud.streaming import http_wrapper as MUT
        from unit_tests._testing import _Monkey

        HTTP, RESPONSE = object(), object()
        REQUEST = _Request()
        _created, _checked = [], []
        _counter = [None] * 4

        def _wo_exception(*args, **kw):
            _created.append((args, kw))
            if _counter:
                _counter.pop()
                raise RetryAfterError(RESPONSE, '', REQUEST.url, 0.1)
            return RESPONSE

        with _Monkey(MUT, _make_api_request_no_retry=_wo_exception,
                     _check_response=_checked.append):
            response = self._callFUT(HTTP, REQUEST, retries=5)

        self.assertTrue(response is RESPONSE)
        self.assertEqual(len(_created), 5)
        expected_kw = {'redirections': MUT._REDIRECTIONS}
        for attempt in _created:
            self.assertEqual(attempt, ((HTTP, REQUEST), expected_kw))
        self.assertEqual(_checked, [])  # not called by '_wo_exception'
Ejemplo n.º 14
0
    def test_w_loggable_body_w_http(self):
        from unit_tests._testing import _Monkey
        from google.cloud.streaming import http_wrapper as MUT

        class _Connection(object):
            debuglevel = 0

            def set_debuglevel(self, value):
                self.debuglevel = value

        request = _Request(loggable_body=object())
        LEVEL = 1
        _httplib2 = _Dummy(debuglevel=0)
        update_me = _Connection()
        skip_me = _Connection()
        connections = {'update:me': update_me, 'skip_me': skip_me}
        _http = _Dummy(connections=connections)
        with _Monkey(MUT, httplib2=_httplib2):
            with self._makeOne(request, LEVEL, _http):
                self.assertEqual(_httplib2.debuglevel, LEVEL)
                self.assertEqual(update_me.debuglevel, LEVEL)
                self.assertEqual(skip_me.debuglevel, 0)
        self.assertEqual(_httplib2.debuglevel, 0)
        self.assertEqual(update_me.debuglevel, 0)
        self.assertEqual(skip_me.debuglevel, 0)
Ejemplo n.º 15
0
    def test_from_pb_w_metadata_and_kwargs(self):
        from google.longrunning import operations_pb2
        from google.protobuf.any_pb2 import Any
        from google.protobuf.struct_pb2 import Struct, Value
        from google.cloud import operation as MUT
        from unit_tests._testing import _Monkey
        TYPE_URI = 'type.googleapis.com/%s' % (Struct.DESCRIPTOR.full_name,)
        type_url_map = {TYPE_URI: Struct}

        client = _Client()
        meta = Struct(fields={'foo': Value(string_value=u'Bar')})
        metadata_pb = Any(type_url=TYPE_URI, value=meta.SerializeToString())
        operation_pb = operations_pb2.Operation(
            name=self.OPERATION_NAME, metadata=metadata_pb)
        klass = self._getTargetClass()

        with _Monkey(MUT, _TYPE_URL_MAP=type_url_map):
            operation = klass.from_pb(operation_pb, client, baz='qux')

        self.assertEqual(operation.name, self.OPERATION_NAME)
        self.assertTrue(operation.client is client)
        pb_metadata = operation.pb_metadata
        self.assertTrue(isinstance(pb_metadata, Struct))
        self.assertEqual(list(pb_metadata.fields), ['foo'])
        self.assertEqual(pb_metadata.fields['foo'].string_value, 'Bar')
        self.assertEqual(operation.metadata, {'baz': 'qux'})
    def test_no_value(self):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers

        with _Monkey(_helpers, app_identity=None):
            dataset_id = self._callFUT()
            self.assertEqual(dataset_id, None)
Ejemplo n.º 17
0
    def test_w_loggable_body_w_http(self):
        from unit_tests._testing import _Monkey
        from google.cloud.streaming import http_wrapper as MUT

        class _Connection(object):
            debuglevel = 0

            def set_debuglevel(self, value):
                self.debuglevel = value

        request = _Request(loggable_body=object())
        LEVEL = 1
        _httplib2 = _Dummy(debuglevel=0)
        update_me = _Connection()
        skip_me = _Connection()
        connections = {'update:me': update_me, 'skip_me': skip_me}
        _http = _Dummy(connections=connections)
        with _Monkey(MUT, httplib2=_httplib2):
            with self._makeOne(request, LEVEL, _http):
                self.assertEqual(_httplib2.debuglevel, LEVEL)
                self.assertEqual(update_me.debuglevel, LEVEL)
                self.assertEqual(skip_me.debuglevel, 0)
        self.assertEqual(_httplib2.debuglevel, 0)
        self.assertEqual(update_me.debuglevel, 0)
        self.assertEqual(skip_me.debuglevel, 0)
Ejemplo n.º 18
0
    def test_get_multi_max_loops(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT
        from google.cloud.datastore.key import Key

        KIND = 'Kind'
        ID = 1234

        # Make a found entity pb to be returned from mock backend.
        entity_pb = _make_entity_pb(self.PROJECT, KIND, ID, 'foo', 'Foo')

        # Make a connection to return the entity pb.
        creds = object()
        client = self._makeOne(credentials=creds)
        client.connection._add_lookup_result([entity_pb])

        key = Key(KIND, ID, project=self.PROJECT)
        deferred = []
        missing = []
        with _Monkey(_MUT, _MAX_LOOPS=-1):
            result = client.get_multi([key], missing=missing,
                                      deferred=deferred)

        # Make sure we have no results, even though the connection has been
        # set up as in `test_hit` to return a single result.
        self.assertEqual(result, [])
        self.assertEqual(missing, [])
        self.assertEqual(deferred, [])
Ejemplo n.º 19
0
    def test_logging_api_w_gax(self):
        from google.cloud.logging import client as MUT
        from unit_tests._testing import _Monkey

        wrapped = object()
        _called_with = []

        def _generated_api(*args, **kw):
            _called_with.append((args, kw))
            return wrapped

        class _GaxLoggingAPI(object):

            def __init__(self, _wrapped):
                self._wrapped = _wrapped

        creds = _Credentials()
        client = self._makeOne(project=self.PROJECT, credentials=creds)

        with _Monkey(MUT,
                     _USE_GAX=True,
                     GeneratedLoggingAPI=_generated_api,
                     GAXLoggingAPI=_GaxLoggingAPI):
            api = client.logging_api

        self.assertIsInstance(api, _GaxLoggingAPI)
        self.assertTrue(api._wrapped is wrapped)
        # API instance is cached
        again = client.logging_api
        self.assertTrue(again is api)
Ejemplo n.º 20
0
    def _helper(self, target, host, port=None):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers as MUT

        mock_result = object()
        stub_inputs = []
        CHANNEL = object()

        class _GRPCModule(object):

            def insecure_channel(self, *args):
                self.insecure_channel_args = args
                return CHANNEL

        grpc_mod = _GRPCModule()

        def mock_stub_class(channel):
            stub_inputs.append(channel)
            return mock_result

        with _Monkey(MUT, grpc=grpc_mod):
            result = self._callFUT(mock_stub_class, host, port=port)

        self.assertTrue(result is mock_result)
        self.assertEqual(stub_inputs, [CHANNEL])
        self.assertEqual(grpc_mod.insecure_channel_args, (target,))
    def test_no_value(self):
        from unit_tests._testing import _Monkey

        environ = {}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, None)
    def _helper(self, target, host, port=None):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers as MUT

        mock_result = object()
        stub_inputs = []
        CHANNEL = object()

        class _GRPCModule(object):
            def insecure_channel(self, *args):
                self.insecure_channel_args = args
                return CHANNEL

        grpc_mod = _GRPCModule()

        def mock_stub_class(channel):
            stub_inputs.append(channel)
            return mock_result

        with _Monkey(MUT, grpc=grpc_mod):
            result = self._callFUT(mock_stub_class, host, port=port)

        self.assertTrue(result is mock_result)
        self.assertEqual(stub_inputs, [CHANNEL])
        self.assertEqual(grpc_mod.insecure_channel_args, (target, ))
Ejemplo n.º 23
0
    def test_ctor_defaults(self):
        from unit_tests._testing import _Monkey
        from google.cloud import client

        PROJECT = 'PROJECT'
        CREDENTIALS = object()
        FUNC_CALLS = []

        def mock_determine_proj(project):
            FUNC_CALLS.append((project, '_determine_default_project'))
            return PROJECT

        def mock_get_credentials():
            FUNC_CALLS.append('get_credentials')
            return CREDENTIALS

        with _Monkey(client, get_credentials=mock_get_credentials,
                     _determine_default_project=mock_determine_proj):
            client_obj = self._makeOne()

        self.assertEqual(client_obj.project, PROJECT)
        self.assertTrue(isinstance(client_obj.connection, _MockConnection))
        self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
        self.assertEqual(
            FUNC_CALLS,
            [(None, '_determine_default_project'), 'get_credentials'])
Ejemplo n.º 24
0
    def test_no_value(self):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers

        with _Monkey(_helpers, app_identity=None):
            dataset_id = self._callFUT()
            self.assertEqual(dataset_id, None)
Ejemplo n.º 25
0
    def test_ctor_defaults(self):
        from unit_tests._testing import _Monkey
        from google.cloud import client

        PROJECT = 'PROJECT'
        CREDENTIALS = object()
        FUNC_CALLS = []

        def mock_determine_proj(project):
            FUNC_CALLS.append((project, '_determine_default_project'))
            return PROJECT

        def mock_get_credentials():
            FUNC_CALLS.append('get_credentials')
            return CREDENTIALS

        with _Monkey(client, get_credentials=mock_get_credentials,
                     _determine_default_project=mock_determine_proj):
            client_obj = self._makeOne()

        self.assertEqual(client_obj.project, PROJECT)
        self.assertIsInstance(client_obj.connection, _MockConnection)
        self.assertIs(client_obj.connection.credentials, CREDENTIALS)
        self.assertEqual(
            FUNC_CALLS,
            [(None, '_determine_default_project'), 'get_credentials'])
Ejemplo n.º 26
0
    def test_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.pubsub import _gax as MUT

        channels = []
        mock_result = object()
        insecure_args = []
        mock_channel = object()

        def mock_subscriber_api(channel):
            channels.append(channel)
            return mock_result

        def mock_insecure_channel(host):
            insecure_args.append(host)
            return mock_channel

        host = 'CURR_HOST:1234'
        connection = _Connection(in_emulator=True, host=host)
        with _Monkey(MUT, SubscriberApi=mock_subscriber_api,
                     insecure_channel=mock_insecure_channel):
            result = self._callFUT(connection)

        self.assertIs(result, mock_result)
        self.assertEqual(channels, [mock_channel])
        self.assertEqual(insecure_args, [host])
Ejemplo n.º 27
0
    def test_publish_single_bytes_wo_attrs_w_add_timestamp_alt_client(self):
        import base64
        import datetime
        from google.cloud.pubsub import topic as MUT
        from google.cloud._helpers import _RFC3339_MICROS
        from unit_tests._testing import _Monkey
        NOW = datetime.datetime.utcnow()

        def _utcnow():
            return NOW

        PAYLOAD = b'This is the message text'
        B64 = base64.b64encode(PAYLOAD).decode('ascii')
        MSGID = 'DEADBEEF'
        MESSAGE = {
            'data': B64,
            'attributes': {'timestamp': NOW.strftime(_RFC3339_MICROS)},
        }
        client1 = _Client(project=self.PROJECT)
        client2 = _Client(project=self.PROJECT)
        api = client2.publisher_api = _FauxPublisherAPI()
        api._topic_publish_response = [MSGID]

        topic = self._makeOne(self.TOPIC_NAME, client=client1,
                              timestamp_messages=True)
        with _Monkey(MUT, _NOW=_utcnow):
            msgid = topic.publish(PAYLOAD, client=client2)

        self.assertEqual(msgid, MSGID)
        self.assertEqual(api._topic_published, (self.TOPIC_PATH, [MESSAGE]))
Ejemplo n.º 28
0
    def test_get_multi_max_loops(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT
        from google.cloud.datastore.key import Key

        KIND = 'Kind'
        ID = 1234

        # Make a found entity pb to be returned from mock backend.
        entity_pb = _make_entity_pb(self.PROJECT, KIND, ID, 'foo', 'Foo')

        # Make a connection to return the entity pb.
        creds = object()
        client = self._makeOne(credentials=creds)
        client.connection._add_lookup_result([entity_pb])

        key = Key(KIND, ID, project=self.PROJECT)
        deferred = []
        missing = []
        with _Monkey(_MUT, _MAX_LOOPS=-1):
            result = client.get_multi([key],
                                      missing=missing,
                                      deferred=deferred)

        # Make sure we have no results, even though the connection has been
        # set up as in `test_hit` to return a single result.
        self.assertEqual(result, [])
        self.assertEqual(missing, [])
        self.assertEqual(deferred, [])
Ejemplo n.º 29
0
    def _determine_default_helper(self,
                                  gcd=None,
                                  fallback=None,
                                  project_called=None):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client

        _callers = []

        def gcd_mock():
            _callers.append('gcd_mock')
            return gcd

        def fallback_mock(project=None):
            _callers.append(('fallback_mock', project))
            return fallback

        patched_methods = {
            '_get_gcd_project': gcd_mock,
            '_base_default_project': fallback_mock,
        }

        with _Monkey(client, **patched_methods):
            returned_project = self._callFUT(project_called)

        return returned_project, _callers
Ejemplo n.º 30
0
    def test_subscriber_api_w_gax(self):
        from google.cloud.pubsub import client as MUT
        from unit_tests._testing import _Monkey

        wrapped = object()
        _called_with = []

        def _generated_api(*args, **kw):
            _called_with.append((args, kw))
            return wrapped

        class _GaxSubscriberAPI(object):

            def __init__(self, _wrapped):
                self._wrapped = _wrapped

        creds = _Credentials()
        client = self._makeOne(project=self.PROJECT, credentials=creds)

        with _Monkey(MUT,
                     _USE_GAX=True,
                     make_gax_subscriber_api=_generated_api,
                     GAXSubscriberAPI=_GaxSubscriberAPI):
            api = client.subscriber_api

        self.assertIsInstance(api, _GaxSubscriberAPI)
        self.assertTrue(api._wrapped is wrapped)
        # API instance is cached
        again = client.subscriber_api
        self.assertTrue(again is api)
        args = (client.connection,)
        self.assertEqual(_called_with, [(args, {})])
Ejemplo n.º 31
0
    def test_without_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import client as MUT

        credentials = _Credentials()
        user_agent = 'you-sir-age-int'
        client = _Client(credentials, user_agent)

        fake_stub = object()
        make_secure_stub_args = []

        def mock_make_secure_stub(*args):
            make_secure_stub_args.append(args)
            return fake_stub

        with _Monkey(MUT, make_secure_stub=mock_make_secure_stub):
            result = self._callFUT(client)

        self.assertIs(result, fake_stub)
        self.assertEqual(make_secure_stub_args, [
            (
                client.credentials,
                client.user_agent,
                MUT.bigtable_instance_admin_pb2.BigtableInstanceAdminStub,
                MUT.INSTANCE_ADMIN_HOST,
            ),
        ])
Ejemplo n.º 32
0
    def test_it_with_stubs(self):
        from unit_tests._testing import _Monkey
        from google.cloud.storage import _helpers as MUT

        class _Buffer(object):

            def __init__(self, return_vals):
                self.return_vals = return_vals
                self._block_sizes = []

            def read(self, block_size):
                self._block_sizes.append(block_size)
                return self.return_vals.pop()

        BASE64 = _Base64()
        DIGEST_VAL = object()
        BYTES_TO_SIGN = b'BYTES_TO_SIGN'
        BUFFER = _Buffer([b'', BYTES_TO_SIGN])
        MD5 = _MD5(DIGEST_VAL)

        with _Monkey(MUT, base64=BASE64, md5=MD5):
            SIGNED_CONTENT = self._callFUT(BUFFER)

        self.assertEqual(BUFFER._block_sizes, [8192, 8192])
        self.assertTrue(SIGNED_CONTENT is DIGEST_VAL)
        self.assertEqual(BASE64._called_b64encode, [DIGEST_VAL])
        self.assertEqual(MD5._called, [None])
        self.assertEqual(MD5.hash_obj.num_digest_calls, 1)
        self.assertEqual(MD5.hash_obj._blocks, [BYTES_TO_SIGN])
Ejemplo n.º 33
0
    def test_without_emulator(self):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import client as MUT

        credentials = _Credentials()
        user_agent = 'you-sir-age-int'
        client = _Client(credentials, user_agent)

        fake_stub = object()
        make_secure_stub_args = []

        def mock_make_secure_stub(*args):
            make_secure_stub_args.append(args)
            return fake_stub

        with _Monkey(MUT, make_secure_stub=mock_make_secure_stub):
            result = self._callFUT(client)

        self.assertIs(result, fake_stub)
        self.assertEqual(make_secure_stub_args, [
            (
                client.credentials,
                client.user_agent,
                MUT.operations_grpc_pb2.OperationsStub,
                MUT.OPERATIONS_API_HOST,
            ),
        ])
Ejemplo n.º 34
0
    def test_no_value(self):
        from unit_tests._testing import _Monkey

        environ = {}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, None)
Ejemplo n.º 35
0
    def test_ctor_w_project_no_environ(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT

        # 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)
Ejemplo n.º 36
0
    def test_ctor_w_project_no_environ(self):
        from unit_tests._testing import _Monkey
        from google.cloud.datastore import client as _MUT

        # 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)
    def test_no_environment_variable_set(self):
        from unit_tests._testing import _Monkey

        environ = {}
        with _Monkey(os, getenv=environ.get):
            result = self._callFUT()

        self.assertIsNone(result)
Ejemplo n.º 38
0
    def test_no_environment_variable_set(self):
        from unit_tests._testing import _Monkey

        environ = {}
        with _Monkey(os, getenv=environ.get):
            result = self._callFUT()

        self.assertIsNone(result)
Ejemplo n.º 39
0
    def _constructor_test_helper(self,
                                 expected_scopes,
                                 creds,
                                 read_only=False,
                                 admin=False,
                                 user_agent=None,
                                 expected_creds=None):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import client as MUT

        user_agent = user_agent or MUT.DEFAULT_USER_AGENT

        mock_make_data_stub = _MakeStubMock()
        mock_make_instance_stub = _MakeStubMock()
        mock_make_operations_stub = _MakeStubMock()
        mock_make_table_stub = _MakeStubMock()
        with _Monkey(MUT,
                     _make_data_stub=mock_make_data_stub,
                     _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)

        # Verify the mocks.
        self.assertEqual(mock_make_data_stub.calls, [client])
        if admin:
            self.assertSequenceEqual(mock_make_instance_stub.calls, [client])
            self.assertSequenceEqual(mock_make_operations_stub.calls, [client])
            self.assertSequenceEqual(mock_make_table_stub.calls, [client])
        else:
            self.assertSequenceEqual(mock_make_instance_stub.calls, [])
            self.assertSequenceEqual(mock_make_operations_stub.calls, [])
            self.assertSequenceEqual(mock_make_table_stub.calls, [])

        expected_creds = expected_creds or creds
        self.assertTrue(client._credentials is expected_creds)
        if expected_scopes is not None:
            self.assertEqual(client._credentials.scopes, expected_scopes)

        self.assertEqual(client.project, self.PROJECT)
        self.assertEqual(client.user_agent, user_agent)
        # Check gRPC stubs (or mocks of them) are set
        self.assertIs(client._data_stub, mock_make_data_stub.result)
        if admin:
            self.assertIs(client._instance_stub_internal,
                          mock_make_instance_stub.result)
            self.assertIs(client._operations_stub_internal,
                          mock_make_operations_stub.result)
            self.assertIs(client._table_stub_internal,
                          mock_make_table_stub.result)
        else:
            self.assertIsNone(client._instance_stub_internal)
            self.assertIsNone(client._operations_stub_internal)
            self.assertIsNone(client._table_stub_internal)
Ejemplo n.º 40
0
    def test_value_set(self):
        from unit_tests._testing import _Monkey
        from google.cloud._helpers import PROJECT

        MOCK_PROJECT = object()
        environ = {PROJECT: MOCK_PROJECT}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, MOCK_PROJECT)
    def test_value_set(self):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers

        APP_ENGINE_ID = object()
        APP_IDENTITY = _AppIdentity(APP_ENGINE_ID)
        with _Monkey(_helpers, app_identity=APP_IDENTITY):
            dataset_id = self._callFUT()
            self.assertEqual(dataset_id, APP_ENGINE_ID)
Ejemplo n.º 42
0
    def test_value_set(self):
        from unit_tests._testing import _Monkey
        from google.cloud import _helpers

        APP_ENGINE_ID = object()
        APP_IDENTITY = _AppIdentity(APP_ENGINE_ID)
        with _Monkey(_helpers, app_identity=APP_IDENTITY):
            dataset_id = self._callFUT()
            self.assertEqual(dataset_id, APP_ENGINE_ID)
    def test_value_set(self):
        from unit_tests._testing import _Monkey
        from google.cloud._helpers import PROJECT

        MOCK_PROJECT = object()
        environ = {PROJECT: MOCK_PROJECT}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, MOCK_PROJECT)
Ejemplo n.º 44
0
    def test_wo_loggable_body_wo_http(self):
        from unit_tests._testing import _Monkey
        from google.cloud.streaming import http_wrapper as MUT

        request = _Request()
        LEVEL = 1
        _httplib2 = _Dummy(debuglevel=0)
        with _Monkey(MUT, httplib2=_httplib2):
            with self._makeOne(request, LEVEL):
                self.assertEqual(_httplib2.debuglevel, 0)
Ejemplo n.º 45
0
    def _monkeyConnection(self, connection):
        from six.moves import http_client
        from unit_tests._testing import _Monkey

        def _connection_factory(host, timeout):
            connection.host = host
            connection.timeout = timeout
            return connection

        return _Monkey(http_client, HTTPConnection=_connection_factory)
Ejemplo n.º 46
0
    def test_it(self):
        from unit_tests._testing import _Monkey
        from google.cloud import credentials as MUT

        client = _Client()
        with _Monkey(MUT, client=client):
            found = self._callFUT()
        self.assertTrue(isinstance(found, _Credentials))
        self.assertTrue(found is client._signed)
        self.assertTrue(client._get_app_default_called)
    def _monkeyConnection(self, connection):
        from six.moves import http_client
        from unit_tests._testing import _Monkey

        def _connection_factory(host, timeout):
            connection.host = host
            connection.timeout = timeout
            return connection

        return _Monkey(http_client, HTTPConnection=_connection_factory)
Ejemplo n.º 48
0
    def test_value_set(self):
        import os
        from unit_tests._testing import _Monkey
        from google.cloud.datastore.client import GCD_DATASET

        MOCK_PROJECT = object()
        environ = {GCD_DATASET: MOCK_PROJECT}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, MOCK_PROJECT)
Ejemplo n.º 49
0
    def test_wo_loggable_body_wo_http(self):
        from unit_tests._testing import _Monkey
        from google.cloud.streaming import http_wrapper as MUT

        request = _Request()
        LEVEL = 1
        _httplib2 = _Dummy(debuglevel=0)
        with _Monkey(MUT, httplib2=_httplib2):
            with self._makeOne(request, LEVEL):
                self.assertEqual(_httplib2.debuglevel, 0)
Ejemplo n.º 50
0
    def test_value_set(self):
        import os
        from unit_tests._testing import _Monkey
        from google.cloud.datastore.client import GCD_DATASET

        MOCK_PROJECT = object()
        environ = {GCD_DATASET: MOCK_PROJECT}
        with _Monkey(os, getenv=environ.get):
            project = self._callFUT()
            self.assertEqual(project, MOCK_PROJECT)
Ejemplo n.º 51
0
    def test_it(self):
        from unit_tests._testing import _Monkey
        from google.cloud import credentials as MUT

        client = _Client()
        with _Monkey(MUT, client=client):
            found = self._callFUT()
        self.assertTrue(isinstance(found, _Credentials))
        self.assertTrue(found is client._signed)
        self.assertTrue(client._get_app_default_called)
Ejemplo n.º 52
0
    def test_commit(self):
        from unit_tests._testing import _Monkey
        from unit_tests.bigtable._testing import _FakeStub
        from google.cloud.bigtable import row as MUT

        row_key = b'row_key'
        table_name = 'projects/more-stuff'
        column_family_id = u'column_family_id'
        column = b'column'
        client = _Client()
        table = _Table(table_name, client=client)
        row = self._makeOne(row_key, table)

        # Create request_pb
        value = b'bytes-value'
        # We will call row.append_cell_value(COLUMN_FAMILY_ID, COLUMN, value).
        request_pb = _ReadModifyWriteRowRequestPB(
            table_name=table_name,
            row_key=row_key,
            rules=[
                _ReadModifyWriteRulePB(
                    family_name=column_family_id,
                    column_qualifier=column,
                    append_value=value,
                ),
            ],
        )

        # Create response_pb
        response_pb = object()

        # Patch the stub used by the API method.
        client._data_stub = stub = _FakeStub(response_pb)

        # Create expected_result.
        row_responses = []
        expected_result = object()

        def mock_parse_rmw_row_response(row_response):
            row_responses.append(row_response)
            return expected_result

        # Perform the method and check the result.
        with _Monkey(MUT, _parse_rmw_row_response=mock_parse_rmw_row_response):
            row.append_cell_value(column_family_id, column, value)
            result = row.commit()

        self.assertEqual(result, expected_result)
        self.assertEqual(stub.method_calls, [(
            'ReadModifyWriteRow',
            (request_pb,),
            {},
        )])
        self.assertEqual(row_responses, [response_pb])
        self.assertEqual(row._rule_pb_list, [])
Ejemplo n.º 53
0
    def test_commit(self):
        from unit_tests._testing import _Monkey
        from unit_tests.bigtable._testing import _FakeStub
        from google.cloud.bigtable import row as MUT

        row_key = b'row_key'
        table_name = 'projects/more-stuff'
        column_family_id = u'column_family_id'
        column = b'column'
        client = _Client()
        table = _Table(table_name, client=client)
        row = self._makeOne(row_key, table)

        # Create request_pb
        value = b'bytes-value'
        # We will call row.append_cell_value(COLUMN_FAMILY_ID, COLUMN, value).
        request_pb = _ReadModifyWriteRowRequestPB(
            table_name=table_name,
            row_key=row_key,
            rules=[
                _ReadModifyWriteRulePB(
                    family_name=column_family_id,
                    column_qualifier=column,
                    append_value=value,
                ),
            ],
        )

        # Create response_pb
        response_pb = object()

        # Patch the stub used by the API method.
        client._data_stub = stub = _FakeStub(response_pb)

        # Create expected_result.
        row_responses = []
        expected_result = object()

        def mock_parse_rmw_row_response(row_response):
            row_responses.append(row_response)
            return expected_result

        # Perform the method and check the result.
        with _Monkey(MUT, _parse_rmw_row_response=mock_parse_rmw_row_response):
            row.append_cell_value(column_family_id, column, value)
            result = row.commit()

        self.assertEqual(result, expected_result)
        self.assertEqual(stub.method_calls, [(
            'ReadModifyWriteRow',
            (request_pb, ),
            {},
        )])
        self.assertEqual(row_responses, [response_pb])
        self.assertEqual(row._rule_pb_list, [])
Ejemplo n.º 54
0
    def test_w_same_class(self):
        from google.cloud import operation as MUT
        from unit_tests._testing import _Monkey
        TYPE_URI = 'testing.google-cloud-python.com/testing'
        klass = object()
        type_url_map = {TYPE_URI: klass}

        with _Monkey(MUT, _TYPE_URL_MAP=type_url_map):
            self._callFUT(TYPE_URI, klass)

        self.assertEqual(type_url_map, {TYPE_URI: klass})
Ejemplo n.º 55
0
    def test_it(self):
        from google.cloud import _helpers as MUT
        from unit_tests._testing import _Monkey

        user_root = 'a'
        config_file = 'b'
        with _Monkey(MUT, _USER_ROOT=user_root,
                     _GCLOUD_CONFIG_FILE=config_file):
            result = self._callFUT()

        expected = os.path.join(user_root, '.config', config_file)
        self.assertEqual(result, expected)
Ejemplo n.º 56
0
    def test_w_conflict(self):
        from google.cloud import operation as MUT
        from unit_tests._testing import _Monkey
        TYPE_URI = 'testing.google-cloud-python.com/testing'
        klass, other = object(), object()
        type_url_map = {TYPE_URI: other}

        with _Monkey(MUT, _TYPE_URL_MAP=type_url_map):
            with self.assertRaises(ValueError):
                self._callFUT(TYPE_URI, klass)

        self.assertEqual(type_url_map, {TYPE_URI: other})
Ejemplo n.º 57
0
    def test_commit_too_many_mutations(self):
        from unit_tests._testing import _Monkey
        from google.cloud.bigtable import row as MUT

        row_key = b'row_key'
        table = object()
        row = self._makeOne(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):
            with self.assertRaises(ValueError):
                row.commit()