Debian Codegraph @

neutron_lib/tests/unit/db/test_api.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 from unittest import mock
15
16 from oslo_db import exception as db_exc
17 import osprofiler
18 import sqlalchemy
19 from sqlalchemy.orm import exc
20 import testtools
21
22 from neutron_lib.db import api as db_api
23 from neutron_lib import exceptions
24 from neutron_lib import fixture
25 from neutron_lib.tests import _base
26
27
28 class TestExceptionToRetryContextManager(_base.BaseTestCase):
29
30 def test_translates_single_exception(self):
31 with testtools.ExpectedException(db_exc.RetryRequest):
32 with db_api.exc_to_retry(ValueError):
33 raise ValueError()
34
35 def test_translates_multiple_exception_types(self):
36 with testtools.ExpectedException(db_exc.RetryRequest):
37 with db_api.exc_to_retry((ValueError, TypeError)):
38 raise TypeError()
39
40 def test_translates_DBerror_inner_exception(self):
41 with testtools.ExpectedException(db_exc.RetryRequest):
42 with db_api.exc_to_retry(ValueError):
43 raise db_exc.DBError(ValueError())
44
45 def test_passes_other_exceptions(self):
46 with testtools.ExpectedException(ValueError):
47 with db_api.exc_to_retry(TypeError):
48 raise ValueError()
49
50 def test_inner_exception_preserved_in_retryrequest(self):
51 try:
52 vexc = ValueError('test')
53 with db_api.exc_to_retry(ValueError):
54 raise vexc
55 except db_exc.RetryRequest as e:
56 self.assertEqual(vexc, e.inner_exc)
57
58 def test_retries_on_multi_exception_containing_target(self):
59 with testtools.ExpectedException(db_exc.RetryRequest):
60 with db_api.exc_to_retry(ValueError):
61 e = exceptions.MultipleExceptions([ValueError(), TypeError()])
62 raise e
63
64
65 class TestDeadLockDecorator(_base.BaseTestCase):
66
67 @db_api.retry_db_errors
68 def _decorated_function(self, fail_count, exc_to_raise):
69 self.fail_count = getattr(self, 'fail_count', fail_count + 1) - 1
70 if self.fail_count:
71 raise exc_to_raise
72
73 def test_regular_exception_excluded(self):
74 with testtools.ExpectedException(ValueError):
75 self._decorated_function(1, ValueError)
76
77 def test_staledata_error_caught(self):
78 e = exc.StaleDataError()
79 self.assertIsNone(self._decorated_function(1, e))
80
81 def test_dbconnection_error_caught(self):
82 e = db_exc.DBConnectionError()
83 self.assertIsNone(self._decorated_function(1, e))
84
85 def test_multi_exception_contains_retry(self):
86 e = exceptions.MultipleExceptions(
87 [ValueError(), db_exc.RetryRequest(TypeError())])
88 self.assertIsNone(self._decorated_function(1, e))
89
90 def test_multi_exception_contains_deadlock(self):
91 e = exceptions.MultipleExceptions([ValueError(), db_exc.DBDeadlock()])
92 self.assertIsNone(self._decorated_function(1, e))
93
94 def test_multi_nested_exception_contains_deadlock(self):
95 i = exceptions.MultipleExceptions([ValueError(), db_exc.DBDeadlock()])
96 e = exceptions.MultipleExceptions([ValueError(), i])
97 self.assertIsNone(self._decorated_function(1, e))
98
99 def test_multi_exception_raised_on_exceed(self):
100 # limit retries so this doesn't take 40 seconds
101 retry_fixture = fixture.DBRetryErrorsFixture(max_retries=2)
102 retry_fixture.setUp()
103 e = exceptions.MultipleExceptions([ValueError(), db_exc.DBDeadlock()])
104 with testtools.ExpectedException(exceptions.MultipleExceptions):
105 self._decorated_function(db_api.MAX_RETRIES + 1, e)
106 retry_fixture.cleanUp()
107
108 def test_mysql_savepoint_error(self):
109 e = db_exc.DBError("(pymysql.err.InternalError) (1305, 'SAVEPOINT "
110 "sa_savepoint_1 does not exist')")
111 self.assertIsNone(self._decorated_function(1, e))
112
113 @db_api.retry_if_session_inactive('alt_context')
114 def _alt_context_function(self, alt_context, *args, **kwargs):
115 return self._decorated_function(*args, **kwargs)
116
117 @db_api.retry_if_session_inactive()
118 def _context_function(self, context, list_arg, dict_arg,
119 fail_count, exc_to_raise):
120 list_arg.append(1)
121 dict_arg[max(dict_arg.keys()) + 1] = True
122 self.fail_count = getattr(self, 'fail_count', fail_count + 1) - 1
123 if self.fail_count:
124 raise exc_to_raise
125 return list_arg, dict_arg
126
127 def test_stacked_retries_dont_explode_retry_count(self):
128 context = mock.Mock()
129 context.session.is_active = False
130 e = db_exc.DBConnectionError()
131 mock.patch('time.sleep').start()
132 with testtools.ExpectedException(db_exc.DBConnectionError):
133 # after 20 failures, the inner retry should give up and
134 # the exception should be tagged to prevent the outer retry
135 self._alt_context_function(context, db_api.MAX_RETRIES + 1, e)
136
137 def _test_retry_time_cost(self, exc_to_raise):
138 worst_case = [0.5, 1, 2, 4, 8,
139 10, 10, 10, 10, 10,
140 10, 10, 10, 10, 10,
141 10, 10, 10, 10, 10]
142
143 class FakeTime:
144 def __init__(self):
145 self.counter = 0
146
147 def sleep(self, t):
148 self.counter += t
149
150 fake_timer = FakeTime()
151
152 def fake_sleep(t):
153 fake_timer.sleep(t)
154
155 e = exc_to_raise()
156 mock.patch('time.sleep', side_effect=fake_sleep).start()
157 with testtools.ExpectedException(exc_to_raise):
158 self._decorated_function(db_api.MAX_RETRIES + 1, e)
159 if exc_to_raise == db_exc.DBDeadlock:
160 self.assertEqual(True, (fake_timer.counter <= sum(worst_case)))
161 else:
162 self.assertGreaterEqual(sum(worst_case), fake_timer.counter)
163
164 def test_all_deadlock_time_elapsed(self):
165 self._test_retry_time_cost(db_exc.DBDeadlock)
166
167 def test_not_deadlock_time_elapsed(self):
168 self._test_retry_time_cost(db_exc.DBConnectionError)
169
170 def test_retry_if_session_inactive_args_not_mutated_after_retries(self):
171 context = mock.Mock()
172 context.session.is_active = False
173 list_arg = [1, 2, 3, 4]
174 dict_arg = {1: 'a', 2: 'b'}
175 la, da = self._context_function(context, list_arg, dict_arg,
176 5, db_exc.DBDeadlock())
177 # even though we had 5 failures the list and dict should only
178 # be mutated once
179 self.assertEqual(5, len(la))
180 self.assertEqual(3, len(da))
181
182 def test_retry_if_session_inactive_kwargs_not_mutated_after_retries(self):
183 context = mock.Mock()
184 context.session.is_active = False
185 list_arg = [1, 2, 3, 4]
186 dict_arg = {1: 'a', 2: 'b'}
187 la, da = self._context_function(context, list_arg=list_arg,
188 dict_arg=dict_arg,
189 fail_count=5,
190 exc_to_raise=db_exc.DBDeadlock())
191 # even though we had 5 failures the list and dict should only
192 # be mutated once
193 self.assertEqual(5, len(la))
194 self.assertEqual(3, len(da))
195
196 def test_retry_if_session_inactive_no_retry_in_active_session(self):
197 context = mock.Mock()
198 context.session.is_active = True
199 with testtools.ExpectedException(db_exc.DBDeadlock):
200 # retry decorator should have no effect in an active session
201 self._context_function(context, [], {1: 2},
202 fail_count=1,
203 exc_to_raise=db_exc.DBDeadlock())
204
205
206 class TestDBProfiler(_base.BaseTestCase):
207
208 @mock.patch.object(osprofiler.opts, 'is_trace_enabled',
209 return_value=True)
210 @mock.patch.object(osprofiler.opts, 'is_db_trace_enabled',
211 return_value=True)
212 def test_set_hook(self, _mock_dbt, _mock_t):
213 with mock.patch.object(
214 osprofiler.sqlalchemy, 'add_tracing') as add_tracing:
215 engine_mock = mock.Mock()
216 db_api._set_hook(engine_mock)
217 add_tracing.assert_called_once_with(
218 sqlalchemy, mock.ANY, "neutron.db")