Debian Codegraph @

oslo_db/tests/sqlalchemy/test_sqlalchemy.py

raw symbols SCIP
1 # Copyright (c) 2012 Rackspace Hosting
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 """Unit tests for SQLAlchemy specific code."""
17
18 import logging
19 import os
20 from unittest import mock
21
22 import fixtures
23 import sqlalchemy
24 from sqlalchemy import exc
25 from sqlalchemy.pool import NullPool
26 from sqlalchemy import sql
27 from sqlalchemy import Column, MetaData, Table
28 from sqlalchemy import Integer, String
29 from sqlalchemy.orm import declarative_base
30
31 from oslo_db import exception
32 from oslo_db.sqlalchemy import enginefacade
33 from oslo_db.sqlalchemy import engines
34 from oslo_db.sqlalchemy import models
35 from oslo_db.sqlalchemy import session
36 from oslo_db.sqlalchemy import utils
37 from oslo_db.tests import base as test_base
38 from oslo_db.tests.sqlalchemy import base as db_test_base
39
40 BASE = declarative_base()
41 _TABLE_NAME = '__tmp__test__tmp__'
42 _REGEXP_TABLE_NAME = _TABLE_NAME + "regexp"
43
44
45 class RegexpTable(BASE, models.ModelBase):
46 __tablename__ = _REGEXP_TABLE_NAME
47 id = Column(Integer, primary_key=True)
48 bar = Column(String(255))
49
50
51 class RegexpFilterTestCase(db_test_base._DbTestCase):
52
53 def setUp(self):
54 super().setUp()
55 meta = MetaData()
56 test_table = Table(_REGEXP_TABLE_NAME, meta,
57 Column('id', Integer, primary_key=True,
58 nullable=False),
59 Column('bar', String(255)))
60 test_table.create(self.engine)
61 self.addCleanup(test_table.drop, self.engine)
62
63 def _test_regexp_filter(self, regexp, expected):
64 with enginefacade.writer.using(db_test_base.context):
65 _session = db_test_base.context.session
66 for i in ['10', '20', '♥']:
67 tbl = RegexpTable()
68 tbl.update({'bar': i})
69 tbl.save(session=_session)
70
71 regexp_op = RegexpTable.bar.op('REGEXP')(regexp)
72 result = _session.query(RegexpTable).filter(regexp_op).all()
73 self.assertEqual(expected, [r.bar for r in result])
74
75 def test_regexp_filter(self):
76 self._test_regexp_filter('10', ['10'])
77
78 def test_regexp_filter_nomatch(self):
79 self._test_regexp_filter('11', [])
80
81 def test_regexp_filter_unicode(self):
82 self._test_regexp_filter('♥', ['♥'])
83
84 def test_regexp_filter_unicode_nomatch(self):
85 self._test_regexp_filter('♦', [])
86
87
88 class SQLiteSavepointTest(db_test_base._DbTestCase):
89 def setUp(self):
90 super().setUp()
91 meta = MetaData()
92 self.test_table = Table(
93 "test_table", meta,
94 Column('id', Integer, primary_key=True),
95 Column('data', String(10)))
96 self.test_table.create(self.engine)
97 self.addCleanup(self.test_table.drop, self.engine)
98
99 def test_plain_transaction(self):
100 conn = self.engine.connect()
101 trans = conn.begin()
102 conn.execute(
103 self.test_table.insert(),
104 {'data': 'data 1'}
105 )
106 self.assertEqual(
107 [(1, 'data 1')],
108 conn.execute(
109 self.test_table.select().
110 order_by(self.test_table.c.id)
111 ).fetchall()
112 )
113 trans.rollback()
114
115 with self.engine.connect() as conn:
116 self.assertEqual(
117 0,
118 conn.scalar(
119 sqlalchemy.select(
120 sqlalchemy.func.count(self.test_table.c.id),
121 ).select_from(self.test_table)
122 )
123 )
124
125 def test_savepoint_middle(self):
126 with self.engine.begin() as conn:
127 conn.execute(
128 self.test_table.insert(),
129 {'data': 'data 1'}
130 )
131
132 savepoint = conn.begin_nested()
133 conn.execute(
134 self.test_table.insert(),
135 {'data': 'data 2'}
136 )
137 savepoint.rollback()
138
139 conn.execute(
140 self.test_table.insert(),
141 {'data': 'data 3'}
142 )
143
144 self.assertEqual(
145 [(1, 'data 1'), (2, 'data 3')],
146 conn.execute(
147 self.test_table.select().
148 order_by(self.test_table.c.id)
149 ).fetchall()
150 )
151
152 def test_savepoint_beginning(self):
153 with self.engine.begin() as conn:
154 savepoint = conn.begin_nested()
155 conn.execute(
156 self.test_table.insert(),
157 {'data': 'data 1'}
158 )
159 savepoint.rollback()
160
161 conn.execute(
162 self.test_table.insert(),
163 {'data': 'data 2'}
164 )
165
166 self.assertEqual(
167 [(1, 'data 2')],
168 conn.execute(
169 self.test_table.select().
170 order_by(self.test_table.c.id)
171 ).fetchall()
172 )
173
174
175 class FakeDBAPIConnection:
176 def cursor(self):
177 return FakeCursor()
178
179
180 class FakeCursor:
181 def execute(self, sql):
182 pass
183
184
185 class FakeConnectionProxy:
186 pass
187
188
189 class FakeConnectionRec:
190 pass
191
192
193 class OperationalError(Exception):
194 pass
195
196
197 class ProgrammingError(Exception):
198 pass
199
200
201 class QueryParamTest(db_test_base._DbTestCase):
202 def _fixture(self):
203 from sqlalchemy import create_engine
204
205 def _mock_create_engine(*arg, **kw):
206 return create_engine("sqlite://")
207
208 return mock.patch(
209 "oslo_db.sqlalchemy.engines.sqlalchemy.create_engine",
210 side_effect=_mock_create_engine)
211
212 def _normalize_query_dict(self, qdict):
213 # SQLAlchemy 1.4 returns url.query as:
214 # immutabledict({k1: v1, k2: (v2a, v2b, ...), ...})
215 # that is with tuples not lists for multiparams
216
217 return {
218 k: list(v) if isinstance(v, tuple) else v
219 for k, v in qdict.items()
220 }
221
222 def test_add_assorted_params(self):
223 with self._fixture() as ce:
224 engines.create_engine(
225 "mysql+pymysql://foo:bar@bat",
226 connection_parameters="foo=bar&bat=hoho&bat=param2")
227
228 self.assertEqual(
229 self._normalize_query_dict(ce.mock_calls[0][1][0].query),
230 {'bat': ['hoho', 'param2'], 'foo': 'bar'}
231 )
232
233 def test_add_no_params(self):
234 with self._fixture() as ce:
235 engines.create_engine(
236 "mysql+pymysql://foo:bar@bat")
237
238 self.assertEqual(
239 ce.mock_calls[0][1][0].query,
240 self._normalize_query_dict({})
241 )
242
243 def test_combine_params(self):
244 with self._fixture() as ce:
245 engines.create_engine(
246 "mysql+pymysql://foo:bar@bat/"
247 "?charset=utf8&param_file=tripleo.cnf",
248 connection_parameters="plugin=sqlalchemy_collectd&"
249 "collectd_host=127.0.0.1&"
250 "bind_host=192.168.1.5")
251
252 self.assertEqual(
253 self._normalize_query_dict(ce.mock_calls[0][1][0].query),
254 {
255 'bind_host': '192.168.1.5',
256 'charset': 'utf8',
257 'collectd_host': '127.0.0.1',
258 'param_file': 'tripleo.cnf',
259 'plugin': 'sqlalchemy_collectd'
260 }
261 )
262
263 def test_combine_multi_params(self):
264 with self._fixture() as ce:
265 engines.create_engine(
266 "mysql+pymysql://foo:bar@bat/"
267 "?charset=utf8&param_file=tripleo.cnf&plugin=connmon",
268 connection_parameters="plugin=sqlalchemy_collectd&"
269 "collectd_host=127.0.0.1&"
270 "bind_host=192.168.1.5")
271
272 self.assertEqual(
273 self._normalize_query_dict(ce.mock_calls[0][1][0].query),
274 {
275 'bind_host': '192.168.1.5',
276 'charset': 'utf8',
277 'collectd_host': '127.0.0.1',
278 'param_file': 'tripleo.cnf',
279 'plugin': ['connmon', 'sqlalchemy_collectd']
280 }
281 )
282
283
284 class MySQLDefaultModeTestCase(db_test_base._MySQLOpportunisticTestCase):
285 def test_default_is_traditional(self):
286 with self.engine.connect() as conn:
287 sql_mode = conn.execute(
288 sql.text("SHOW VARIABLES LIKE 'sql_mode'")
289 ).first()[1]
290
291 self.assertIn("TRADITIONAL", sql_mode)
292
293
294 class MySQLModeTestCase(db_test_base._MySQLOpportunisticTestCase):
295
296 def __init__(self, *args, **kwargs):
297 super().__init__(*args, **kwargs)
298 # By default, run in empty SQL mode.
299 # Subclasses override this with specific modes.
300 self.mysql_mode = ''
301
302 def setUp(self):
303 super().setUp()
304 mode_engine = session.create_engine(
305 self.engine.url,
306 mysql_sql_mode=self.mysql_mode)
307 self.connection = mode_engine.connect()
308
309 meta = MetaData()
310 self.test_table = Table(_TABLE_NAME + "mode", meta,
311 Column('id', Integer, primary_key=True),
312 Column('bar', String(255)))
313 with self.connection.begin():
314 self.test_table.create(self.connection)
315
316 def cleanup():
317 with self.connection.begin():
318 self.test_table.drop(self.connection)
319 self.connection.close()
320 mode_engine.dispose()
321
322 self.addCleanup(cleanup)
323
324 def _test_string_too_long(self, value):
325 with self.connection.begin():
326 self.connection.execute(self.test_table.insert(), {'bar': value})
327 result = self.connection.execute(self.test_table.select())
328 return result.fetchone().bar
329
330 def test_string_too_long(self):
331 value = 'a' * 512
332 # String is too long.
333 # With no SQL mode set, this gets truncated.
334 self.assertNotEqual(value,
335 self._test_string_too_long(value))
336
337
338 class MySQLStrictAllTablesModeTestCase(MySQLModeTestCase):
339 "Test data integrity enforcement in MySQL STRICT_ALL_TABLES mode."
340
341 def __init__(self, *args, **kwargs):
342 super().__init__(*args, **kwargs)
343 self.mysql_mode = 'STRICT_ALL_TABLES'
344
345 def test_string_too_long(self):
346 value = 'a' * 512
347 # String is too long.
348 # With STRICT_ALL_TABLES or TRADITIONAL mode set, this is an error.
349 self.assertRaises(exception.DBError,
350 self._test_string_too_long, value)
351
352
353 class MySQLTraditionalModeTestCase(MySQLStrictAllTablesModeTestCase):
354 """Test data integrity enforcement in MySQL TRADITIONAL mode.
355
356 Since TRADITIONAL includes STRICT_ALL_TABLES, this inherits all
357 STRICT_ALL_TABLES mode tests.
358 """
359
360 def __init__(self, *args, **kwargs):
361 super().__init__(*args, **kwargs)
362 self.mysql_mode = 'TRADITIONAL'
363
364
365 class SQLiteConnectTest(test_base.BaseTestCase):
366
367 def _fixture(self, **kw):
368 return session.create_engine("sqlite://", **kw)
369
370 def test_sqlite_fk_listener(self):
371 engine = self._fixture(sqlite_fk=True)
372 with engine.connect() as conn:
373 self.assertEqual(
374 1,
375 conn.execute(
376 sql.text('pragma foreign_keys')
377 ).scalars().first(),
378 )
379
380 engine = self._fixture(sqlite_fk=False)
381
382 with engine.connect() as conn:
383 self.assertEqual(
384 0,
385 conn.execute(
386 sql.text('pragma foreign_keys')
387 ).scalars().first(),
388 )
389
390 def test_sqlite_synchronous_listener(self):
391 engine = self._fixture()
392
393 # "The default setting is synchronous=FULL." (e.g. 2)
394 # http://www.sqlite.org/pragma.html#pragma_synchronous
395 with engine.connect() as conn:
396 self.assertEqual(
397 2,
398 conn.execute(sql.text('pragma synchronous')).scalars().first(),
399 )
400
401 engine = self._fixture(sqlite_synchronous=False)
402
403 with engine.connect() as conn:
404 self.assertEqual(
405 0,
406 conn.execute(sql.text('pragma synchronous')).scalars().first(),
407 )
408
409
410 class MysqlConnectTest(db_test_base._MySQLOpportunisticTestCase):
411
412 def _fixture(self, sql_mode=None, mysql_wsrep_sync_wait=None):
413
414 kw = {}
415 if sql_mode is not None:
416 kw["mysql_sql_mode"] = sql_mode
417 if mysql_wsrep_sync_wait is not None:
418 kw["mysql_wsrep_sync_wait"] = mysql_wsrep_sync_wait
419
420 return session.create_engine(self.engine.url, **kw)
421
422 def _assert_sql_mode(self, engine, sql_mode_present, sql_mode_non_present):
423 with engine.connect() as conn:
424 mode = conn.execute(
425 sql.text("SHOW VARIABLES LIKE 'sql_mode'")
426 ).fetchone()[1]
427 self.assertIn(
428 sql_mode_present, mode
429 )
430 if sql_mode_non_present:
431 self.assertNotIn(
432 sql_mode_non_present, mode
433 )
434
435 def test_mysql_wsrep_sync_wait_listener(self):
436 with self.engine.connect() as conn:
437 try:
438 conn.execute(
439 sql.text("show variables like '%wsrep_sync_wait%'")
440 ).scalars(1).one()
441 except exc.NoResultFound:
442 self.skipTest("wsrep_sync_wait option is not available")
443
444 engine = self._fixture()
445
446 with engine.connect() as conn:
447 self.assertEqual(
448 "0",
449 conn.execute(
450 sql.text("show variables like '%wsrep_sync_wait%'")
451 ).scalars(1).one(),
452 )
453
454 for wsrep_val in (2, 1, 5):
455 engine = self._fixture(mysql_wsrep_sync_wait=wsrep_val)
456
457 with engine.connect() as conn:
458 self.assertEqual(
459 str(wsrep_val),
460 conn.execute(
461 sql.text("show variables like '%wsrep_sync_wait%'")
462 ).scalars(1).one(),
463 )
464
465 def test_set_mode_traditional(self):
466 engine = self._fixture(sql_mode='TRADITIONAL')
467 self._assert_sql_mode(engine, "TRADITIONAL", "ANSI")
468
469 def test_set_mode_ansi(self):
470 engine = self._fixture(sql_mode='ANSI')
471 self._assert_sql_mode(engine, "ANSI", "TRADITIONAL")
472
473 def test_set_mode_no_mode(self):
474 # If _mysql_set_mode_callback is called with sql_mode=None, then
475 # the SQL mode is NOT set on the connection.
476
477 # get the GLOBAL sql_mode, not the @@SESSION, so that
478 # we get what is configured for the MySQL database, as opposed
479 # to what our own session.create_engine() has set it to.
480 with self.engine.connect() as conn:
481 expected = conn.execute(
482 sql.text("SELECT @@GLOBAL.sql_mode")
483 ).scalar()
484
485 engine = self._fixture(sql_mode=None)
486 self._assert_sql_mode(engine, expected, None)
487
488 def test_fail_detect_mode(self):
489 # If "SHOW VARIABLES LIKE 'sql_mode'" results in no row, then
490 # we get a log indicating can't detect the mode.
491
492 log = self.useFixture(fixtures.FakeLogger(level=logging.WARN))
493
494 mysql_conn = self.engine.raw_connection()
495 self.addCleanup(mysql_conn.close)
496 mysql_conn.detach()
497 mysql_cursor = mysql_conn.cursor()
498
499 def execute(statement, parameters=()):
500 if "SHOW VARIABLES LIKE 'sql_mode'" in statement:
501 statement = "SHOW VARIABLES LIKE 'i_dont_exist'"
502 return mysql_cursor.execute(statement, parameters)
503
504 test_engine = sqlalchemy.create_engine(self.engine.url,
505 _initialize=False)
506
507 with mock.patch.object(
508 test_engine.pool, '_creator',
509 mock.Mock(
510 return_value=mock.Mock(
511 cursor=mock.Mock(
512 return_value=mock.Mock(
513 execute=execute,
514 fetchone=mysql_cursor.fetchone,
515 fetchall=mysql_cursor.fetchall
516 )
517 )
518 )
519 )
520 ):
521 engines._init_events.dispatch_on_drivername("mysql")(test_engine)
522
523 test_engine.raw_connection()
524 self.assertIn('Unable to detect effective SQL mode',
525 log.output)
526
527 def test_logs_real_mode(self):
528 # If "SHOW VARIABLES LIKE 'sql_mode'" results in a value, then
529 # we get a log with the value.
530
531 log = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
532
533 engine = self._fixture(sql_mode='TRADITIONAL')
534
535 with engine.connect() as conn:
536 actual_mode = conn.execute(
537 sql.text("SHOW VARIABLES LIKE 'sql_mode'")
538 ).fetchone()[1]
539
540 self.assertIn('MySQL server mode set to %s' % actual_mode,
541 log.output)
542
543 def test_warning_when_not_traditional(self):
544 # If "SHOW VARIABLES LIKE 'sql_mode'" results in a value that doesn't
545 # include 'TRADITIONAL', then a warning is logged.
546
547 log = self.useFixture(fixtures.FakeLogger(level=logging.WARN))
548 self._fixture(sql_mode='ANSI')
549
550 self.assertIn("consider enabling TRADITIONAL or STRICT_ALL_TABLES",
551 log.output)
552
553 def test_no_warning_when_traditional(self):
554 # If "SHOW VARIABLES LIKE 'sql_mode'" results in a value that includes
555 # 'TRADITIONAL', then no warning is logged.
556
557 log = self.useFixture(fixtures.FakeLogger(level=logging.WARN))
558 self._fixture(sql_mode='TRADITIONAL')
559
560 self.assertNotIn("consider enabling TRADITIONAL or STRICT_ALL_TABLES",
561 log.output)
562
563 def test_no_warning_when_strict_all_tables(self):
564 # If "SHOW VARIABLES LIKE 'sql_mode'" results in a value that includes
565 # 'STRICT_ALL_TABLES', then no warning is logged.
566
567 log = self.useFixture(fixtures.FakeLogger(level=logging.WARN))
568 self._fixture(sql_mode='TRADITIONAL')
569
570 self.assertNotIn("consider enabling TRADITIONAL or STRICT_ALL_TABLES",
571 log.output)
572
573
574 class CreateEngineTest(test_base.BaseTestCase):
575 """Test that dialect-specific arguments/ listeners are set up correctly.
576
577 """
578
579 def setUp(self):
580 super().setUp()
581 self.args = {'connect_args': {}}
582
583 def test_queuepool_args(self):
584 engines._init_connection_args(
585 utils.make_url("mysql+pymysql://u:p@host/test"),
586 self.args,
587 {'max_pool_size': 10, 'max_overflow': 10},
588 )
589 self.assertEqual(10, self.args['pool_size'])
590 self.assertEqual(10, self.args['max_overflow'])
591
592 def test_sqlite_memory_pool_args(self):
593 for _url in ("sqlite://", "sqlite:///:memory:"):
594 engines._init_connection_args(
595 utils.make_url(_url),
596 self.args,
597 {'max_pool_size': 10, 'max_overflow': 10},
598 )
599
600 # queuepool arguments are not present
601 self.assertNotIn('pool_size', self.args)
602 self.assertNotIn('max_overflow', self.args)
603
604 self.assertEqual(False,
605 self.args['connect_args']['check_same_thread'])
606
607 # due to memory connection
608 self.assertIn('poolclass', self.args)
609
610 def test_sqlite_file_pool_args(self):
611 engines._init_connection_args(
612 utils.make_url("sqlite:///somefile.db"),
613 self.args,
614 {'max_pool_size': 10, 'max_overflow': 10},
615 )
616
617 # queuepool arguments are not peresnet
618 self.assertNotIn('pool_size', self.args)
619 self.assertNotIn(
620 'max_overflow', self.args)
621
622 self.assertFalse(self.args['connect_args'])
623 self.assertIs(self.args["poolclass"], NullPool)
624
625 def _test_mysql_connect_args_default(self, connect_args):
626 self.assertEqual({'charset': 'utf8', 'use_unicode': 1},
627 connect_args)
628
629 def test_mysql_connect_args_default(self):
630 engines._init_connection_args(
631 utils.make_url("mysql://u:p@host/test"), self.args, {})
632 self._test_mysql_connect_args_default(self.args['connect_args'])
633
634 def test_mysql_pymysql_connect_args_default(self):
635 engines._init_connection_args(
636 utils.make_url("mysql+pymysql://u:p@host/test"), self.args, {})
637 self.assertEqual({'charset': 'utf8'}, self.args['connect_args'])
638
639 def test_mysql_mysqldb_connect_args_default(self):
640 engines._init_connection_args(
641 utils.make_url("mysql+mysqldb://u:p@host/test"), self.args, {})
642 self._test_mysql_connect_args_default(self.args['connect_args'])
643
644 def test_postgresql_connect_args_default(self):
645 engines._init_connection_args(
646 utils.make_url("postgresql://u:p@host/test"), self.args, {})
647 self.assertEqual('utf8', self.args['client_encoding'])
648 self.assertFalse(self.args['connect_args'])
649
650 def test_mysqlconnector_raise_on_warnings_default(self):
651 engines._init_connection_args(
652 utils.make_url("mysql+mysqlconnector://u:p@host/test"),
653 self.args, {})
654 self.assertEqual(False, self.args['connect_args']['raise_on_warnings'])
655
656 def test_mysqlconnector_raise_on_warnings_override(self):
657 engines._init_connection_args(
658 utils.make_url(
659 "mysql+mysqlconnector://u:p@host/test"
660 "?raise_on_warnings=true"),
661 self.args, {}
662 )
663
664 self.assertNotIn('raise_on_warnings', self.args['connect_args'])
665
666 def test_thread_checkin(self):
667 with mock.patch("sqlalchemy.event.listens_for"):
668 with mock.patch("sqlalchemy.event.listen") as listen_evt:
669 engines._init_events.dispatch_on_drivername(
670 "sqlite")(mock.Mock())
671
672 self.assertEqual(
673 listen_evt.mock_calls[0][1][-1],
674 engines._thread_yield
675 )
676
677 def test_warn_on_missing_driver(self):
678
679 warnings = mock.Mock()
680
681 def warn_interpolate(msg, args):
682 # test the interpolation itself to ensure the password
683 # is concealed
684 warnings.warning(msg % (args, ))
685
686 with mock.patch(
687 "oslo_db.sqlalchemy.engines.LOG.warning",
688 warn_interpolate):
689
690 engines._vet_url(
691 utils.make_url("mysql://scott:tiger@some_host/some_db"))
692 engines._vet_url(utils.make_url(
693 "mysql+mysqldb://scott:tiger@some_host/some_db"))
694 engines._vet_url(utils.make_url(
695 "mysql+pymysql://scott:tiger@some_host/some_db"))
696 engines._vet_url(utils.make_url(
697 "postgresql+psycopg2://scott:tiger@some_host/some_db"))
698 engines._vet_url(utils.make_url(
699 "postgresql://scott:tiger@some_host/some_db"))
700
701 self.assertEqual(
702 [
703 mock.call.warning(
704 "URL mysql://scott:***@some_host/some_db does not contain "
705 "a '+drivername' portion, "
706 "and will make use of a default driver. "
707 "A full dbname+drivername:// protocol is recommended. "
708 "For MySQL, it is strongly recommended that "
709 "mysql+pymysql:// "
710 "be specified for maximum service compatibility",
711
712 ),
713 mock.call.warning(
714 "URL postgresql://scott:***@some_host/some_db does not "
715 "contain a '+drivername' portion, "
716 "and will make use of a default driver. "
717 "A full dbname+drivername:// protocol is recommended."
718 )
719 ],
720 warnings.mock_calls
721 )
722
723
724 class ProcessGuardTest(db_test_base._DbTestCase):
725 def test_process_guard(self):
726 self.engine.dispose()
727
728 def get_parent_pid():
729 return 4
730
731 def get_child_pid():
732 return 5
733
734 with mock.patch("os.getpid", get_parent_pid):
735 with self.engine.connect() as conn:
736 dbapi_id = id(conn.connection.driver_connection)
737
738 with mock.patch("os.getpid", get_child_pid):
739 with self.engine.connect() as conn:
740 new_dbapi_id = id(conn.connection.driver_connection)
741
742 self.assertNotEqual(dbapi_id, new_dbapi_id)
743
744 # ensure it doesn't trip again
745 with mock.patch("os.getpid", get_child_pid):
746 with self.engine.connect() as conn:
747 newer_dbapi_id = id(conn.connection.driver_connection)
748
749 self.assertEqual(new_dbapi_id, newer_dbapi_id)
750
751
752 class PatchStacktraceTest(db_test_base._DbTestCase):
753
754 def test_trace(self):
755 engine = self.engine
756
757 # NOTE(viktors): The code in oslo_db.sqlalchemy.session filters out
758 # lines from modules under oslo_db, so we should remove
759 # "oslo_db/" from file path in traceback.
760 import traceback
761 orig_extract_stack = traceback.extract_stack
762
763 def extract_stack():
764 return [(row[0].replace("oslo_db/", ""), row[1], row[2], row[3])
765 for row in orig_extract_stack()]
766
767 with mock.patch("traceback.extract_stack", side_effect=extract_stack):
768
769 engines._add_trace_comments(engine)
770 conn = engine.connect()
771 orig_do_exec = engine.dialect.do_execute
772 with mock.patch.object(engine.dialect, "do_execute") as mock_exec:
773
774 mock_exec.side_effect = orig_do_exec
775 conn.execute(sql.text("select 1"))
776
777 call = mock_exec.mock_calls[0]
778
779 # we're the caller, see that we're in there
780 caller = os.path.join("tests", "sqlalchemy", "test_sqlalchemy.py")
781 self.assertIn(caller, call[1][1])