From 700c2fa95cd8714b70fcd484b207795298c50690 Mon Sep 17 00:00:00 2001 From: Renjie Cai Date: Mon, 1 Jul 2019 23:30:45 +0800 Subject: [PATCH] Feature/clone txn (#106) * add clone method to Txn * add test for rxn.clone() --- README.md | 2 +- etcd3/stateful/transaction.py | 21 ++++++++++++++++++--- tests/test_transaction_util.py | 10 ++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1d33c00..4895cf3 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ Notice: The authentication header through gRPC-JSON-Gateway only supported in [e **Install** ```bash -$ pip install etcd3-py +$ pip install --upgrade etcd3-py ``` **Sync Client** diff --git a/etcd3/stateful/transaction.py b/etcd3/stateful/transaction.py index 268f449..600f074 100644 --- a/etcd3/stateful/transaction.py +++ b/etcd3/stateful/transaction.py @@ -55,9 +55,10 @@ def __init__(self, client, compare=None, success=None, failure=None): :param failure: failure components of the transaction, default to [] """ self.client = client - self._compare = compare or [] - self._success = success or [] - self._failure = failure or [] + self._compare = list(compare or []) + self._success = list(success or []) + self._failure = list(failure or []) + self._committed = False def clear(self): # pragma: no cover """ @@ -267,6 +268,20 @@ def delete(key=None, range_end=None, prev_kv=False, prefix=None, all=None): """ return kv.delete_range(key=key, range_end=range_end, prev_kv=prev_kv, prefix=prefix, all=all, txn_obj=True) + def __copy__(self): + return Txn( + client=self.client, + compare=self._compare[:], + success=self._success[:], + failure=self._failure[:] + ) + + def clone(self): + """ + :return: Txn + """ + return self.__copy__() + class TxnCompareOp(object): """ diff --git a/tests/test_transaction_util.py b/tests/test_transaction_util.py index 1216d12..b25f610 100644 --- a/tests/test_transaction_util.py +++ b/tests/test_transaction_util.py @@ -110,3 +110,13 @@ def test_transaction(client): txn = client.Txn() r = txn.compare(txn.key('foo').lease == ID).commit() assert r.succeeded + + +def test_txn_clone(client): + txn0 = client.Txn() + txn0.If(txn0.key('foo').value < b'1') + txn1 = txn0.clone() + assert id(txn0._compare) != id(txn1._compare) + txn0.Then(txn0.range('foo')) + assert len(txn0._success) == 1 + assert len(txn1._success) == 0