|
| 1 | +# Copyright 2024 Google LLC All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from google.cloud.spanner_v1 import ( |
| 16 | + BatchCreateSessionsRequest, |
| 17 | + BeginTransactionRequest, |
| 18 | + CommitRequest, |
| 19 | +) |
| 20 | +from google.cloud.spanner_v1.testing.mock_spanner import SpannerServicer |
| 21 | +from google.cloud.spanner_v1.transaction import Transaction |
| 22 | +from tests.mockserver_tests.mock_server_test_base import ( |
| 23 | + MockServerTestBase, |
| 24 | + add_error, |
| 25 | + aborted_status, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +class TestAbortedTransaction(MockServerTestBase): |
| 30 | + def test_run_in_transaction_commit_aborted(self): |
| 31 | + # Add an Aborted error for the Commit method on the mock server. |
| 32 | + add_error(SpannerServicer.Commit.__name__, aborted_status()) |
| 33 | + # Run a transaction. The Commit method will return Aborted the first |
| 34 | + # time that the transaction tries to commit. It will then be retried |
| 35 | + # and succeed. |
| 36 | + self.database.run_in_transaction(_insert_mutations) |
| 37 | + |
| 38 | + # Verify that the transaction was retried. |
| 39 | + requests = self.spanner_service.requests |
| 40 | + self.assertEqual(5, len(requests), msg=requests) |
| 41 | + self.assertTrue(isinstance(requests[0], BatchCreateSessionsRequest)) |
| 42 | + self.assertTrue(isinstance(requests[1], BeginTransactionRequest)) |
| 43 | + self.assertTrue(isinstance(requests[2], CommitRequest)) |
| 44 | + # The transaction is aborted and retried. |
| 45 | + self.assertTrue(isinstance(requests[3], BeginTransactionRequest)) |
| 46 | + self.assertTrue(isinstance(requests[4], CommitRequest)) |
| 47 | + |
| 48 | + |
| 49 | +def _insert_mutations(transaction: Transaction): |
| 50 | + transaction.insert("my_table", ["col1", "col2"], ["value1", "value2"]) |
0 commit comments