| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
from unittest import mock |
| 17 |
from urllib import parse |
| 18 |
|
| 19 |
import fixtures |
| 20 |
import sqlalchemy |
| 21 |
from sqlalchemy import Boolean, Index, Integer, DateTime, String |
| 22 |
from sqlalchemy import MetaData, Table, Column |
| 23 |
from sqlalchemy import ForeignKey, ForeignKeyConstraint |
| 24 |
from sqlalchemy.dialects.postgresql import psycopg2 |
| 25 |
from sqlalchemy.exc import OperationalError |
| 26 |
from sqlalchemy.ext.hybrid import hybrid_property |
| 27 |
from sqlalchemy.orm import column_property |
| 28 |
from sqlalchemy.orm import declarative_base |
| 29 |
from sqlalchemy.orm import registry |
| 30 |
from sqlalchemy.orm import Session |
| 31 |
from sqlalchemy import sql |
| 32 |
from sqlalchemy.sql.expression import cast |
| 33 |
from sqlalchemy.sql import select |
| 34 |
from sqlalchemy.types import UserDefinedType |
| 35 |
|
| 36 |
from oslo_db import exception |
| 37 |
from oslo_db.sqlalchemy import enginefacade |
| 38 |
from oslo_db.sqlalchemy import models |
| 39 |
from oslo_db.sqlalchemy import provision |
| 40 |
from oslo_db.sqlalchemy import utils |
| 41 |
from oslo_db.tests import base as test_base |
| 42 |
from oslo_db.tests.sqlalchemy import base as db_test_base |
| 43 |
|
| 44 |
Base = declarative_base() |
| 45 |
|
| 46 |
|
| 47 |
class TestSanitizeDbUrl(test_base.BaseTestCase): |
| 48 |
|
| 49 |
def test_url_with_cred(self): |
| 50 |
db_url = 'myproto://johndoe:secret@localhost/myschema' |
| 51 |
expected = 'myproto://****:****@localhost/myschema' |
| 52 |
actual = utils.sanitize_db_url(db_url) |
| 53 |
self.assertEqual(expected, actual) |
| 54 |
|
| 55 |
def test_url_with_no_cred(self): |
| 56 |
db_url = 'sqlite:///mysqlitefile' |
| 57 |
actual = utils.sanitize_db_url(db_url) |
| 58 |
self.assertEqual(db_url, actual) |
| 59 |
|
| 60 |
|
| 61 |
class CustomType(UserDefinedType): |
| 62 |
"""Dummy column type for testing unsupported types.""" |
| 63 |
def get_col_spec(self): |
| 64 |
return "CustomType" |
| 65 |
|
| 66 |
|
| 67 |
class FakeTable(Base): |
| 68 |
__tablename__ = 'fake_table' |
| 69 |
|
| 70 |
user_id = Column(String(50), primary_key=True) |
| 71 |
project_id = Column(String(50)) |
| 72 |
snapshot_id = Column(String(50)) |
| 73 |
updated_at = Column(DateTime, nullable=True) |
| 74 |
enabled = Column(Boolean, default=True) |
| 75 |
|
| 76 |
_some_hybrid = column_property(project_id + snapshot_id) |
| 77 |
|
| 78 |
@hybrid_property |
| 79 |
def some_hybrid(self): |
| 80 |
raise NotImplementedError() |
| 81 |
|
| 82 |
@some_hybrid.expression |
| 83 |
def some_hybrid(cls): |
| 84 |
return cls._some_hybrid |
| 85 |
|
| 86 |
def foo(self): |
| 87 |
pass |
| 88 |
|
| 89 |
|
| 90 |
class FakeTableJoinedInh(FakeTable): |
| 91 |
__tablename__ = 'fake_table_inh' |
| 92 |
|
| 93 |
id = Column(String(50), ForeignKey('fake_table.user_id'), primary_key=True) |
| 94 |
|
| 95 |
|
| 96 |
class FakeTableSingleInh(FakeTable): |
| 97 |
__mapper_args__ = {'polymorphic_identity': 'foo'} |
| 98 |
|
| 99 |
|
| 100 |
class FakeTableWithMultipleKeys(Base): |
| 101 |
__tablename__ = 'fake_table_multiple_keys' |
| 102 |
|
| 103 |
key1 = Column(String(50), primary_key=True) |
| 104 |
key2 = Column(String(50), primary_key=True) |
| 105 |
key3 = Column(String(50)) |
| 106 |
|
| 107 |
|
| 108 |
class FakeTableWithIndexes(Base): |
| 109 |
__tablename__ = 'fake_table_unique_index' |
| 110 |
|
| 111 |
id = Column(String(50), primary_key=True) |
| 112 |
key1 = Column(String(50)) |
| 113 |
key2 = Column(String(50)) |
| 114 |
key3 = Column(String(50)) |
| 115 |
|
| 116 |
__table_args__ = ( |
| 117 |
Index('idx_unique', 'key1', 'key2', unique=True), |
| 118 |
Index('idx_unique', 'key1', 'key3', unique=False), |
| 119 |
) |
| 120 |
|
| 121 |
|
| 122 |
class FakeTableClassicalyMapped: |
| 123 |
pass |
| 124 |
|
| 125 |
|
| 126 |
fake_table = Table( |
| 127 |
'fake_table_classically_mapped', |
| 128 |
Base.metadata, |
| 129 |
Column('id', Integer, primary_key=True), |
| 130 |
Column('key', String(50)) |
| 131 |
) |
| 132 |
|
| 133 |
reg = registry() |
| 134 |
reg.map_imperatively(FakeTableClassicalyMapped, fake_table) |
| 135 |
|
| 136 |
|
| 137 |
class FakeModel: |
| 138 |
def __init__(self, values): |
| 139 |
self.values = values |
| 140 |
|
| 141 |
def __getattr__(self, name): |
| 142 |
try: |
| 143 |
value = self.values[name] |
| 144 |
except KeyError: |
| 145 |
raise AttributeError(name) |
| 146 |
return value |
| 147 |
|
| 148 |
def __getitem__(self, key): |
| 149 |
if key in self.values: |
| 150 |
return self.values[key] |
| 151 |
else: |
| 152 |
raise NotImplementedError() |
| 153 |
|
| 154 |
def __repr__(self): |
| 155 |
return '<FakeModel: %s>' % self.values |
| 156 |
|
| 157 |
|
| 158 |
class TestPaginateQuery(test_base.BaseTestCase): |
| 159 |
def setUp(self): |
| 160 |
super().setUp() |
| 161 |
|
| 162 |
self.query = mock.Mock() |
| 163 |
self.mock_asc = self.useFixture( |
| 164 |
fixtures.MockPatchObject(sqlalchemy, 'asc')).mock |
| 165 |
self.mock_desc = self.useFixture( |
| 166 |
fixtures.MockPatchObject(sqlalchemy, 'desc')).mock |
| 167 |
|
| 168 |
self.marker = FakeTable(user_id='user', |
| 169 |
project_id='p', |
| 170 |
snapshot_id='s', |
| 171 |
updated_at=None) |
| 172 |
self.model = FakeTable |
| 173 |
|
| 174 |
def test_paginate_query_no_pagination_no_sort_dirs(self): |
| 175 |
self.query.order_by.return_value = self.query |
| 176 |
self.mock_asc.side_effect = [ |
| 177 |
'asc_3', 'asc_2', 'asc_1' |
| 178 |
] |
| 179 |
|
| 180 |
utils.paginate_query(self.query, self.model, 5, |
| 181 |
['user_id', 'project_id', 'snapshot_id']) |
| 182 |
|
| 183 |
self.mock_asc.assert_has_calls([ |
| 184 |
mock.call(self.model.user_id), |
| 185 |
mock.call(self.model.project_id), |
| 186 |
mock.call(self.model.snapshot_id), |
| 187 |
]) |
| 188 |
self.query.order_by.assert_has_calls([ |
| 189 |
mock.call('asc_3'), |
| 190 |
mock.call('asc_2'), |
| 191 |
mock.call('asc_1'), |
| 192 |
]) |
| 193 |
self.query.limit.assert_called_once_with(5) |
| 194 |
|
| 195 |
def test_paginate_query_no_pagination(self): |
| 196 |
self.query.order_by.return_value = self.query |
| 197 |
self.mock_asc.side_effect = ['asc'] |
| 198 |
self.mock_desc.side_effect = ['desc'] |
| 199 |
|
| 200 |
utils.paginate_query(self.query, self.model, 5, |
| 201 |
['user_id', 'project_id'], |
| 202 |
sort_dirs=['asc', 'desc']) |
| 203 |
|
| 204 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 205 |
self.mock_desc.assert_called_once_with(self.model.project_id) |
| 206 |
self.query.order_by.assert_has_calls([ |
| 207 |
mock.call('asc'), |
| 208 |
mock.call('desc'), |
| 209 |
]) |
| 210 |
self.query.limit.assert_called_once_with(5) |
| 211 |
|
| 212 |
def test_invalid_sort_key_str(self): |
| 213 |
self.assertEqual("Sort key supplied is invalid: None", |
| 214 |
str(exception.InvalidSortKey())) |
| 215 |
self.assertEqual("Sort key supplied is invalid: lol", |
| 216 |
str(exception.InvalidSortKey("lol"))) |
| 217 |
|
| 218 |
def test_invalid_unicode_paramater_str(self): |
| 219 |
self.assertEqual( |
| 220 |
"Invalid Parameter: Encoding directive wasn't provided.", |
| 221 |
str(exception.DBInvalidUnicodeParameter())) |
| 222 |
|
| 223 |
def test_paginate_query_attribute_error(self): |
| 224 |
self.mock_asc.return_value = 'asc' |
| 225 |
|
| 226 |
self.assertRaises(exception.InvalidSortKey, |
| 227 |
utils.paginate_query, self.query, |
| 228 |
self.model, 5, ['user_id', 'non-existent key']) |
| 229 |
|
| 230 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 231 |
self.query.order_by.assert_called_once_with('asc') |
| 232 |
|
| 233 |
def test_paginate_query_attribute_error_invalid_sortkey(self): |
| 234 |
self.assertRaises(exception.InvalidSortKey, |
| 235 |
utils.paginate_query, self.query, |
| 236 |
self.model, 5, ['bad_user_id']) |
| 237 |
|
| 238 |
def test_paginate_query_attribute_error_invalid_sortkey_2(self): |
| 239 |
self.assertRaises(exception.InvalidSortKey, |
| 240 |
utils.paginate_query, self.query, |
| 241 |
self.model, 5, ['foo']) |
| 242 |
|
| 243 |
def test_paginate_query_attribute_error_invalid_sortkey_3(self): |
| 244 |
self.assertRaises(exception.InvalidSortKey, |
| 245 |
utils.paginate_query, self.query, |
| 246 |
self.model, 5, ['asc-nullinvalid']) |
| 247 |
|
| 248 |
def test_paginate_query_assertion_error(self): |
| 249 |
self.assertRaises(AssertionError, |
| 250 |
utils.paginate_query, self.query, |
| 251 |
self.model, 5, ['user_id'], |
| 252 |
marker=self.marker, |
| 253 |
sort_dir='asc', sort_dirs=['asc']) |
| 254 |
|
| 255 |
def test_paginate_query_assertion_error_2(self): |
| 256 |
self.assertRaises(AssertionError, |
| 257 |
utils.paginate_query, self.query, |
| 258 |
self.model, 5, ['user_id'], |
| 259 |
marker=self.marker, |
| 260 |
sort_dir=None, sort_dirs=['asc', 'desk']) |
| 261 |
|
| 262 |
@mock.patch.object(sqlalchemy.sql, 'and_') |
| 263 |
@mock.patch.object(sqlalchemy.sql, 'or_') |
| 264 |
def test_paginate_query(self, mock_or, mock_and): |
| 265 |
self.query.order_by.return_value = self.query |
| 266 |
self.query.filter.return_value = self.query |
| 267 |
self.mock_asc.return_value = 'asc_1' |
| 268 |
self.mock_desc.return_value = 'desc_1' |
| 269 |
mock_and.side_effect = ['some_crit', 'another_crit'] |
| 270 |
mock_or.return_value = 'some_f' |
| 271 |
|
| 272 |
utils.paginate_query(self.query, self.model, 5, |
| 273 |
['user_id', 'project_id'], |
| 274 |
marker=self.marker, |
| 275 |
sort_dirs=['asc', 'desc']) |
| 276 |
|
| 277 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 278 |
self.mock_desc.assert_called_once_with(self.model.project_id) |
| 279 |
self.query.order_by.assert_has_calls([ |
| 280 |
mock.call('asc_1'), |
| 281 |
mock.call('desc_1'), |
| 282 |
]) |
| 283 |
mock_and.assert_has_calls([ |
| 284 |
mock.call(mock.ANY), |
| 285 |
mock.call(mock.ANY, mock.ANY) |
| 286 |
]) |
| 287 |
mock_or.assert_called_once_with('some_crit', 'another_crit') |
| 288 |
self.query.filter.assert_called_once_with('some_f') |
| 289 |
self.query.limit.assert_called_once_with(5) |
| 290 |
|
| 291 |
@mock.patch.object(sqlalchemy.sql, 'and_') |
| 292 |
@mock.patch.object(sqlalchemy.sql, 'or_') |
| 293 |
def test_paginate_query_null(self, mock_or, mock_and): |
| 294 |
self.query.order_by.return_value = self.query |
| 295 |
self.query.filter.return_value = self.query |
| 296 |
self.mock_desc.side_effect = [ |
| 297 |
'asc_null_2', |
| 298 |
'desc_null_2', |
| 299 |
'desc_1', |
| 300 |
] |
| 301 |
self.mock_asc.side_effect = [ |
| 302 |
'asc_1' |
| 303 |
] |
| 304 |
mock_or.side_effect = [ |
| 305 |
'or_1', |
| 306 |
'or_2', |
| 307 |
'some_f', |
| 308 |
] |
| 309 |
mock_and.side_effect = [ |
| 310 |
'some_crit', |
| 311 |
'another_crit', |
| 312 |
] |
| 313 |
|
| 314 |
with mock.patch.object( |
| 315 |
self.model.user_id.comparator.expression, 'is_not' |
| 316 |
) as mock_is_not, \ |
| 317 |
mock.patch.object( |
| 318 |
self.model.user_id.comparator.expression, 'is_' |
| 319 |
) as mock_is_a, \ |
| 320 |
mock.patch.object( |
| 321 |
self.model.project_id.comparator.expression, 'is_' |
| 322 |
) as mock_is_b: |
| 323 |
mock_is_not.return_value = 'asc_null_1' |
| 324 |
mock_is_a.side_effect = [ |
| 325 |
'desc_null_filter_1', |
| 326 |
'desc_null_filter_2', |
| 327 |
] |
| 328 |
mock_is_b.side_effect = [ |
| 329 |
'desc_null_1', |
| 330 |
'asc_null_filter', |
| 331 |
] |
| 332 |
|
| 333 |
utils.paginate_query(self.query, self.model, 5, |
| 334 |
['user_id', 'project_id'], |
| 335 |
marker=self.marker, |
| 336 |
sort_dirs=[ |
| 337 |
'asc-nullslast', 'desc-nullsfirst']) |
| 338 |
|
| 339 |
mock_is_not.assert_called_once_with(None) |
| 340 |
mock_is_a.assert_has_calls([ |
| 341 |
mock.call(None), |
| 342 |
mock.call(None), |
| 343 |
]) |
| 344 |
mock_is_b.assert_has_calls([ |
| 345 |
mock.call(None), |
| 346 |
mock.call(None), |
| 347 |
]) |
| 348 |
|
| 349 |
self.mock_desc.assert_has_calls([ |
| 350 |
mock.call('asc_null_1'), |
| 351 |
mock.call('desc_null_1'), |
| 352 |
mock.call(self.model.project_id), |
| 353 |
]) |
| 354 |
self.mock_asc.assert_has_calls([ |
| 355 |
mock.call(self.model.user_id), |
| 356 |
]) |
| 357 |
mock_or.assert_has_calls([ |
| 358 |
mock.call(mock.ANY, 'desc_null_filter_2'), |
| 359 |
mock.call(mock.ANY, 'asc_null_filter'), |
| 360 |
mock.call('some_crit', 'another_crit'), |
| 361 |
]) |
| 362 |
mock_and.assert_has_calls([ |
| 363 |
mock.call('or_1'), |
| 364 |
mock.call(mock.ANY, 'or_2'), |
| 365 |
]) |
| 366 |
|
| 367 |
self.query.order_by.assert_has_calls([ |
| 368 |
mock.call('asc_null_2'), |
| 369 |
mock.call('asc_1'), |
| 370 |
mock.call('desc_null_2'), |
| 371 |
mock.call('desc_1'), |
| 372 |
]) |
| 373 |
self.query.filter.assert_called_once_with('some_f') |
| 374 |
self.query.limit.assert_called_once_with(5) |
| 375 |
|
| 376 |
@mock.patch.object(sqlalchemy.sql, 'and_') |
| 377 |
@mock.patch.object(sqlalchemy.sql, 'or_') |
| 378 |
def test_paginate_query_marker_null(self, mock_or, mock_and): |
| 379 |
|
| 380 |
self.mock_asc.side_effect = [ |
| 381 |
'asc_1' |
| 382 |
] |
| 383 |
self.mock_desc.side_effect = [ |
| 384 |
'asc_null_2', |
| 385 |
'desc_null_2', |
| 386 |
'desc_1', |
| 387 |
] |
| 388 |
self.query.order_by.return_value = self.query |
| 389 |
self.query.filter.return_value = self.query |
| 390 |
mock_and.return_value = 'some_crit' |
| 391 |
mock_or.side_effect = ['or_1', 'some_f'] |
| 392 |
|
| 393 |
with mock.patch.object( |
| 394 |
self.model.user_id.comparator.expression, 'is_not' |
| 395 |
) as mock_is_not, \ |
| 396 |
mock.patch.object( |
| 397 |
self.model.updated_at.comparator.expression, 'is_' |
| 398 |
) as mock_is_a, \ |
| 399 |
mock.patch.object( |
| 400 |
self.model.user_id.comparator.expression, 'is_' |
| 401 |
) as mock_is_b: |
| 402 |
|
| 403 |
mock_is_not.return_value = 'asc_null_1' |
| 404 |
mock_is_a.return_value = 'desc_null_1' |
| 405 |
mock_is_b.side_effect = ['asc_null_filter_1', 'asc_null_filter_2'] |
| 406 |
|
| 407 |
utils.paginate_query(self.query, self.model, 5, |
| 408 |
['user_id', 'updated_at'], |
| 409 |
marker=self.marker, |
| 410 |
sort_dirs=[ |
| 411 |
'asc-nullslast', 'desc-nullsfirst']) |
| 412 |
mock_is_not.assert_called_once_with(None) |
| 413 |
mock_is_a.assert_called_once_with(None) |
| 414 |
mock_is_b.assert_has_calls([mock.call(None), mock.call(None)]) |
| 415 |
|
| 416 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 417 |
self.mock_desc.assert_has_calls([ |
| 418 |
mock.call('asc_null_1'), |
| 419 |
mock.call('desc_null_1'), |
| 420 |
mock.call(self.model.updated_at), |
| 421 |
]) |
| 422 |
mock_and.assert_called_once_with('or_1') |
| 423 |
mock_or.assert_has_calls([ |
| 424 |
mock.call(mock.ANY, 'asc_null_filter_2'), |
| 425 |
mock.call('some_crit'), |
| 426 |
]) |
| 427 |
self.query.order_by.assert_has_calls([ |
| 428 |
mock.call('asc_null_2'), |
| 429 |
mock.call('asc_1'), |
| 430 |
mock.call('desc_null_2'), |
| 431 |
mock.call('desc_1'), |
| 432 |
]) |
| 433 |
self.query.filter.assert_called_once_with('some_f') |
| 434 |
self.query.limit.assert_called_once_with(5) |
| 435 |
|
| 436 |
@mock.patch.object(sqlalchemy.sql, 'and_') |
| 437 |
@mock.patch.object(sqlalchemy.sql, 'or_') |
| 438 |
def test_paginate_query_marker_null_with_two_primary_keys( |
| 439 |
self, mock_or, mock_and): |
| 440 |
self.mock_asc.return_value = 'asc_1' |
| 441 |
self.mock_desc.side_effect = [ |
| 442 |
'asc_null_2', |
| 443 |
'desc_null_2', |
| 444 |
'desc_1', |
| 445 |
'desc_null_4', |
| 446 |
'desc_4', |
| 447 |
] |
| 448 |
self.query.order_by.return_value = self.query |
| 449 |
mock_or.side_effect = [ |
| 450 |
'or_1', |
| 451 |
'or_2', |
| 452 |
'some_f', |
| 453 |
] |
| 454 |
mock_and.side_effect = [ |
| 455 |
'some_crit', |
| 456 |
'other_crit', |
| 457 |
] |
| 458 |
self.query.filter.return_value = self.query |
| 459 |
|
| 460 |
with mock.patch.object( |
| 461 |
self.model.user_id.comparator.expression, 'is_not' |
| 462 |
) as mock_is_not, \ |
| 463 |
mock.patch.object( |
| 464 |
self.model.updated_at.comparator.expression, 'is_' |
| 465 |
) as mock_is_a, \ |
| 466 |
mock.patch.object( |
| 467 |
self.model.user_id.comparator.expression, 'is_' |
| 468 |
) as mock_is_b, \ |
| 469 |
mock.patch.object( |
| 470 |
self.model.project_id.comparator.expression, 'is_' |
| 471 |
) as mock_is_c: |
| 472 |
|
| 473 |
mock_is_not.return_value = 'asc_null_1' |
| 474 |
mock_is_a.return_value = 'desc_null_1' |
| 475 |
mock_is_b.side_effect = ['asc_null_filter_1', 'asc_null_filter_2'] |
| 476 |
mock_is_c.side_effect = ['desc_null_3', 'desc_null_filter_3'] |
| 477 |
|
| 478 |
utils.paginate_query(self.query, self.model, 5, |
| 479 |
['user_id', 'updated_at', 'project_id'], |
| 480 |
marker=self.marker, |
| 481 |
sort_dirs=['asc-nullslast', 'desc-nullsfirst', |
| 482 |
'desc-nullsfirst']) |
| 483 |
|
| 484 |
mock_is_not.assert_called_once_with(None) |
| 485 |
mock_is_a.assert_called_once_with(None) |
| 486 |
mock_is_b.assert_has_calls([mock.call(None), mock.call(None)]) |
| 487 |
mock_is_c.assert_has_calls([mock.call(None), mock.call(None)]) |
| 488 |
|
| 489 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 490 |
self.mock_desc.assert_has_calls([ |
| 491 |
mock.call('asc_null_1'), |
| 492 |
mock.call('desc_null_1'), |
| 493 |
mock.call(self.model.updated_at), |
| 494 |
mock.call('desc_null_3'), |
| 495 |
mock.call(self.model.project_id), |
| 496 |
]) |
| 497 |
self.query.order_by.assert_has_calls([ |
| 498 |
mock.call('asc_null_2'), |
| 499 |
mock.call('asc_1'), |
| 500 |
mock.call('desc_null_2'), |
| 501 |
mock.call('desc_1'), |
| 502 |
mock.call('desc_null_4'), |
| 503 |
mock.call('desc_4'), |
| 504 |
]) |
| 505 |
mock_or.assert_has_calls([ |
| 506 |
mock.call(mock.ANY, 'asc_null_filter_2'), |
| 507 |
mock.call(mock.ANY, 'desc_null_filter_3'), |
| 508 |
mock.call('some_crit', 'other_crit'), |
| 509 |
]) |
| 510 |
mock_and.assert_has_calls([ |
| 511 |
mock.call('or_1'), |
| 512 |
mock.call(mock.ANY, 'or_2'), |
| 513 |
]) |
| 514 |
self.query.filter.assert_called_once_with('some_f') |
| 515 |
self.query.limit.assert_called_once_with(5) |
| 516 |
|
| 517 |
def test_paginate_query_value_error(self): |
| 518 |
self.mock_asc.return_value = 'asc_1' |
| 519 |
self.query.order_by.return_value = self.query |
| 520 |
|
| 521 |
self.assertRaises(ValueError, utils.paginate_query, |
| 522 |
self.query, self.model, 5, ['user_id', 'project_id'], |
| 523 |
marker=self.marker, sort_dirs=['asc', 'mixed']) |
| 524 |
|
| 525 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 526 |
self.query.order_by.assert_called_once_with('asc_1') |
| 527 |
|
| 528 |
def test_paginate_on_hybrid(self): |
| 529 |
self.mock_asc.return_value = 'asc_1' |
| 530 |
self.mock_desc.return_value = 'desc_1' |
| 531 |
self.query.order_by.return_value = self.query |
| 532 |
|
| 533 |
utils.paginate_query(self.query, self.model, 5, |
| 534 |
['user_id', 'some_hybrid'], |
| 535 |
sort_dirs=['asc', 'desc']) |
| 536 |
|
| 537 |
self.mock_asc.assert_called_once_with(self.model.user_id) |
| 538 |
self.mock_desc.assert_called_once_with(self.model.some_hybrid) |
| 539 |
self.query.order_by.assert_has_calls([ |
| 540 |
mock.call('asc_1'), |
| 541 |
mock.call('desc_1'), |
| 542 |
]) |
| 543 |
self.query.limit.assert_called_once_with(5) |
| 544 |
|
| 545 |
|
| 546 |
class Test_UnstableSortingOrder(test_base.BaseTestCase): |
| 547 |
def test_multiple_primary_keys_stable(self): |
| 548 |
self.assertTrue( |
| 549 |
utils._stable_sorting_order( |
| 550 |
FakeTableWithMultipleKeys, ['key1', 'key2'])) |
| 551 |
|
| 552 |
def test_classically_mapped_primary_keys_stable(self): |
| 553 |
self.assertTrue( |
| 554 |
utils._stable_sorting_order(FakeTableClassicalyMapped, ['id'])) |
| 555 |
|
| 556 |
def test_multiple_primary_keys_unstable(self): |
| 557 |
self.assertFalse( |
| 558 |
utils._stable_sorting_order( |
| 559 |
FakeTableWithMultipleKeys, ['key1', 'key3'])) |
| 560 |
|
| 561 |
def test_joined_inh_stable(self): |
| 562 |
self.assertTrue( |
| 563 |
utils._stable_sorting_order(FakeTableJoinedInh, ['user_id']) |
| 564 |
) |
| 565 |
|
| 566 |
def test_single_inh_stable(self): |
| 567 |
self.assertTrue( |
| 568 |
utils._stable_sorting_order(FakeTableSingleInh, ['user_id']) |
| 569 |
) |
| 570 |
|
| 571 |
def test_unknown_primary_keys_stable(self): |
| 572 |
self.assertIsNone( |
| 573 |
utils._stable_sorting_order(object, ['key1', 'key2'])) |
| 574 |
|
| 575 |
def test_unique_index_stable(self): |
| 576 |
self.assertTrue( |
| 577 |
utils._stable_sorting_order( |
| 578 |
FakeTableWithIndexes, ['key1', 'key2'])) |
| 579 |
|
| 580 |
def test_unique_index_unstable(self): |
| 581 |
self.assertFalse( |
| 582 |
utils._stable_sorting_order( |
| 583 |
FakeTableWithIndexes, ['key1', 'key3'])) |
| 584 |
|
| 585 |
|
| 586 |
class TestGetUniqueKeys(test_base.BaseTestCase): |
| 587 |
def test_multiple_primary_keys(self): |
| 588 |
self.assertEqual( |
| 589 |
[{'key1', 'key2'}], |
| 590 |
utils.get_unique_keys(FakeTableWithMultipleKeys)) |
| 591 |
|
| 592 |
def test_unique_index(self): |
| 593 |
self.assertEqual( |
| 594 |
[{'id'}, {'key1', 'key2'}], |
| 595 |
utils.get_unique_keys(FakeTableWithIndexes)) |
| 596 |
|
| 597 |
def test_unknown_primary_keys(self): |
| 598 |
self.assertIsNone(utils.get_unique_keys(object)) |
| 599 |
|
| 600 |
def test_cache(self): |
| 601 |
|
| 602 |
class CacheTable: |
| 603 |
info = {} |
| 604 |
constraints_called = 0 |
| 605 |
indexes_called = 0 |
| 606 |
|
| 607 |
@property |
| 608 |
def constraints(self): |
| 609 |
self.constraints_called += 1 |
| 610 |
return [] |
| 611 |
|
| 612 |
@property |
| 613 |
def indexes(self): |
| 614 |
self.indexes_called += 1 |
| 615 |
return [] |
| 616 |
|
| 617 |
class CacheModel: |
| 618 |
pass |
| 619 |
|
| 620 |
table = CacheTable() |
| 621 |
mapper_mock = mock.Mock(mapped_table=table, local_table=table) |
| 622 |
mapper_mock.base_mapper = mapper_mock |
| 623 |
mock_inspect = mock.Mock( |
| 624 |
return_value=mapper_mock) |
| 625 |
model = CacheModel() |
| 626 |
self.assertNotIn('oslodb_unique_keys', CacheTable.info) |
| 627 |
with mock.patch("oslo_db.sqlalchemy.utils.inspect", mock_inspect): |
| 628 |
utils.get_unique_keys(model) |
| 629 |
|
| 630 |
self.assertIn('oslodb_unique_keys', CacheTable.info) |
| 631 |
self.assertEqual(1, table.constraints_called) |
| 632 |
self.assertEqual(1, table.indexes_called) |
| 633 |
|
| 634 |
for i in range(10): |
| 635 |
utils.get_unique_keys(model) |
| 636 |
|
| 637 |
self.assertEqual(1, table.constraints_called) |
| 638 |
self.assertEqual(1, table.indexes_called) |
| 639 |
|
| 640 |
|
| 641 |
class TestPaginateQueryActualSQL(test_base.BaseTestCase): |
| 642 |
|
| 643 |
def test_paginate_with_boolean_sort(self): |
| 644 |
s = Session() |
| 645 |
q = s.query(FakeTable) |
| 646 |
q = utils.paginate_query(q, FakeTable, 5, ['enabled'], |
| 647 |
sort_dirs=['asc'], |
| 648 |
marker=FakeTable(user_id='hello', |
| 649 |
enabled=False)) |
| 650 |
expected_core_sql = ( |
| 651 |
select(FakeTable). |
| 652 |
order_by(sqlalchemy.asc(FakeTable.enabled)). |
| 653 |
where(cast(FakeTable.enabled, Integer) > 0). |
| 654 |
limit(5) |
| 655 |
) |
| 656 |
|
| 657 |
self.assertEqual( |
| 658 |
str(expected_core_sql.compile()), |
| 659 |
str(q.statement.compile()) |
| 660 |
) |
| 661 |
|
| 662 |
def test_paginate_on_hybrid_assert_stmt(self): |
| 663 |
s = Session() |
| 664 |
q = s.query(FakeTable) |
| 665 |
q = utils.paginate_query( |
| 666 |
q, FakeTable, 5, |
| 667 |
['user_id', 'some_hybrid'], |
| 668 |
sort_dirs=['asc', 'desc']) |
| 669 |
expected_core_sql = ( |
| 670 |
select(FakeTable). |
| 671 |
order_by(sqlalchemy.asc(FakeTable.user_id)). |
| 672 |
order_by(sqlalchemy.desc(FakeTable.some_hybrid)). |
| 673 |
limit(5) |
| 674 |
) |
| 675 |
|
| 676 |
self.assertEqual( |
| 677 |
str(expected_core_sql.compile()), |
| 678 |
str(q.statement.compile()) |
| 679 |
) |
| 680 |
|
| 681 |
|
| 682 |
class TestMigrationUtils(db_test_base._DbTestCase): |
| 683 |
|
| 684 |
"""Class for testing utils that are used in db migrations.""" |
| 685 |
|
| 686 |
def setUp(self): |
| 687 |
super().setUp() |
| 688 |
self.meta = MetaData() |
| 689 |
self.conn = self.engine.connect() |
| 690 |
|
| 691 |
|
| 692 |
self.addCleanup(self.meta.drop_all, self.engine) |
| 693 |
self.addCleanup(self.conn.close) |
| 694 |
|
| 695 |
def _populate_db_for_drop_duplicate_entries(self, engine, meta, |
| 696 |
table_name): |
| 697 |
values = [ |
| 698 |
{'id': 11, 'a': 3, 'b': 10, 'c': 'abcdef'}, |
| 699 |
{'id': 12, 'a': 5, 'b': 10, 'c': 'abcdef'}, |
| 700 |
{'id': 13, 'a': 6, 'b': 10, 'c': 'abcdef'}, |
| 701 |
{'id': 14, 'a': 7, 'b': 10, 'c': 'abcdef'}, |
| 702 |
{'id': 21, 'a': 1, 'b': 20, 'c': 'aa'}, |
| 703 |
{'id': 31, 'a': 1, 'b': 20, 'c': 'bb'}, |
| 704 |
{'id': 41, 'a': 1, 'b': 30, 'c': 'aef'}, |
| 705 |
{'id': 42, 'a': 2, 'b': 30, 'c': 'aef'}, |
| 706 |
{'id': 43, 'a': 3, 'b': 30, 'c': 'aef'} |
| 707 |
] |
| 708 |
|
| 709 |
test_table = Table(table_name, meta, |
| 710 |
Column('id', Integer, primary_key=True, |
| 711 |
nullable=False), |
| 712 |
Column('a', Integer), |
| 713 |
Column('b', Integer), |
| 714 |
Column('c', String(255)), |
| 715 |
Column('deleted', Integer, default=0), |
| 716 |
Column('deleted_at', DateTime), |
| 717 |
Column('updated_at', DateTime)) |
| 718 |
|
| 719 |
test_table.create(engine) |
| 720 |
with engine.connect() as conn, conn.begin(): |
| 721 |
conn.execute(test_table.insert(), values) |
| 722 |
return test_table, values |
| 723 |
|
| 724 |
def test_drop_old_duplicate_entries_from_table(self): |
| 725 |
table_name = "__test_tmp_table__" |
| 726 |
|
| 727 |
test_table, values = self._populate_db_for_drop_duplicate_entries( |
| 728 |
self.engine, self.meta, table_name) |
| 729 |
utils.drop_old_duplicate_entries_from_table( |
| 730 |
self.engine, table_name, False, 'b', 'c') |
| 731 |
|
| 732 |
uniq_values = set() |
| 733 |
expected_ids = [] |
| 734 |
for value in sorted(values, key=lambda x: x['id'], reverse=True): |
| 735 |
uniq_value = (('b', value['b']), ('c', value['c'])) |
| 736 |
if uniq_value in uniq_values: |
| 737 |
continue |
| 738 |
uniq_values.add(uniq_value) |
| 739 |
expected_ids.append(value['id']) |
| 740 |
|
| 741 |
with self.engine.connect() as conn, conn.begin(): |
| 742 |
real_ids = [ |
| 743 |
row[0] for row in |
| 744 |
conn.execute(select(test_table.c.id)).fetchall() |
| 745 |
] |
| 746 |
|
| 747 |
self.assertEqual(len(expected_ids), len(real_ids)) |
| 748 |
for id_ in expected_ids: |
| 749 |
self.assertIn(id_, real_ids) |
| 750 |
|
| 751 |
def test_drop_dup_entries_in_file_conn(self): |
| 752 |
table_name = "__test_tmp_table__" |
| 753 |
tmp_db_file = self.create_tempfiles([['name', '']], ext='.sql')[0] |
| 754 |
facade = enginefacade.transaction_context() |
| 755 |
facade.configure(connection=f'sqlite:///{tmp_db_file}') |
| 756 |
in_file_engine = facade.writer.get_engine() |
| 757 |
meta = MetaData() |
| 758 |
test_table, values = self._populate_db_for_drop_duplicate_entries( |
| 759 |
in_file_engine, meta, table_name) |
| 760 |
utils.drop_old_duplicate_entries_from_table( |
| 761 |
in_file_engine, table_name, False, 'b', 'c') |
| 762 |
|
| 763 |
def test_drop_old_duplicate_entries_from_table_soft_delete(self): |
| 764 |
table_name = "__test_tmp_table__" |
| 765 |
|
| 766 |
table, values = self._populate_db_for_drop_duplicate_entries( |
| 767 |
self.engine, self.meta, table_name) |
| 768 |
utils.drop_old_duplicate_entries_from_table(self.engine, table_name, |
| 769 |
True, 'b', 'c') |
| 770 |
uniq_values = set() |
| 771 |
expected_values = [] |
| 772 |
soft_deleted_values = [] |
| 773 |
|
| 774 |
for value in sorted(values, key=lambda x: x['id'], reverse=True): |
| 775 |
uniq_value = (('b', value['b']), ('c', value['c'])) |
| 776 |
if uniq_value in uniq_values: |
| 777 |
soft_deleted_values.append(value) |
| 778 |
continue |
| 779 |
uniq_values.add(uniq_value) |
| 780 |
expected_values.append(value) |
| 781 |
|
| 782 |
base_select = table.select() |
| 783 |
|
| 784 |
with self.engine.connect() as conn, conn.begin(): |
| 785 |
rows_select = base_select.where(table.c.deleted != table.c.id) |
| 786 |
row_ids = [ |
| 787 |
row.id for row in conn.execute(rows_select).fetchall() |
| 788 |
] |
| 789 |
self.assertEqual(len(expected_values), len(row_ids)) |
| 790 |
for value in expected_values: |
| 791 |
self.assertIn(value['id'], row_ids) |
| 792 |
|
| 793 |
deleted_rows_select = base_select.where( |
| 794 |
table.c.deleted == table.c.id) |
| 795 |
deleted_rows_ids = [ |
| 796 |
row.id for row in |
| 797 |
conn.execute(deleted_rows_select).fetchall() |
| 798 |
] |
| 799 |
self.assertEqual(len(values) - len(row_ids), |
| 800 |
len(deleted_rows_ids)) |
| 801 |
for value in soft_deleted_values: |
| 802 |
self.assertIn(value['id'], deleted_rows_ids) |
| 803 |
|
| 804 |
def test_get_foreign_key_constraint_name(self): |
| 805 |
table_1 = Table('table_name_1', self.meta, |
| 806 |
Column('id', Integer, primary_key=True), |
| 807 |
Column('deleted', Integer)) |
| 808 |
table_2 = Table('table_name_2', self.meta, |
| 809 |
Column('id', Integer, primary_key=True), |
| 810 |
Column('foreign_id', Integer), |
| 811 |
ForeignKeyConstraint(['foreign_id'], |
| 812 |
['table_name_1.id'], |
| 813 |
name='table_name_2_fk1'), |
| 814 |
Column('deleted', Integer)) |
| 815 |
|
| 816 |
self.meta.create_all(self.engine, tables=[table_1, table_2]) |
| 817 |
fkc = utils.get_foreign_key_constraint_name(self.engine, |
| 818 |
'table_name_2', |
| 819 |
'foreign_id') |
| 820 |
self.assertEqual(fkc, 'table_name_2_fk1') |
| 821 |
|
| 822 |
|
| 823 |
class PostgresqlTestMigrations(TestMigrationUtils, |
| 824 |
db_test_base._PostgreSQLOpportunisticTestCase): |
| 825 |
|
| 826 |
"""Test migrations on PostgreSQL.""" |
| 827 |
pass |
| 828 |
|
| 829 |
|
| 830 |
class MySQLTestMigrations(TestMigrationUtils, |
| 831 |
db_test_base._MySQLOpportunisticTestCase): |
| 832 |
|
| 833 |
"""Test migrations on MySQL.""" |
| 834 |
pass |
| 835 |
|
| 836 |
|
| 837 |
class TestConnectionUtils(test_base.BaseTestCase): |
| 838 |
|
| 839 |
def setUp(self): |
| 840 |
super().setUp() |
| 841 |
|
| 842 |
self.full_credentials = {'backend': 'postgresql+psycopg2', |
| 843 |
'database': 'test', |
| 844 |
'user': 'dude', |
| 845 |
'passwd': 'pass'} |
| 846 |
|
| 847 |
self.connect_string = 'postgresql+psycopg2://dude:pass@localhost/test' |
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
@classmethod |
| 853 |
def fake_dbapi(cls): |
| 854 |
return mock.MagicMock() |
| 855 |
|
| 856 |
class OurDialect(psycopg2.PGDialect_psycopg2): |
| 857 |
def dbapi(self): |
| 858 |
return fake_dbapi |
| 859 |
|
| 860 |
def import_dbapi(self): |
| 861 |
return fake_dbapi |
| 862 |
|
| 863 |
patch_dbapi = mock.patch.object( |
| 864 |
psycopg2, |
| 865 |
"PGDialect_psycopg2", |
| 866 |
new=OurDialect, |
| 867 |
) |
| 868 |
|
| 869 |
patch_dbapi.start() |
| 870 |
self.addCleanup(patch_dbapi.stop) |
| 871 |
|
| 872 |
patch_onconnect = mock.patch.object(psycopg2.PGDialect_psycopg2, |
| 873 |
'on_connect') |
| 874 |
patch_onconnect.start() |
| 875 |
self.addCleanup(patch_onconnect.stop) |
| 876 |
|
| 877 |
def test_ensure_backend_available(self): |
| 878 |
with mock.patch.object( |
| 879 |
sqlalchemy.engine.base.Engine, 'connect') as mock_connect: |
| 880 |
fake_connection = mock.Mock() |
| 881 |
mock_connect.return_value = fake_connection |
| 882 |
|
| 883 |
eng = provision.Backend._ensure_backend_available( |
| 884 |
self.connect_string) |
| 885 |
|
| 886 |
self.assertIsInstance(eng, sqlalchemy.engine.base.Engine) |
| 887 |
self.assertEqual(utils.make_url(self.connect_string), eng.url) |
| 888 |
|
| 889 |
mock_connect.assert_called_once() |
| 890 |
fake_connection.close.assert_called_once() |
| 891 |
|
| 892 |
def test_ensure_backend_available_no_connection_raises(self): |
| 893 |
log = self.useFixture(fixtures.FakeLogger()) |
| 894 |
err = OperationalError("Can't connect to database", None, None) |
| 895 |
with mock.patch.object( |
| 896 |
sqlalchemy.engine.base.Engine, 'connect') as mock_connect: |
| 897 |
mock_connect.side_effect = err |
| 898 |
|
| 899 |
exc = self.assertRaises( |
| 900 |
exception.BackendNotAvailable, |
| 901 |
provision.Backend._ensure_backend_available, |
| 902 |
self.connect_string) |
| 903 |
self.assertEqual( |
| 904 |
"Backend 'postgresql+psycopg2' is unavailable: " |
| 905 |
"Could not connect", str(exc)) |
| 906 |
self.assertEqual( |
| 907 |
"The postgresql+psycopg2 backend is unavailable: %s" % err, |
| 908 |
log.output.strip()) |
| 909 |
|
| 910 |
def test_ensure_backend_available_no_dbapi_raises(self): |
| 911 |
log = self.useFixture(fixtures.FakeLogger()) |
| 912 |
with mock.patch.object(sqlalchemy, 'create_engine') as mock_create: |
| 913 |
mock_create.side_effect = ImportError( |
| 914 |
"Can't import DBAPI module foobar") |
| 915 |
|
| 916 |
exc = self.assertRaises( |
| 917 |
exception.BackendNotAvailable, |
| 918 |
provision.Backend._ensure_backend_available, |
| 919 |
self.connect_string) |
| 920 |
|
| 921 |
mock_create.assert_called_once_with( |
| 922 |
utils.make_url(self.connect_string)) |
| 923 |
|
| 924 |
self.assertEqual( |
| 925 |
"Backend 'postgresql+psycopg2' is unavailable: " |
| 926 |
"No DBAPI installed", str(exc)) |
| 927 |
self.assertEqual( |
| 928 |
"The postgresql+psycopg2 backend is unavailable: Can't import " |
| 929 |
"DBAPI module foobar", log.output.strip()) |
| 930 |
|
| 931 |
def test_get_db_connection_info(self): |
| 932 |
conn_pieces = parse.urlparse(self.connect_string) |
| 933 |
self.assertEqual(('dude', 'pass', 'test', 'localhost'), |
| 934 |
utils.get_db_connection_info(conn_pieces)) |
| 935 |
|
| 936 |
|
| 937 |
class MyModelSoftDeletedProjectId(declarative_base(), models.ModelBase, |
| 938 |
models.SoftDeleteMixin): |
| 939 |
__tablename__ = 'soft_deleted_project_id_test_model' |
| 940 |
id = Column(Integer, primary_key=True) |
| 941 |
project_id = Column(Integer) |
| 942 |
|
| 943 |
|
| 944 |
class MyModel(declarative_base(), models.ModelBase): |
| 945 |
__tablename__ = 'test_model' |
| 946 |
id = Column(Integer, primary_key=True) |
| 947 |
|
| 948 |
|
| 949 |
class MyModelSoftDeleted(declarative_base(), models.ModelBase, |
| 950 |
models.SoftDeleteMixin): |
| 951 |
__tablename__ = 'soft_deleted_test_model' |
| 952 |
id = Column(Integer, primary_key=True) |
| 953 |
|
| 954 |
|
| 955 |
class TestModelQuery(test_base.BaseTestCase): |
| 956 |
|
| 957 |
def setUp(self): |
| 958 |
super().setUp() |
| 959 |
|
| 960 |
self.session = mock.MagicMock() |
| 961 |
self.session.query.return_value = self.session.query |
| 962 |
self.session.query.filter.return_value = self.session.query |
| 963 |
|
| 964 |
def test_wrong_model(self): |
| 965 |
self.assertRaises(TypeError, utils.model_query, |
| 966 |
FakeModel, session=self.session) |
| 967 |
|
| 968 |
def test_no_soft_deleted(self): |
| 969 |
self.assertRaises(ValueError, utils.model_query, |
| 970 |
MyModel, session=self.session, deleted=True) |
| 971 |
|
| 972 |
def test_deleted_false(self): |
| 973 |
mock_query = utils.model_query( |
| 974 |
MyModelSoftDeleted, session=self.session, deleted=False) |
| 975 |
|
| 976 |
deleted_filter = mock_query.filter.call_args[0][0] |
| 977 |
self.assertEqual('soft_deleted_test_model.deleted = :deleted_1', |
| 978 |
str(deleted_filter)) |
| 979 |
self.assertEqual(deleted_filter.right.value, |
| 980 |
MyModelSoftDeleted.__mapper__.c.deleted.default.arg) |
| 981 |
|
| 982 |
def test_deleted_true(self): |
| 983 |
mock_query = utils.model_query( |
| 984 |
MyModelSoftDeleted, session=self.session, deleted=True) |
| 985 |
|
| 986 |
deleted_filter = mock_query.filter.call_args[0][0] |
| 987 |
self.assertEqual(str(deleted_filter), |
| 988 |
'soft_deleted_test_model.deleted != :deleted_1') |
| 989 |
self.assertEqual(deleted_filter.right.value, |
| 990 |
MyModelSoftDeleted.__mapper__.c.deleted.default.arg) |
| 991 |
|
| 992 |
@mock.patch.object(utils, "_read_deleted_filter") |
| 993 |
def test_no_deleted_value(self, _read_deleted_filter): |
| 994 |
utils.model_query(MyModelSoftDeleted, session=self.session) |
| 995 |
self.assertEqual(0, _read_deleted_filter.call_count) |
| 996 |
|
| 997 |
def test_project_filter(self): |
| 998 |
project_id = 10 |
| 999 |
|
| 1000 |
mock_query = utils.model_query( |
| 1001 |
MyModelSoftDeletedProjectId, session=self.session, |
| 1002 |
project_only=True, project_id=project_id) |
| 1003 |
|
| 1004 |
deleted_filter = mock_query.filter.call_args[0][0] |
| 1005 |
self.assertEqual( |
| 1006 |
'soft_deleted_project_id_test_model.project_id = :project_id_1', |
| 1007 |
str(deleted_filter)) |
| 1008 |
self.assertEqual(project_id, deleted_filter.right.value) |
| 1009 |
|
| 1010 |
def test_project_filter_wrong_model(self): |
| 1011 |
self.assertRaises(ValueError, utils.model_query, |
| 1012 |
MyModelSoftDeleted, session=self.session, |
| 1013 |
project_id=10) |
| 1014 |
|
| 1015 |
def test_project_filter_allow_none(self): |
| 1016 |
mock_query = utils.model_query( |
| 1017 |
MyModelSoftDeletedProjectId, |
| 1018 |
session=self.session, project_id=(10, None)) |
| 1019 |
|
| 1020 |
self.assertRegex( |
| 1021 |
str( |
| 1022 |
mock_query.filter.call_args[0][0]. |
| 1023 |
compile(compile_kwargs={"render_postcompile": True}) |
| 1024 |
), |
| 1025 |
'soft_deleted_project_id_test_model.project_id' |
| 1026 |
r' IN \(:project_id.+, (?::project_id.+|NULL)\)', |
| 1027 |
) |
| 1028 |
|
| 1029 |
def test_model_query_common(self): |
| 1030 |
utils.model_query(MyModel, args=(MyModel.id,), session=self.session) |
| 1031 |
self.session.query.assert_called_with(MyModel.id) |
| 1032 |
|
| 1033 |
|
| 1034 |
class TestUtils(db_test_base._DbTestCase): |
| 1035 |
def setUp(self): |
| 1036 |
super().setUp() |
| 1037 |
meta = MetaData() |
| 1038 |
self.test_table = Table( |
| 1039 |
'test_table', |
| 1040 |
meta, |
| 1041 |
Column('a', Integer), |
| 1042 |
Column('b', Integer) |
| 1043 |
) |
| 1044 |
self.test_table.create(self.engine) |
| 1045 |
self.addCleanup(meta.drop_all, self.engine) |
| 1046 |
|
| 1047 |
def test_get_indexes(self): |
| 1048 |
Index('index_a', self.test_table.c.a).create(self.engine) |
| 1049 |
Index('index_b', self.test_table.c.b).create(self.engine) |
| 1050 |
indexes = utils.get_indexes(self.engine, "test_table") |
| 1051 |
indexes = [(index['name'], index['column_names']) for index in indexes] |
| 1052 |
self.assertIn(('index_a', ['a']), indexes) |
| 1053 |
self.assertIn(('index_b', ['b']), indexes) |
| 1054 |
|
| 1055 |
def test_index_exists(self): |
| 1056 |
self.assertFalse(utils.index_exists(self.engine, 'test_table', |
| 1057 |
'new_index')) |
| 1058 |
Index('new_index', self.test_table.c.a).create(self.engine) |
| 1059 |
self.assertTrue(utils.index_exists(self.engine, 'test_table', |
| 1060 |
'new_index')) |
| 1061 |
|
| 1062 |
def test_index_exists_on_columns(self): |
| 1063 |
columns = [self.test_table.c.a, self.test_table.c.b] |
| 1064 |
Index('new_index', *columns).create(self.engine) |
| 1065 |
self.assertTrue(utils.index_exists_on_columns(self.engine, |
| 1066 |
'test_table', |
| 1067 |
('a', 'b'))) |
| 1068 |
|
| 1069 |
def test_add_index(self): |
| 1070 |
self.assertFalse(utils.index_exists(self.engine, 'test_table', |
| 1071 |
'new_index')) |
| 1072 |
utils.add_index(self.engine, 'test_table', 'new_index', ('a',)) |
| 1073 |
self.assertTrue(utils.index_exists(self.engine, 'test_table', |
| 1074 |
'new_index')) |
| 1075 |
|
| 1076 |
def test_add_existing_index(self): |
| 1077 |
Index('new_index', self.test_table.c.a).create(self.engine) |
| 1078 |
self.assertRaises(ValueError, utils.add_index, self.engine, |
| 1079 |
'test_table', 'new_index', ('a',)) |
| 1080 |
|
| 1081 |
def test_drop_index(self): |
| 1082 |
Index('new_index', self.test_table.c.a).create(self.engine) |
| 1083 |
utils.drop_index(self.engine, 'test_table', 'new_index') |
| 1084 |
self.assertFalse(utils.index_exists(self.engine, 'test_table', |
| 1085 |
'new_index')) |
| 1086 |
|
| 1087 |
def test_drop_unexisting_index(self): |
| 1088 |
self.assertRaises(ValueError, utils.drop_index, self.engine, |
| 1089 |
'test_table', 'new_index') |
| 1090 |
|
| 1091 |
@mock.patch('oslo_db.sqlalchemy.utils.drop_index') |
| 1092 |
@mock.patch('oslo_db.sqlalchemy.utils.add_index') |
| 1093 |
def test_change_index_columns(self, add_index, drop_index): |
| 1094 |
utils.change_index_columns(self.engine, 'test_table', 'a_index', |
| 1095 |
('a',)) |
| 1096 |
utils.drop_index.assert_called_once_with(self.engine, 'test_table', |
| 1097 |
'a_index') |
| 1098 |
utils.add_index.assert_called_once_with(self.engine, 'test_table', |
| 1099 |
'a_index', ('a',)) |
| 1100 |
|
| 1101 |
def test_column_exists(self): |
| 1102 |
for col in ['a', 'b']: |
| 1103 |
self.assertTrue(utils.column_exists(self.engine, 'test_table', |
| 1104 |
col)) |
| 1105 |
self.assertFalse(utils.column_exists(self.engine, 'test_table', |
| 1106 |
'fake_column')) |
| 1107 |
|
| 1108 |
|
| 1109 |
class TestUtilsMysqlOpportunistically( |
| 1110 |
TestUtils, db_test_base._MySQLOpportunisticTestCase): |
| 1111 |
pass |
| 1112 |
|
| 1113 |
|
| 1114 |
class TestUtilsPostgresqlOpportunistically( |
| 1115 |
TestUtils, db_test_base._PostgreSQLOpportunisticTestCase): |
| 1116 |
pass |
| 1117 |
|
| 1118 |
|
| 1119 |
class TestDialectFunctionDispatcher(test_base.BaseTestCase): |
| 1120 |
def _single_fixture(self): |
| 1121 |
callable_fn = mock.Mock() |
| 1122 |
|
| 1123 |
dispatcher = orig = utils.dispatch_for_dialect("*")( |
| 1124 |
callable_fn.default) |
| 1125 |
dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite) |
| 1126 |
dispatcher = dispatcher.dispatch_for("mysql+pymysql")( |
| 1127 |
callable_fn.mysql_pymysql) |
| 1128 |
dispatcher = dispatcher.dispatch_for("mysql")( |
| 1129 |
callable_fn.mysql) |
| 1130 |
dispatcher = dispatcher.dispatch_for("postgresql")( |
| 1131 |
callable_fn.postgresql) |
| 1132 |
|
| 1133 |
self.assertTrue(dispatcher is orig) |
| 1134 |
|
| 1135 |
return dispatcher, callable_fn |
| 1136 |
|
| 1137 |
def _multiple_fixture(self): |
| 1138 |
callable_fn = mock.Mock() |
| 1139 |
|
| 1140 |
for targ in [ |
| 1141 |
callable_fn.default, |
| 1142 |
callable_fn.sqlite, |
| 1143 |
callable_fn.mysql, |
| 1144 |
callable_fn.mysql_pymysql, |
| 1145 |
callable_fn.postgresql, |
| 1146 |
callable_fn.postgresql_psycopg2, |
| 1147 |
callable_fn.pyodbc |
| 1148 |
]: |
| 1149 |
targ.return_value = None |
| 1150 |
|
| 1151 |
dispatcher = orig = utils.dispatch_for_dialect("*", multiple=True)( |
| 1152 |
callable_fn.default) |
| 1153 |
dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite) |
| 1154 |
dispatcher = dispatcher.dispatch_for("mysql+pymysql")( |
| 1155 |
callable_fn.mysql_pymysql) |
| 1156 |
dispatcher = dispatcher.dispatch_for("mysql")( |
| 1157 |
callable_fn.mysql) |
| 1158 |
dispatcher = dispatcher.dispatch_for("postgresql+*")( |
| 1159 |
callable_fn.postgresql) |
| 1160 |
dispatcher = dispatcher.dispatch_for("postgresql+psycopg2")( |
| 1161 |
callable_fn.postgresql_psycopg2) |
| 1162 |
dispatcher = dispatcher.dispatch_for("*+pyodbc")( |
| 1163 |
callable_fn.pyodbc) |
| 1164 |
|
| 1165 |
self.assertTrue(dispatcher is orig) |
| 1166 |
|
| 1167 |
return dispatcher, callable_fn |
| 1168 |
|
| 1169 |
def test_single(self): |
| 1170 |
|
| 1171 |
dispatcher, callable_fn = self._single_fixture() |
| 1172 |
dispatcher("sqlite://", 1) |
| 1173 |
dispatcher("postgresql+psycopg2://u:p@h/t", 2) |
| 1174 |
dispatcher("mysql+pymysql://u:p@h/t", 3) |
| 1175 |
dispatcher("mysql://u:p@h/t", 4) |
| 1176 |
dispatcher("mysql+mysqlconnector://u:p@h/t", 5) |
| 1177 |
|
| 1178 |
self.assertEqual( |
| 1179 |
[ |
| 1180 |
mock.call.sqlite('sqlite://', 1), |
| 1181 |
mock.call.postgresql("postgresql+psycopg2://u:p@h/t", 2), |
| 1182 |
mock.call.mysql_pymysql("mysql+pymysql://u:p@h/t", 3), |
| 1183 |
mock.call.mysql("mysql://u:p@h/t", 4), |
| 1184 |
mock.call.mysql("mysql+mysqlconnector://u:p@h/t", 5), |
| 1185 |
], |
| 1186 |
callable_fn.mock_calls) |
| 1187 |
|
| 1188 |
def test_single_kwarg(self): |
| 1189 |
dispatcher, callable_fn = self._single_fixture() |
| 1190 |
dispatcher("sqlite://", foo='bar') |
| 1191 |
dispatcher("postgresql+psycopg2://u:p@h/t", 1, x='y') |
| 1192 |
|
| 1193 |
self.assertEqual( |
| 1194 |
[ |
| 1195 |
mock.call.sqlite('sqlite://', foo='bar'), |
| 1196 |
mock.call.postgresql( |
| 1197 |
"postgresql+psycopg2://u:p@h/t", |
| 1198 |
1, x='y'), |
| 1199 |
], |
| 1200 |
callable_fn.mock_calls) |
| 1201 |
|
| 1202 |
def test_dispatch_on_target(self): |
| 1203 |
callable_fn = mock.Mock() |
| 1204 |
|
| 1205 |
@utils.dispatch_for_dialect("*") |
| 1206 |
def default_fn(url, x, y): |
| 1207 |
callable_fn.default(url, x, y) |
| 1208 |
|
| 1209 |
@default_fn.dispatch_for("sqlite") |
| 1210 |
def sqlite_fn(url, x, y): |
| 1211 |
callable_fn.sqlite(url, x, y) |
| 1212 |
default_fn.dispatch_on_drivername("*")(url, x, y) |
| 1213 |
|
| 1214 |
default_fn("sqlite://", 4, 5) |
| 1215 |
self.assertEqual( |
| 1216 |
[ |
| 1217 |
mock.call.sqlite("sqlite://", 4, 5), |
| 1218 |
mock.call.default("sqlite://", 4, 5) |
| 1219 |
], |
| 1220 |
callable_fn.mock_calls |
| 1221 |
) |
| 1222 |
|
| 1223 |
def test_single_no_dispatcher(self): |
| 1224 |
callable_fn = mock.Mock() |
| 1225 |
|
| 1226 |
dispatcher = utils.dispatch_for_dialect("sqlite")(callable_fn.sqlite) |
| 1227 |
dispatcher = dispatcher.dispatch_for("mysql")(callable_fn.mysql) |
| 1228 |
exc = self.assertRaises( |
| 1229 |
ValueError, |
| 1230 |
dispatcher, "postgresql://s:t@localhost/test" |
| 1231 |
) |
| 1232 |
self.assertEqual( |
| 1233 |
"No default function found for driver: 'postgresql+psycopg2'", |
| 1234 |
str(exc) |
| 1235 |
) |
| 1236 |
|
| 1237 |
def test_multiple_no_dispatcher(self): |
| 1238 |
callable_fn = mock.Mock() |
| 1239 |
|
| 1240 |
dispatcher = utils.dispatch_for_dialect("sqlite", multiple=True)( |
| 1241 |
callable_fn.sqlite) |
| 1242 |
dispatcher = dispatcher.dispatch_for("mysql")(callable_fn.mysql) |
| 1243 |
dispatcher("postgresql://s:t@localhost/test") |
| 1244 |
self.assertEqual( |
| 1245 |
[], callable_fn.mock_calls |
| 1246 |
) |
| 1247 |
|
| 1248 |
def test_multiple_no_driver(self): |
| 1249 |
callable_fn = mock.Mock( |
| 1250 |
default=mock.Mock(return_value=None), |
| 1251 |
sqlite=mock.Mock(return_value=None) |
| 1252 |
) |
| 1253 |
|
| 1254 |
dispatcher = utils.dispatch_for_dialect("*", multiple=True)( |
| 1255 |
callable_fn.default) |
| 1256 |
dispatcher = dispatcher.dispatch_for("sqlite")( |
| 1257 |
callable_fn.sqlite) |
| 1258 |
|
| 1259 |
dispatcher.dispatch_on_drivername("sqlite")("foo") |
| 1260 |
self.assertEqual( |
| 1261 |
[mock.call.sqlite("foo"), mock.call.default("foo")], |
| 1262 |
callable_fn.mock_calls |
| 1263 |
) |
| 1264 |
|
| 1265 |
def test_multiple_nesting(self): |
| 1266 |
callable_fn = mock.Mock( |
| 1267 |
default=mock.Mock(return_value=None), |
| 1268 |
mysql=mock.Mock(return_value=None) |
| 1269 |
) |
| 1270 |
|
| 1271 |
dispatcher = utils.dispatch_for_dialect("*", multiple=True)( |
| 1272 |
callable_fn.default) |
| 1273 |
|
| 1274 |
dispatcher = dispatcher.dispatch_for("mysql+mysqlconnector")( |
| 1275 |
dispatcher.dispatch_for("mysql+mysqldb")( |
| 1276 |
callable_fn.mysql |
| 1277 |
) |
| 1278 |
) |
| 1279 |
|
| 1280 |
mysqldb_url = utils.make_url("mysql+mysqldb://") |
| 1281 |
mysqlconnector_url = utils.make_url("mysql+mysqlconnector://") |
| 1282 |
sqlite_url = utils.make_url("sqlite://") |
| 1283 |
|
| 1284 |
dispatcher(mysqldb_url, 1) |
| 1285 |
dispatcher(mysqlconnector_url, 2) |
| 1286 |
dispatcher(sqlite_url, 3) |
| 1287 |
|
| 1288 |
self.assertEqual( |
| 1289 |
[ |
| 1290 |
mock.call.mysql(mysqldb_url, 1), |
| 1291 |
mock.call.default(mysqldb_url, 1), |
| 1292 |
mock.call.mysql(mysqlconnector_url, 2), |
| 1293 |
mock.call.default(mysqlconnector_url, 2), |
| 1294 |
mock.call.default(sqlite_url, 3) |
| 1295 |
], |
| 1296 |
callable_fn.mock_calls |
| 1297 |
) |
| 1298 |
|
| 1299 |
def test_single_retval(self): |
| 1300 |
dispatcher, callable_fn = self._single_fixture() |
| 1301 |
callable_fn.mysql_pymysql.return_value = 5 |
| 1302 |
|
| 1303 |
self.assertEqual( |
| 1304 |
5, dispatcher("mysql+pymysql://u:p@h/t", 3) |
| 1305 |
) |
| 1306 |
|
| 1307 |
def test_engine(self): |
| 1308 |
eng = sqlalchemy.create_engine("sqlite:///path/to/my/db.db") |
| 1309 |
dispatcher, callable_fn = self._single_fixture() |
| 1310 |
|
| 1311 |
dispatcher(eng) |
| 1312 |
self.assertEqual( |
| 1313 |
[mock.call.sqlite(eng)], |
| 1314 |
callable_fn.mock_calls |
| 1315 |
) |
| 1316 |
|
| 1317 |
def test_url_pymysql(self): |
| 1318 |
url = utils.make_url("mysql+pymysql://scott:tiger@localhost/test") |
| 1319 |
dispatcher, callable_fn = self._single_fixture() |
| 1320 |
|
| 1321 |
dispatcher(url, 15) |
| 1322 |
self.assertEqual( |
| 1323 |
[mock.call.mysql_pymysql(url, 15)], |
| 1324 |
callable_fn.mock_calls |
| 1325 |
) |
| 1326 |
|
| 1327 |
def test_url_mysql_generic(self): |
| 1328 |
url = utils.make_url("mysql://scott:tiger@localhost/test") |
| 1329 |
dispatcher, callable_fn = self._single_fixture() |
| 1330 |
|
| 1331 |
dispatcher(url, 15) |
| 1332 |
self.assertEqual( |
| 1333 |
[mock.call.mysql(url, 15)], |
| 1334 |
callable_fn.mock_calls |
| 1335 |
) |
| 1336 |
|
| 1337 |
def test_invalid_target(self): |
| 1338 |
dispatcher, callable_fn = self._single_fixture() |
| 1339 |
|
| 1340 |
exc = self.assertRaises( |
| 1341 |
ValueError, |
| 1342 |
dispatcher, 20 |
| 1343 |
) |
| 1344 |
self.assertEqual("Invalid target type: 20", str(exc)) |
| 1345 |
|
| 1346 |
def test_invalid_dispatch(self): |
| 1347 |
callable_fn = mock.Mock() |
| 1348 |
|
| 1349 |
dispatcher = utils.dispatch_for_dialect("*")(callable_fn.default) |
| 1350 |
|
| 1351 |
exc = self.assertRaises( |
| 1352 |
ValueError, |
| 1353 |
dispatcher.dispatch_for("+pyodbc"), callable_fn.pyodbc |
| 1354 |
) |
| 1355 |
self.assertEqual( |
| 1356 |
"Couldn't parse database[+driver]: '+pyodbc'", |
| 1357 |
str(exc) |
| 1358 |
) |
| 1359 |
|
| 1360 |
def test_single_only_one_target(self): |
| 1361 |
callable_fn = mock.Mock() |
| 1362 |
|
| 1363 |
dispatcher = utils.dispatch_for_dialect("*")(callable_fn.default) |
| 1364 |
dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite) |
| 1365 |
|
| 1366 |
exc = self.assertRaises( |
| 1367 |
TypeError, |
| 1368 |
dispatcher.dispatch_for("sqlite"), callable_fn.sqlite2 |
| 1369 |
) |
| 1370 |
self.assertEqual( |
| 1371 |
"Multiple functions for expression 'sqlite'", str(exc) |
| 1372 |
) |
| 1373 |
|
| 1374 |
def test_multiple(self): |
| 1375 |
dispatcher, callable_fn = self._multiple_fixture() |
| 1376 |
|
| 1377 |
dispatcher("postgresql+pyodbc://", 1) |
| 1378 |
dispatcher("mysql+pymysql://", 2) |
| 1379 |
dispatcher("postgresql+psycopg2://", 4) |
| 1380 |
dispatcher("postgresql://", 5) |
| 1381 |
|
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
self.assertEqual( |
| 1386 |
[ |
| 1387 |
mock.call.postgresql('postgresql+pyodbc://', 1), |
| 1388 |
mock.call.pyodbc('postgresql+pyodbc://', 1), |
| 1389 |
mock.call.default('postgresql+pyodbc://', 1), |
| 1390 |
mock.call.mysql_pymysql('mysql+pymysql://', 2), |
| 1391 |
mock.call.mysql('mysql+pymysql://', 2), |
| 1392 |
mock.call.default('mysql+pymysql://', 2), |
| 1393 |
mock.call.postgresql_psycopg2('postgresql+psycopg2://', 4), |
| 1394 |
mock.call.postgresql('postgresql+psycopg2://', 4), |
| 1395 |
mock.call.default('postgresql+psycopg2://', 4), |
| 1396 |
|
| 1397 |
|
| 1398 |
mock.call.postgresql_psycopg2('postgresql://', 5), |
| 1399 |
mock.call.postgresql('postgresql://', 5), |
| 1400 |
mock.call.default('postgresql://', 5), |
| 1401 |
], |
| 1402 |
callable_fn.mock_calls |
| 1403 |
) |
| 1404 |
|
| 1405 |
def test_multiple_no_return_value(self): |
| 1406 |
dispatcher, callable_fn = self._multiple_fixture() |
| 1407 |
callable_fn.sqlite.return_value = 5 |
| 1408 |
|
| 1409 |
exc = self.assertRaises( |
| 1410 |
TypeError, |
| 1411 |
dispatcher, "sqlite://" |
| 1412 |
) |
| 1413 |
self.assertEqual( |
| 1414 |
"Return value not allowed for multiple filtered function", |
| 1415 |
str(exc) |
| 1416 |
) |
| 1417 |
|
| 1418 |
|
| 1419 |
class TestGetInnoDBTables(db_test_base._MySQLOpportunisticTestCase): |
| 1420 |
|
| 1421 |
def test_all_tables_use_innodb(self): |
| 1422 |
with self.engine.connect() as conn, conn.begin(): |
| 1423 |
conn.execute( |
| 1424 |
sql.text( |
| 1425 |
"CREATE TABLE customers " |
| 1426 |
"(a INT, b CHAR (20), INDEX (a)) ENGINE=InnoDB")) |
| 1427 |
self.assertEqual([], utils.get_non_innodb_tables(self.engine)) |
| 1428 |
|
| 1429 |
def test_all_tables_use_innodb_false(self): |
| 1430 |
with self.engine.connect() as conn, conn.begin(): |
| 1431 |
conn.execute( |
| 1432 |
sql.text("CREATE TABLE employee (i INT) ENGINE=MEMORY") |
| 1433 |
) |
| 1434 |
self.assertEqual(['employee'], |
| 1435 |
utils.get_non_innodb_tables(self.engine)) |
| 1436 |
|
| 1437 |
def test_skip_tables_use_default_value(self): |
| 1438 |
with self.engine.connect() as conn, conn.begin(): |
| 1439 |
conn.execute( |
| 1440 |
sql.text("CREATE TABLE migrate_version (i INT) ENGINE=MEMORY") |
| 1441 |
) |
| 1442 |
self.assertEqual([], |
| 1443 |
utils.get_non_innodb_tables(self.engine)) |
| 1444 |
|
| 1445 |
def test_skip_tables_use_passed_value(self): |
| 1446 |
with self.engine.connect() as conn, conn.begin(): |
| 1447 |
conn.execute( |
| 1448 |
sql.text("CREATE TABLE some_table (i INT) ENGINE=MEMORY")) |
| 1449 |
self.assertEqual([], |
| 1450 |
utils.get_non_innodb_tables( |
| 1451 |
self.engine, skip_tables=('some_table',))) |
| 1452 |
|
| 1453 |
def test_skip_tables_use_empty_list(self): |
| 1454 |
with self.engine.connect() as conn, conn.begin(): |
| 1455 |
conn.execute( |
| 1456 |
sql.text("CREATE TABLE some_table_3 (i INT) ENGINE=MEMORY")) |
| 1457 |
self.assertEqual(['some_table_3'], |
| 1458 |
utils.get_non_innodb_tables( |
| 1459 |
self.engine, skip_tables=())) |
| 1460 |
|
| 1461 |
def test_skip_tables_use_several_values(self): |
| 1462 |
with self.engine.connect() as conn, conn.begin(): |
| 1463 |
conn.execute( |
| 1464 |
sql.text("CREATE TABLE some_table_1 (i INT) ENGINE=MEMORY")) |
| 1465 |
conn.execute( |
| 1466 |
sql.text("CREATE TABLE some_table_2 (i INT) ENGINE=MEMORY")) |
| 1467 |
self.assertEqual([], |
| 1468 |
utils.get_non_innodb_tables( |
| 1469 |
self.engine, |
| 1470 |
skip_tables=('some_table_1', 'some_table_2'))) |