-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_transaction.py
317 lines (243 loc) · 10.3 KB
/
test_transaction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
#disable: accessing protected members, too many methods
#pylint: disable=W0212,R0904
import sys
import unittest
from hamcrest import assert_that
from hamcrest import is_
from hamcrest import calling
from hamcrest import raises
from hamcrest import contains
from hamcrest import has_property
import fudge
from nti.testing.matchers import is_true
from nti.testing.matchers import is_false
from ..interfaces import CommitFailedError
from ..interfaces import AbortFailedError
from ..interfaces import ForeignTransactionError
from ..transactions import do
from ..transactions import do_near_end
from ..transactions import _do_commit
from ..transactions import TransactionLoop
import transaction
from transaction.interfaces import TransientError
from transaction.interfaces import NoTransaction
from transaction.interfaces import AlreadyInTransaction
class TestCommit(unittest.TestCase):
class RaisingCommit(object):
def __init__(self, t=Exception):
self.t = t
def nti_commit(self):
if self.t:
raise self.t
def test_commit_raises_type_error_raises_commit_failed(self):
assert_that(calling(_do_commit).with_args(self.RaisingCommit(TypeError),
'', 0),
raises(CommitFailedError))
def test_commit_raises_type_error_raises_commit_failed_good_message(self):
assert_that(calling(_do_commit).with_args(
self.RaisingCommit(TypeError("A custom message")),
'', 0),
raises(CommitFailedError, "A custom message"))
@fudge.patch('nti.transactions.transactions.logger.exception')
def test_commit_raises_assertion_error(self, fake_logger):
fake_logger.expects_call()
assert_that(calling(_do_commit).with_args(self.RaisingCommit(AssertionError),
'', 0),
raises(AssertionError))
@fudge.patch('nti.transactions.transactions.logger.exception')
def test_commit_raises_value_error(self, fake_logger):
fake_logger.expects_call()
assert_that(calling(_do_commit).with_args(self.RaisingCommit(ValueError),
'', 0),
raises(ValueError))
@fudge.patch('nti.transactions.transactions.logger.exception')
def test_commit_raises_custom_error(self, fake_logger):
fake_logger.expects_call()
class MyException(Exception):
pass
try:
raise MyException()
except MyException:
assert_that(calling(_do_commit).with_args(self.RaisingCommit(ValueError),
'', 0),
raises(MyException))
@fudge.patch('nti.transactions.transactions.logger.warn')
def test_commit_clean_but_long(self, fake_logger):
fake_logger.expects_call()
_do_commit(self.RaisingCommit(None), '', 0)
class TestLoop(unittest.TestCase):
def setUp(self):
try:
transaction.abort()
except NoTransaction:
pass
def test_trivial(self):
result = TransactionLoop(lambda a: a, retries=1, long_commit_duration=1, sleep=1)(1)
assert_that(result, is_(1))
def test_explicit(self):
assert_that(transaction.manager, has_property('explicit', is_false()))
def handler():
assert_that(transaction.manager, has_property('explicit', is_true()))
return 42
result = TransactionLoop(handler)()
assert_that(result, is_(42))
def test_explicit_begin(self):
def handler():
transaction.begin()
assert_that(calling(TransactionLoop(handler)), raises(AlreadyInTransaction))
def test_explicit_end(self):
def handler():
transaction.abort()
assert_that(calling(TransactionLoop(handler)), raises(NoTransaction))
def test_explicit_foreign(self):
def handler():
transaction.abort()
transaction.begin()
assert_that(calling(TransactionLoop(handler)), raises(ForeignTransactionError))
def test_setup_teardown(self):
class Loop(TransactionLoop):
setupcalled = teardowncalled = False
def setUp(self):
assert_that(transaction.manager, has_property('explicit', is_true()))
self.setupcalled = True
def tearDown(self):
self.teardowncalled = True
def handler():
raise Exception
loop = Loop(handler)
assert_that(calling(loop), raises(Exception))
assert_that(loop, has_property('setupcalled', is_true()))
assert_that(loop, has_property('teardowncalled', is_true()))
def test_retriable(self, loop_class=TransactionLoop, exc_type=TransientError):
calls = []
def handler():
# exc_info should be clear on entry.
assert_that(sys.exc_info(), is_((None, None, None)))
if not calls:
calls.append(1)
raise exc_type()
return "hi"
loop = loop_class(handler)
result = loop()
assert_that(result, is_("hi"))
assert_that(calls, is_([1]))
def test_custom_retriable(self):
class Loop(TransactionLoop):
_retryable_errors = ((Exception, None),)
self.test_retriable(Loop, AssertionError)
def test_retriable_gives_up(self):
def handler():
raise TransientError()
loop = TransactionLoop(handler, sleep=0.01, retries=1)
assert_that(calling(loop), raises(TransientError))
def test_non_retryable(self):
class MyError(Exception):
pass
def handler():
raise MyError()
loop = TransactionLoop(handler, sleep=0.01, retries=100000000)
assert_that(calling(loop), raises(MyError))
def test_isRetryableError_exception(self):
# If the transaction.isRetryableError() raises, for some reason,
# we still process our list
class MyError(object):
pass
class Loop(TransactionLoop):
_retryable_errors = ((MyError, None),)
loop = Loop(None)
loop._retryable(None, (None, MyError(), None))
@fudge.patch('transaction._manager.TransactionManager.begin',
'transaction._manager.TransactionManager.get')
def test_note(self, fake_begin, fake_get):
fake_tx = fudge.Fake()
(fake_tx
.expects('note').with_args(u'Hi')
.expects('nti_abort')
.provides('isDoomed').returns(True))
fake_begin.expects_call().returns(fake_tx)
fake_get.expects_call().returns(fake_tx)
class Loop(TransactionLoop):
def describe_transaction(self, *args, **kwargs):
return u"Hi"
result = Loop(lambda: 42)()
assert_that(result, is_(42))
@fudge.patch('transaction._manager.TransactionManager.begin',
'transaction._manager.TransactionManager.get')
def test_abort_no_side_effect(self, fake_begin, fake_get):
fake_tx = fudge.Fake()
fake_tx.expects('nti_abort')
fake_begin.expects_call().returns(fake_tx)
fake_get.expects_call().returns(fake_tx)
class Loop(TransactionLoop):
side_effect_free = True
result = Loop(lambda: 42)()
assert_that(result, is_(42))
@fudge.patch('transaction._transaction.Transaction.nti_abort')
def test_abort_doomed(self, fake_abort):
fake_abort.expects_call()
def handler():
assert_that(transaction.manager.explicit, is_true())
transaction.get().doom()
return 42
result = TransactionLoop(handler)()
assert_that(result, is_(42))
@fudge.patch('transaction._manager.TransactionManager.begin',
'transaction._manager.TransactionManager.get')
def test_abort_veto(self, fake_begin, fake_get):
fake_tx = fudge.Fake()
fake_tx.expects('nti_abort')
fake_tx.provides('isDoomed').returns(False)
fake_begin.expects_call().returns(fake_tx)
fake_get.expects_call().returns(fake_tx)
class Loop(TransactionLoop):
def should_veto_commit(self, result, *args, **kwargs):
assert_that(result, is_(42))
return True
result = Loop(lambda: 42)()
assert_that(result, is_(42))
@fudge.patch('transaction._manager.TransactionManager.begin',
'nti.transactions.transactions.print_exception')
def test_abort_systemexit(self, fake_begin, fake_print):
fake_tx = fudge.Fake()
fake_tx.expects('abort').raises(ValueError)
fake_tx.provides('isDoomed').returns(False)
fake_begin.expects_call().returns(fake_tx)
fake_print.is_callable()
def handler():
raise SystemExit()
loop = TransactionLoop(handler)
try:
loop()
self.fail("Should raise SystemExit")
except SystemExit:
pass
@fudge.patch('transaction._manager.TransactionManager.begin',
'nti.transactions.transactions.logger.exception',
'nti.transactions.transactions.logger.warning')
def test_abort_exception_raises(self, fake_begin,
fake_logger, fake_format):
# begin() returns an object without abort(), which we catch.
fake_begin.expects_call().returns_fake()
# Likewise for the things we try to do to log it
fake_logger.expects_call().raises(ValueError)
fake_format.expects_call().raises(ValueError)
def handler():
raise Exception()
loop = TransactionLoop(handler)
assert_that(calling(loop), raises(AbortFailedError))
class TestDataManagers(unittest.TestCase):
def test_data_manager_sorting(self):
results = []
def test_call(x):
results.append(x)
# The managers will execute in order added (since identical),
# except for the one that requests to go last.
do(call=test_call, args=(0,))
do(call=test_call, args=(1,))
do_near_end(call=test_call, args=(10,))
do(call=test_call, args=(2,))
transaction.commit()
assert_that(results, contains(0, 1, 2, 10))