diff --git a/gcloud/datastore/test_transaction.py b/gcloud/datastore/test_transaction.py index 58cdf18e817a..ead71196eb39 100644 --- a/gcloud/datastore/test_transaction.py +++ b/gcloud/datastore/test_transaction.py @@ -65,6 +65,31 @@ def test_ctor_with_env(self): self.assertEqual(xact.dataset_id, DATASET_ID) self.assertEqual(xact.connection, CONNECTION) + def test_current(self): + from gcloud.datastore.test_api import _NoCommitBatch + _DATASET = 'DATASET' + connection = _Connection() + xact1 = self._makeOne(_DATASET, connection) + xact2 = self._makeOne(_DATASET, connection) + self.assertTrue(xact1.current() is None) + self.assertTrue(xact2.current() is None) + with xact1: + self.assertTrue(xact1.current() is xact1) + self.assertTrue(xact2.current() is xact1) + with _NoCommitBatch(_DATASET, _Connection): + self.assertTrue(xact1.current() is None) + self.assertTrue(xact2.current() is None) + with xact2: + self.assertTrue(xact1.current() is xact2) + self.assertTrue(xact2.current() is xact2) + with _NoCommitBatch(_DATASET, _Connection): + self.assertTrue(xact1.current() is None) + self.assertTrue(xact2.current() is None) + self.assertTrue(xact1.current() is xact1) + self.assertTrue(xact2.current() is xact1) + self.assertTrue(xact1.current() is None) + self.assertTrue(xact2.current() is None) + def test_begin(self): _DATASET = 'DATASET' connection = _Connection(234) diff --git a/gcloud/datastore/transaction.py b/gcloud/datastore/transaction.py index 0f1db7ff7bdf..8378a4f89bb7 100644 --- a/gcloud/datastore/transaction.py +++ b/gcloud/datastore/transaction.py @@ -110,6 +110,19 @@ def id(self): """ return self._id + @staticmethod + def current(): + """Return the topmost transaction. + + .. note:: if the topmost element on the stack is not a transaction, + returns None. + + :rtype: :class:`gcloud.datastore.transaction.Transaction` or None + """ + top = Batch.current() + if isinstance(top, Transaction): + return top + def begin(self): """Begins a transaction.