Exemple #1
0
    def test_begin_transaction(self, mock_create_stub):
        # Mock gRPC layer
        grpc_stub = mock.Mock()
        mock_create_stub.return_value = grpc_stub

        client = spanner_v1.SpannerClient()

        # Mock request
        session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]',
                                      '[SESSION]')
        options_ = {}

        # Mock response
        id_ = b'27'
        expected_response = {'id': id_}
        expected_response = transaction_pb2.Transaction(**expected_response)
        grpc_stub.BeginTransaction.return_value = expected_response

        response = client.begin_transaction(session, options_)
        self.assertEqual(expected_response, response)

        grpc_stub.BeginTransaction.assert_called_once()
        args, kwargs = grpc_stub.BeginTransaction.call_args
        self.assertEqual(len(args), 2)
        self.assertEqual(len(kwargs), 1)
        self.assertIn('metadata', kwargs)
        actual_request = args[0]

        expected_request = spanner_pb2.BeginTransactionRequest(
            session=session, options=options_)
        self.assertEqual(expected_request, actual_request)
Exemple #2
0
    def test_begin_transaction(self):
        # Setup Expected Response
        id_ = b"27"
        expected_response = {"id": id_}
        expected_response = transaction_pb2.Transaction(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = spanner_v1.SpannerClient()

        # Setup Request
        session = client.session_path("[PROJECT]", "[INSTANCE]", "[DATABASE]",
                                      "[SESSION]")
        options_ = {}

        response = client.begin_transaction(session, options_)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = spanner_pb2.BeginTransactionRequest(
            session=session, options=options_)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Exemple #3
0
    def begin_transaction(self, session, options_, options=None):
        """
        Begins a new transaction. This step can often be skipped:
        ``Read``, ``ExecuteSql`` and
        ``Commit`` can begin a new transaction as a
        side-effect.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> options_ = {}
            >>>
            >>> response = client.begin_transaction(session, options_)

        Args:
            session (str): Required. The session in which the transaction runs.
            options_ (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Required. Options for the new transaction.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Transaction` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.BeginTransactionRequest(
            session=session, options=options_)
        return self._begin_transaction(request, options)
    def begin_transaction(self,
                          session,
                          options_,
                          retry=google.api_core.gapic_v1.method.DEFAULT,
                          timeout=google.api_core.gapic_v1.method.DEFAULT,
                          metadata=None):
        """
        Begins a new transaction. This step can often be skipped:
        ``Read``, ``ExecuteSql`` and
        ``Commit`` can begin a new transaction as a
        side-effect.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> options_ = {}
            >>>
            >>> response = client.begin_transaction(session, options_)

        Args:
            session (str): Required. The session in which the transaction runs.
            options_ (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Required. Options for the new transaction.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Transaction` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        request = spanner_pb2.BeginTransactionRequest(
            session=session,
            options=options_,
        )
        return self._begin_transaction(
            request, metadata=metadata, retry=retry, timeout=timeout)
def _transaction(stub):
    """Probe to test BeginTransaction, Commit and Rollback grpc from Spanner stub.

  Args:
    stub: An object of SpannerStub.
  """
    _transaction_tracer = initialize_tracer()
    with _transaction_tracer.span(name='_transaction') as root_span:
        root_span.add_annotation('endpoint info available',
                                 endpoint=_SPANNER_TARGET)
        session = None
        try:
            with _transaction_tracer.span(name='stub.CreateSession'):
                session = stub.CreateSession(
                    spanner_pb2.CreateSessionRequest(database=_DATABASE))

            txn_options = transaction_pb2.TransactionOptions(
                read_write=transaction_pb2.TransactionOptions.ReadWrite())
            txn_request = spanner_pb2.BeginTransactionRequest(
                session=session.name,
                options=txn_options,
            )

            # Probing BeginTransaction call
            with _transaction_tracer.span(name='stub.BeginTransaction'):
                txn = stub.BeginTransaction(txn_request)

            # Probing Commit call
            commit_request = spanner_pb2.CommitRequest(session=session.name,
                                                       transaction_id=txn.id)
            with _transaction_tracer.span(name='stub.Commit'):
                stub.Commit(commit_request)

            # Probing Rollback call
            txn = stub.BeginTransaction(txn_request)
            rollback_request = spanner_pb2.RollbackRequest(
                session=session.name, transaction_id=txn.id)
            with _transaction_tracer.span(name='stub.Rollback'):
                stub.Rollback(rollback_request)

        finally:
            if session is not None:
                with _transaction_tracer.span(name='stub.DeleteSession'):
                    stub.DeleteSession(
                        spanner_pb2.DeleteSessionRequest(name=session.name))
Exemple #6
0
    def test_begin_transaction(self):
        # Setup Expected Response
        id_ = b'27'
        expected_response = {'id': id_}
        expected_response = transaction_pb2.Transaction(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = spanner_v1.SpannerClient(channel=channel)

        # Setup Request
        session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]',
                                      '[SESSION]')
        options_ = {}

        response = client.begin_transaction(session, options_)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = spanner_pb2.BeginTransactionRequest(
            session=session, options=options_)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request