SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. sqlalchemy/__init__.py +298 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +89 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4166 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +220 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +698 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  21. sqlalchemy/dialects/mysql/base.py +3877 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3977 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1601 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +158 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +909 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +368 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +229 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1323 -0
  50. sqlalchemy/dialects/postgresql/base.py +5789 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +593 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +423 -0
  55. sqlalchemy/dialects/postgresql/json.py +408 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  57. sqlalchemy/dialects/postgresql/operators.py +130 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +670 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  60. sqlalchemy/dialects/postgresql/provision.py +184 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +799 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  68. sqlalchemy/dialects/sqlite/base.py +3063 -0
  69. sqlalchemy/dialects/sqlite/dml.py +279 -0
  70. sqlalchemy/dialects/sqlite/json.py +100 -0
  71. sqlalchemy/dialects/sqlite/provision.py +229 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +161 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp313t-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp313t-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +633 -0
  80. sqlalchemy/engine/_row_cy.cp313t-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp313t-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3354 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2421 -0
  88. sqlalchemy/engine/default.py +2402 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3495 -0
  91. sqlalchemy/engine/mock.py +134 -0
  92. sqlalchemy/engine/processors.py +82 -0
  93. sqlalchemy/engine/reflection.py +2100 -0
  94. sqlalchemy/engine/result.py +1966 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +156 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +674 -0
  102. sqlalchemy/event/base.py +472 -0
  103. sqlalchemy/event/legacy.py +258 -0
  104. sqlalchemy/event/registry.py +390 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +922 -0
  107. sqlalchemy/ext/__init__.py +11 -0
  108. sqlalchemy/ext/associationproxy.py +2072 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2007 -0
  116. sqlalchemy/ext/automap.py +1701 -0
  117. sqlalchemy/ext/baked.py +559 -0
  118. sqlalchemy/ext/compiler.py +600 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +560 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +439 -0
  127. sqlalchemy/ext/serializer.py +185 -0
  128. sqlalchemy/future/__init__.py +16 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +174 -0
  131. sqlalchemy/log.py +283 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +179 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +976 -0
  137. sqlalchemy/orm/bulk_persistence.py +2152 -0
  138. sqlalchemy/orm/clsregistry.py +582 -0
  139. sqlalchemy/orm/collections.py +1568 -0
  140. sqlalchemy/orm/context.py +3471 -0
  141. sqlalchemy/orm/decl_api.py +2280 -0
  142. sqlalchemy/orm/decl_base.py +2309 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +307 -0
  146. sqlalchemy/orm/evaluator.py +379 -0
  147. sqlalchemy/orm/events.py +3386 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +746 -0
  151. sqlalchemy/orm/interfaces.py +1589 -0
  152. sqlalchemy/orm/loading.py +1684 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4411 -0
  155. sqlalchemy/orm/path_registry.py +829 -0
  156. sqlalchemy/orm/persistence.py +1789 -0
  157. sqlalchemy/orm/properties.py +973 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3570 -0
  160. sqlalchemy/orm/scoping.py +2232 -0
  161. sqlalchemy/orm/session.py +5403 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3492 -0
  165. sqlalchemy/orm/strategy_options.py +2562 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +798 -0
  168. sqlalchemy/orm/util.py +2438 -0
  169. sqlalchemy/orm/writeonly.py +694 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1522 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +582 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +74 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +397 -0
  178. sqlalchemy/sql/_dml_constructors.py +132 -0
  179. sqlalchemy/sql/_elements_constructors.py +2164 -0
  180. sqlalchemy/sql/_orm_types.py +20 -0
  181. sqlalchemy/sql/_selectable_constructors.py +840 -0
  182. sqlalchemy/sql/_typing.py +487 -0
  183. sqlalchemy/sql/_util_cy.cp313t-win_arm64.pyd +0 -0
  184. sqlalchemy/sql/_util_cy.py +127 -0
  185. sqlalchemy/sql/annotation.py +590 -0
  186. sqlalchemy/sql/base.py +2699 -0
  187. sqlalchemy/sql/cache_key.py +1066 -0
  188. sqlalchemy/sql/coercions.py +1373 -0
  189. sqlalchemy/sql/compiler.py +8327 -0
  190. sqlalchemy/sql/crud.py +1815 -0
  191. sqlalchemy/sql/ddl.py +1928 -0
  192. sqlalchemy/sql/default_comparator.py +654 -0
  193. sqlalchemy/sql/dml.py +1977 -0
  194. sqlalchemy/sql/elements.py +6033 -0
  195. sqlalchemy/sql/events.py +458 -0
  196. sqlalchemy/sql/expression.py +172 -0
  197. sqlalchemy/sql/functions.py +2305 -0
  198. sqlalchemy/sql/lambdas.py +1443 -0
  199. sqlalchemy/sql/naming.py +209 -0
  200. sqlalchemy/sql/operators.py +2897 -0
  201. sqlalchemy/sql/roles.py +332 -0
  202. sqlalchemy/sql/schema.py +6703 -0
  203. sqlalchemy/sql/selectable.py +7553 -0
  204. sqlalchemy/sql/sqltypes.py +4093 -0
  205. sqlalchemy/sql/traversals.py +1042 -0
  206. sqlalchemy/sql/type_api.py +2446 -0
  207. sqlalchemy/sql/util.py +1495 -0
  208. sqlalchemy/sql/visitors.py +1157 -0
  209. sqlalchemy/testing/__init__.py +96 -0
  210. sqlalchemy/testing/assertions.py +1007 -0
  211. sqlalchemy/testing/assertsql.py +519 -0
  212. sqlalchemy/testing/asyncio.py +128 -0
  213. sqlalchemy/testing/config.py +440 -0
  214. sqlalchemy/testing/engines.py +483 -0
  215. sqlalchemy/testing/entities.py +117 -0
  216. sqlalchemy/testing/exclusions.py +476 -0
  217. sqlalchemy/testing/fixtures/__init__.py +30 -0
  218. sqlalchemy/testing/fixtures/base.py +384 -0
  219. sqlalchemy/testing/fixtures/mypy.py +247 -0
  220. sqlalchemy/testing/fixtures/orm.py +227 -0
  221. sqlalchemy/testing/fixtures/sql.py +538 -0
  222. sqlalchemy/testing/pickleable.py +155 -0
  223. sqlalchemy/testing/plugin/__init__.py +6 -0
  224. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  225. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  226. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  227. sqlalchemy/testing/profiling.py +329 -0
  228. sqlalchemy/testing/provision.py +613 -0
  229. sqlalchemy/testing/requirements.py +1978 -0
  230. sqlalchemy/testing/schema.py +198 -0
  231. sqlalchemy/testing/suite/__init__.py +19 -0
  232. sqlalchemy/testing/suite/test_cte.py +237 -0
  233. sqlalchemy/testing/suite/test_ddl.py +420 -0
  234. sqlalchemy/testing/suite/test_dialect.py +776 -0
  235. sqlalchemy/testing/suite/test_insert.py +630 -0
  236. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  237. sqlalchemy/testing/suite/test_results.py +660 -0
  238. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  239. sqlalchemy/testing/suite/test_select.py +2112 -0
  240. sqlalchemy/testing/suite/test_sequence.py +317 -0
  241. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  242. sqlalchemy/testing/suite/test_types.py +2271 -0
  243. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  244. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  245. sqlalchemy/testing/util.py +535 -0
  246. sqlalchemy/testing/warnings.py +52 -0
  247. sqlalchemy/types.py +76 -0
  248. sqlalchemy/util/__init__.py +158 -0
  249. sqlalchemy/util/_collections.py +688 -0
  250. sqlalchemy/util/_collections_cy.cp313t-win_arm64.pyd +0 -0
  251. sqlalchemy/util/_collections_cy.pxd +8 -0
  252. sqlalchemy/util/_collections_cy.py +516 -0
  253. sqlalchemy/util/_has_cython.py +46 -0
  254. sqlalchemy/util/_immutabledict_cy.cp313t-win_arm64.pyd +0 -0
  255. sqlalchemy/util/_immutabledict_cy.py +240 -0
  256. sqlalchemy/util/compat.py +299 -0
  257. sqlalchemy/util/concurrency.py +322 -0
  258. sqlalchemy/util/cython.py +79 -0
  259. sqlalchemy/util/deprecations.py +401 -0
  260. sqlalchemy/util/langhelpers.py +2320 -0
  261. sqlalchemy/util/preloaded.py +152 -0
  262. sqlalchemy/util/queue.py +304 -0
  263. sqlalchemy/util/tool_support.py +201 -0
  264. sqlalchemy/util/topological.py +120 -0
  265. sqlalchemy/util/typing.py +711 -0
  266. sqlalchemy-2.1.0b2.dist-info/METADATA +269 -0
  267. sqlalchemy-2.1.0b2.dist-info/RECORD +270 -0
  268. sqlalchemy-2.1.0b2.dist-info/WHEEL +5 -0
  269. sqlalchemy-2.1.0b2.dist-info/licenses/LICENSE +19 -0
  270. sqlalchemy-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1007 @@
1
+ # testing/assertions.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import defaultdict
13
+ import contextlib
14
+ from copy import copy
15
+ from itertools import filterfalse
16
+ import re
17
+ import sys
18
+ import warnings
19
+
20
+ from . import assertsql
21
+ from . import config
22
+ from . import engines
23
+ from . import mock
24
+ from .exclusions import db_spec
25
+ from .util import fail
26
+ from .. import exc as sa_exc
27
+ from .. import schema
28
+ from .. import sql
29
+ from .. import types as sqltypes
30
+ from .. import util
31
+ from ..engine import default
32
+ from ..engine import url
33
+ from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
34
+ from ..util import decorator
35
+
36
+
37
+ def expect_warnings(*messages, **kw):
38
+ """Context manager which expects one or more warnings.
39
+
40
+ With no arguments, squelches all SAWarning emitted via
41
+ sqlalchemy.util.warn and sqlalchemy.util.warn_limited. Otherwise
42
+ pass string expressions that will match selected warnings via regex;
43
+ all non-matching warnings are sent through.
44
+
45
+ The expect version **asserts** that the warnings were in fact seen.
46
+
47
+ Note that the test suite sets SAWarning warnings to raise exceptions.
48
+
49
+ """ # noqa
50
+ return _expect_warnings_sqla_only(sa_exc.SAWarning, messages, **kw)
51
+
52
+
53
+ @contextlib.contextmanager
54
+ def expect_warnings_on(db, *messages, **kw):
55
+ """Context manager which expects one or more warnings on specific
56
+ dialects.
57
+
58
+ The expect version **asserts** that the warnings were in fact seen.
59
+
60
+ """
61
+ spec = db_spec(db)
62
+
63
+ if isinstance(db, str) and not spec(config._current):
64
+ yield
65
+ else:
66
+ with expect_warnings(*messages, **kw):
67
+ yield
68
+
69
+
70
+ def emits_warning(*messages):
71
+ """Decorator form of expect_warnings().
72
+
73
+ Note that emits_warning does **not** assert that the warnings
74
+ were in fact seen.
75
+
76
+ """
77
+
78
+ @decorator
79
+ def decorate(fn, *args, **kw):
80
+ with expect_warnings(assert_=False, *messages):
81
+ return fn(*args, **kw)
82
+
83
+ return decorate
84
+
85
+
86
+ def expect_deprecated(*messages, **kw):
87
+ return _expect_warnings_sqla_only(
88
+ sa_exc.SADeprecationWarning, messages, **kw
89
+ )
90
+
91
+
92
+ def expect_noload_deprecation():
93
+ return expect_deprecated(
94
+ r"The (?:``noload`` loader strategy|noload\(\) option) is deprecated."
95
+ )
96
+
97
+
98
+ def expect_deprecated_20(*messages, **kw):
99
+ return _expect_warnings_sqla_only(
100
+ sa_exc.Base20DeprecationWarning, messages, **kw
101
+ )
102
+
103
+
104
+ def emits_warning_on(db, *messages):
105
+ """Mark a test as emitting a warning on a specific dialect.
106
+
107
+ With no arguments, squelches all SAWarning failures. Or pass one or more
108
+ strings; these will be matched to the root of the warning description by
109
+ warnings.filterwarnings().
110
+
111
+ Note that emits_warning_on does **not** assert that the warnings
112
+ were in fact seen.
113
+
114
+ """
115
+
116
+ @decorator
117
+ def decorate(fn, *args, **kw):
118
+ with expect_warnings_on(db, assert_=False, *messages):
119
+ return fn(*args, **kw)
120
+
121
+ return decorate
122
+
123
+
124
+ def uses_deprecated(*messages):
125
+ """Mark a test as immune from fatal deprecation warnings.
126
+
127
+ With no arguments, squelches all SADeprecationWarning failures.
128
+ Or pass one or more strings; these will be matched to the root
129
+ of the warning description by warnings.filterwarnings().
130
+
131
+ As a special case, you may pass a function name prefixed with //
132
+ and it will be re-written as needed to match the standard warning
133
+ verbiage emitted by the sqlalchemy.util.deprecated decorator.
134
+
135
+ Note that uses_deprecated does **not** assert that the warnings
136
+ were in fact seen.
137
+
138
+ """
139
+
140
+ @decorator
141
+ def decorate(fn, *args, **kw):
142
+ with expect_deprecated(*messages, assert_=False):
143
+ return fn(*args, **kw)
144
+
145
+ return decorate
146
+
147
+
148
+ _FILTERS = None
149
+ _SEEN = None
150
+ _EXC_CLS = None
151
+
152
+
153
+ def _expect_warnings_sqla_only(
154
+ exc_cls,
155
+ messages,
156
+ regex=True,
157
+ search_msg=False,
158
+ assert_=True,
159
+ ):
160
+ """SQLAlchemy internal use only _expect_warnings().
161
+
162
+ Alembic is using _expect_warnings() directly, and should be updated
163
+ to use this new interface.
164
+
165
+ """
166
+ return _expect_warnings(
167
+ exc_cls,
168
+ messages,
169
+ regex=regex,
170
+ search_msg=search_msg,
171
+ assert_=assert_,
172
+ raise_on_any_unexpected=True,
173
+ )
174
+
175
+
176
+ @contextlib.contextmanager
177
+ def _expect_warnings(
178
+ exc_cls,
179
+ messages,
180
+ regex=True,
181
+ search_msg=False,
182
+ assert_=True,
183
+ raise_on_any_unexpected=False,
184
+ squelch_other_warnings=False,
185
+ ):
186
+ global _FILTERS, _SEEN, _EXC_CLS
187
+
188
+ if regex or search_msg:
189
+ filters = [re.compile(msg, re.I | re.S) for msg in messages]
190
+ else:
191
+ filters = list(messages)
192
+
193
+ if _FILTERS is not None:
194
+ # nested call; update _FILTERS and _SEEN, return. outer
195
+ # block will assert our messages
196
+ assert _SEEN is not None
197
+ assert _EXC_CLS is not None
198
+ _FILTERS.extend(filters)
199
+ _SEEN.update(filters)
200
+ _EXC_CLS += (exc_cls,)
201
+ yield
202
+ else:
203
+ seen = _SEEN = set(filters)
204
+ _FILTERS = filters
205
+ _EXC_CLS = (exc_cls,)
206
+
207
+ if raise_on_any_unexpected:
208
+
209
+ def real_warn(msg, *arg, **kw):
210
+ if isinstance(msg, sa_exc.SATestSuiteWarning):
211
+ warnings.warn(msg, *arg, **kw)
212
+ else:
213
+ raise AssertionError("Got unexpected warning: %r" % msg)
214
+
215
+ else:
216
+ real_warn = warnings.warn
217
+
218
+ def our_warn(msg, *arg, **kw):
219
+ if isinstance(msg, _EXC_CLS):
220
+ exception = type(msg)
221
+ msg = str(msg)
222
+ elif arg:
223
+ exception = arg[0]
224
+ else:
225
+ exception = None
226
+
227
+ if not exception or not issubclass(exception, _EXC_CLS):
228
+ if not squelch_other_warnings:
229
+ return real_warn(msg, *arg, **kw)
230
+ else:
231
+ return
232
+
233
+ if not filters and not raise_on_any_unexpected:
234
+ return
235
+
236
+ for filter_ in filters:
237
+ if (
238
+ (search_msg and filter_.search(msg))
239
+ or (regex and filter_.match(msg))
240
+ or (not regex and filter_ == msg)
241
+ ):
242
+ seen.discard(filter_)
243
+ break
244
+ else:
245
+ if not squelch_other_warnings:
246
+ real_warn(msg, *arg, **kw)
247
+
248
+ with mock.patch("warnings.warn", our_warn):
249
+ try:
250
+ yield
251
+ finally:
252
+ _SEEN = _FILTERS = _EXC_CLS = None
253
+
254
+ if assert_:
255
+ assert not seen, "Warnings were not seen: %s" % ", ".join(
256
+ "%r" % (s.pattern if regex else s) for s in seen
257
+ )
258
+
259
+
260
+ def global_cleanup_assertions():
261
+ """Check things that have to be finalized at the end of a test suite.
262
+
263
+ Hardcoded at the moment, a modular system can be built here
264
+ to support things like PG prepared transactions, tables all
265
+ dropped, etc.
266
+
267
+ """
268
+ _assert_no_stray_pool_connections()
269
+
270
+
271
+ def _assert_no_stray_pool_connections():
272
+ engines.testing_reaper.assert_all_closed()
273
+
274
+
275
+ def int_within_variance(expected, received, variance):
276
+ deviance = int(expected * variance)
277
+ assert (
278
+ abs(received - expected) < deviance
279
+ ), "Given int value %s is not within %d%% of expected value %s" % (
280
+ received,
281
+ variance * 100,
282
+ expected,
283
+ )
284
+
285
+
286
+ def eq_regex(a, b, msg=None, flags=0):
287
+ assert re.match(b, a, flags), msg or "%r !~ %r" % (a, b)
288
+
289
+
290
+ def eq_(a, b, msg=None):
291
+ """Assert a == b, with repr messaging on failure."""
292
+ assert a == b, msg or "%r != %r" % (a, b)
293
+
294
+
295
+ def ne_(a, b, msg=None):
296
+ """Assert a != b, with repr messaging on failure."""
297
+ assert a != b, msg or "%r == %r" % (a, b)
298
+
299
+
300
+ def le_(a, b, msg=None):
301
+ """Assert a <= b, with repr messaging on failure."""
302
+ assert a <= b, msg or "%r != %r" % (a, b)
303
+
304
+
305
+ def is_instance_of(a, b, msg=None):
306
+ assert isinstance(a, b), msg or "%r is not an instance of %r" % (a, b)
307
+
308
+
309
+ def is_none(a, msg=None):
310
+ is_(a, None, msg=msg)
311
+
312
+
313
+ def is_not_none(a, msg=None):
314
+ is_not(a, None, msg=msg)
315
+
316
+
317
+ def is_true(a, msg=None):
318
+ is_(bool(a), True, msg=msg)
319
+
320
+
321
+ def is_false(a, msg=None):
322
+ is_(bool(a), False, msg=msg)
323
+
324
+
325
+ def is_(a, b, msg=None):
326
+ """Assert a is b, with repr messaging on failure."""
327
+ assert a is b, msg or "%r is not %r" % (a, b)
328
+
329
+
330
+ def is_not(a, b, msg=None):
331
+ """Assert a is not b, with repr messaging on failure."""
332
+ assert a is not b, msg or "%r is %r" % (a, b)
333
+
334
+
335
+ # deprecated. See #5429
336
+ is_not_ = is_not
337
+
338
+
339
+ def in_(a, b, msg=None):
340
+ """Assert a in b, with repr messaging on failure."""
341
+ assert a in b, msg or "%r not in %r" % (a, b)
342
+
343
+
344
+ def not_in(a, b, msg=None):
345
+ """Assert a in not b, with repr messaging on failure."""
346
+ assert a not in b, msg or "%r is in %r" % (a, b)
347
+
348
+
349
+ # deprecated. See #5429
350
+ not_in_ = not_in
351
+
352
+
353
+ def startswith_(a, fragment, msg=None):
354
+ """Assert a.startswith(fragment), with repr messaging on failure."""
355
+ assert a.startswith(fragment), msg or "%r does not start with %r" % (
356
+ a,
357
+ fragment,
358
+ )
359
+
360
+
361
+ def eq_ignore_whitespace(a, b, msg=None):
362
+ a = re.sub(r"^\s+?|\n", "", a)
363
+ a = re.sub(r" {2,}", " ", a)
364
+ a = re.sub(r"\t", "", a)
365
+ b = re.sub(r"^\s+?|\n", "", b)
366
+ b = re.sub(r" {2,}", " ", b)
367
+ b = re.sub(r"\t", "", b)
368
+
369
+ assert a == b, msg or "%r != %r" % (a, b)
370
+
371
+
372
+ def _assert_proper_exception_context(exception):
373
+ """assert that any exception we're catching does not have a __context__
374
+ without a __cause__, and that __suppress_context__ is never set.
375
+
376
+ Python 3 will report nested as exceptions as "during the handling of
377
+ error X, error Y occurred". That's not what we want to do. we want
378
+ these exceptions in a cause chain.
379
+
380
+ """
381
+
382
+ if (
383
+ exception.__context__ is not exception.__cause__
384
+ and not exception.__suppress_context__
385
+ ):
386
+ assert False, (
387
+ "Exception %r was correctly raised but did not set a cause, "
388
+ "within context %r as its cause."
389
+ % (exception, exception.__context__)
390
+ )
391
+
392
+
393
+ def assert_raises(except_cls, callable_, *args, **kw):
394
+ return _assert_raises(except_cls, callable_, args, kw, check_context=True)
395
+
396
+
397
+ def assert_raises_context_ok(except_cls, callable_, *args, **kw):
398
+ return _assert_raises(except_cls, callable_, args, kw)
399
+
400
+
401
+ def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
402
+ return _assert_raises(
403
+ except_cls, callable_, args, kwargs, msg=msg, check_context=True
404
+ )
405
+
406
+
407
+ def assert_warns(except_cls, callable_, *args, **kwargs):
408
+ """legacy adapter function for functions that were previously using
409
+ assert_raises with SAWarning or similar.
410
+
411
+ has some workarounds to accommodate the fact that the callable completes
412
+ with this approach rather than stopping at the exception raise.
413
+
414
+
415
+ """
416
+ with _expect_warnings_sqla_only(except_cls, [".*"]):
417
+ return callable_(*args, **kwargs)
418
+
419
+
420
+ def assert_warns_message(except_cls, msg, callable_, *args, **kwargs):
421
+ """legacy adapter function for functions that were previously using
422
+ assert_raises with SAWarning or similar.
423
+
424
+ has some workarounds to accommodate the fact that the callable completes
425
+ with this approach rather than stopping at the exception raise.
426
+
427
+ Also uses regex.search() to match the given message to the error string
428
+ rather than regex.match().
429
+
430
+ """
431
+ with _expect_warnings_sqla_only(
432
+ except_cls,
433
+ [msg],
434
+ search_msg=True,
435
+ regex=False,
436
+ ):
437
+ return callable_(*args, **kwargs)
438
+
439
+
440
+ def assert_raises_message_context_ok(
441
+ except_cls, msg, callable_, *args, **kwargs
442
+ ):
443
+ return _assert_raises(except_cls, callable_, args, kwargs, msg=msg)
444
+
445
+
446
+ def _assert_raises(
447
+ except_cls, callable_, args, kwargs, msg=None, check_context=False
448
+ ):
449
+ with _expect_raises(except_cls, msg, check_context) as ec:
450
+ callable_(*args, **kwargs)
451
+ return ec.error
452
+
453
+
454
+ class _ErrorContainer:
455
+ error = None
456
+
457
+
458
+ @contextlib.contextmanager
459
+ def _expect_raises(except_cls, msg=None, check_context=False):
460
+ if (
461
+ isinstance(except_cls, type)
462
+ and issubclass(except_cls, Warning)
463
+ or isinstance(except_cls, Warning)
464
+ ):
465
+ raise TypeError(
466
+ "Use expect_warnings for warnings, not "
467
+ "expect_raises / assert_raises"
468
+ )
469
+ ec = _ErrorContainer()
470
+ if check_context:
471
+ are_we_already_in_a_traceback = sys.exc_info()[0]
472
+ try:
473
+ yield ec
474
+ success = False
475
+ except except_cls as err:
476
+ ec.error = err
477
+ success = True
478
+ if msg is not None:
479
+ # I'm often pdbing here, and "err" above isn't
480
+ # in scope, so assign the string explicitly
481
+ error_as_string = str(err)
482
+ assert re.search(msg, error_as_string, re.UNICODE), "%r !~ %s" % (
483
+ msg,
484
+ error_as_string,
485
+ )
486
+ if check_context and not are_we_already_in_a_traceback:
487
+ _assert_proper_exception_context(err)
488
+ print(str(err).encode("utf-8"))
489
+
490
+ # it's generally a good idea to not carry traceback objects outside
491
+ # of the except: block, but in this case especially we seem to have
492
+ # hit some bug in either python 3.10.0b2 or greenlet or both which
493
+ # this seems to fix:
494
+ # https://github.com/python-greenlet/greenlet/issues/242
495
+ del ec
496
+
497
+ # assert outside the block so it works for AssertionError too !
498
+ assert success, "Callable did not raise an exception"
499
+
500
+
501
+ def expect_raises(except_cls, check_context=True):
502
+ return _expect_raises(except_cls, check_context=check_context)
503
+
504
+
505
+ def expect_raises_message(except_cls, msg, check_context=True):
506
+ return _expect_raises(except_cls, msg=msg, check_context=check_context)
507
+
508
+
509
+ class AssertsCompiledSQL:
510
+ def assert_compile(
511
+ self,
512
+ clause,
513
+ result,
514
+ params=None,
515
+ checkparams=None,
516
+ for_executemany=False,
517
+ check_literal_execute=None,
518
+ check_post_param=None,
519
+ dialect=None,
520
+ checkpositional=None,
521
+ check_prefetch=None,
522
+ use_default_dialect=False,
523
+ allow_dialect_select=False,
524
+ supports_default_values=True,
525
+ supports_native_boolean=False,
526
+ supports_default_metavalue=True,
527
+ literal_binds=False,
528
+ render_postcompile=False,
529
+ schema_translate_map=None,
530
+ render_schema_translate=False,
531
+ default_schema_name=None,
532
+ from_linting=False,
533
+ check_param_order=True,
534
+ use_literal_execute_for_simple_int=False,
535
+ ):
536
+ if use_default_dialect:
537
+ dialect = default.DefaultDialect()
538
+ dialect.supports_default_values = supports_default_values
539
+ dialect.supports_default_metavalue = supports_default_metavalue
540
+ dialect.supports_native_boolean = supports_native_boolean
541
+ elif allow_dialect_select:
542
+ dialect = None
543
+ else:
544
+ if dialect is None:
545
+ dialect = getattr(self, "__dialect__", None)
546
+
547
+ if dialect is None:
548
+ dialect = config.db.dialect
549
+ elif dialect == "default" or dialect == "default_qmark":
550
+ if dialect == "default":
551
+ dialect = default.DefaultDialect()
552
+ else:
553
+ dialect = default.DefaultDialect("qmark")
554
+ dialect.supports_default_values = supports_default_values
555
+ dialect.supports_default_metavalue = supports_default_metavalue
556
+ elif dialect == "default_enhanced":
557
+ dialect = default.StrCompileDialect()
558
+ elif isinstance(dialect, str):
559
+ dialect = url.URL.create(dialect).get_dialect()()
560
+
561
+ if default_schema_name:
562
+ dialect.default_schema_name = default_schema_name
563
+
564
+ kw = {}
565
+ compile_kwargs = {}
566
+
567
+ if schema_translate_map:
568
+ kw["schema_translate_map"] = schema_translate_map
569
+
570
+ if params is not None:
571
+ kw["column_keys"] = list(params)
572
+
573
+ if literal_binds:
574
+ compile_kwargs["literal_binds"] = True
575
+
576
+ if render_postcompile:
577
+ compile_kwargs["render_postcompile"] = True
578
+
579
+ if use_literal_execute_for_simple_int:
580
+ compile_kwargs["use_literal_execute_for_simple_int"] = True
581
+
582
+ if for_executemany:
583
+ kw["for_executemany"] = True
584
+
585
+ if render_schema_translate:
586
+ kw["render_schema_translate"] = True
587
+
588
+ if from_linting or getattr(self, "assert_from_linting", False):
589
+ kw["linting"] = sql.FROM_LINTING
590
+
591
+ from sqlalchemy import orm
592
+
593
+ if isinstance(clause, orm.Query):
594
+ stmt = clause._statement_20()
595
+ stmt._label_style = LABEL_STYLE_TABLENAME_PLUS_COL
596
+ clause = stmt
597
+
598
+ if compile_kwargs:
599
+ kw["compile_kwargs"] = compile_kwargs
600
+
601
+ class DontAccess:
602
+ def __getattribute__(self, key):
603
+ raise NotImplementedError(
604
+ "compiler accessed .statement; use "
605
+ "compiler.current_executable"
606
+ )
607
+
608
+ class CheckCompilerAccess:
609
+ def __init__(self, test_statement):
610
+ self.test_statement = test_statement
611
+ self._annotations = {}
612
+ self.supports_execution = getattr(
613
+ test_statement, "supports_execution", False
614
+ )
615
+
616
+ if self.supports_execution:
617
+ self._execution_options = test_statement._execution_options
618
+
619
+ if hasattr(test_statement, "_returning"):
620
+ self._returning = test_statement._returning
621
+ if hasattr(test_statement, "_inline"):
622
+ self._inline = test_statement._inline
623
+ if hasattr(test_statement, "_return_defaults"):
624
+ self._return_defaults = test_statement._return_defaults
625
+
626
+ @property
627
+ def _variant_mapping(self):
628
+ return self.test_statement._variant_mapping
629
+
630
+ def _default_dialect(self):
631
+ return self.test_statement._default_dialect()
632
+
633
+ def compile(self, dialect, **kw):
634
+ return self.test_statement.compile.__func__(
635
+ self, dialect=dialect, **kw
636
+ )
637
+
638
+ def _compiler(self, dialect, **kw):
639
+ return self.test_statement._compiler.__func__(
640
+ self, dialect, **kw
641
+ )
642
+
643
+ def _compiler_dispatch(self, compiler, **kwargs):
644
+ if hasattr(compiler, "statement"):
645
+ with mock.patch.object(
646
+ compiler, "statement", DontAccess()
647
+ ):
648
+ return self.test_statement._compiler_dispatch(
649
+ compiler, **kwargs
650
+ )
651
+ else:
652
+ return self.test_statement._compiler_dispatch(
653
+ compiler, **kwargs
654
+ )
655
+
656
+ # no construct can assume it's the "top level" construct in all cases
657
+ # as anything can be nested. ensure constructs don't assume they
658
+ # are the "self.statement" element
659
+ c = CheckCompilerAccess(clause).compile(dialect=dialect, **kw)
660
+
661
+ if isinstance(clause, sqltypes.TypeEngine):
662
+ cache_key_no_warnings = clause._static_cache_key
663
+ if cache_key_no_warnings:
664
+ hash(cache_key_no_warnings)
665
+ else:
666
+ cache_key_no_warnings = clause._generate_cache_key()
667
+ if cache_key_no_warnings:
668
+ hash(cache_key_no_warnings[0])
669
+
670
+ param_str = repr(getattr(c, "params", {}))
671
+ param_str = param_str.encode("utf-8").decode("ascii", "ignore")
672
+ print(("\nSQL String:\n" + str(c) + param_str).encode("utf-8"))
673
+
674
+ cc = re.sub(r"[\n\t]", "", str(c))
675
+
676
+ if isinstance(result, re.Pattern):
677
+ assert result.match(cc), "%r !~ %r on dialect %r" % (
678
+ cc,
679
+ result,
680
+ dialect,
681
+ )
682
+ else:
683
+ eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
684
+
685
+ if checkparams is not None:
686
+ if render_postcompile:
687
+ expanded_state = c.construct_expanded_state(
688
+ params, escape_names=False
689
+ )
690
+ eq_(expanded_state.parameters, checkparams)
691
+ else:
692
+ eq_(c.construct_params(params), checkparams)
693
+ if checkpositional is not None:
694
+ if render_postcompile:
695
+ expanded_state = c.construct_expanded_state(
696
+ params, escape_names=False
697
+ )
698
+ eq_(
699
+ tuple(
700
+ [
701
+ expanded_state.parameters[x]
702
+ for x in expanded_state.positiontup
703
+ ]
704
+ ),
705
+ checkpositional,
706
+ )
707
+ else:
708
+ p = c.construct_params(params, escape_names=False)
709
+ eq_(tuple([p[x] for x in c.positiontup]), checkpositional)
710
+ if check_prefetch is not None:
711
+ eq_(c.prefetch, check_prefetch)
712
+ if check_literal_execute is not None:
713
+ eq_(
714
+ {
715
+ c.bind_names[b]: b.effective_value
716
+ for b in c.literal_execute_params
717
+ },
718
+ check_literal_execute,
719
+ )
720
+ if check_post_param is not None:
721
+ eq_(
722
+ {
723
+ c.bind_names[b]: b.effective_value
724
+ for b in c.post_compile_params
725
+ },
726
+ check_post_param,
727
+ )
728
+ if check_param_order and getattr(c, "params", None):
729
+
730
+ def get_dialect(paramstyle, positional):
731
+ cp = copy(dialect)
732
+ cp.paramstyle = paramstyle
733
+ cp.positional = positional
734
+ return cp
735
+
736
+ pyformat_dialect = get_dialect("pyformat", False)
737
+ pyformat_c = clause.compile(dialect=pyformat_dialect, **kw)
738
+ stmt = re.sub(r"[\n\t]", "", str(pyformat_c))
739
+
740
+ qmark_dialect = get_dialect("qmark", True)
741
+ qmark_c = clause.compile(dialect=qmark_dialect, **kw)
742
+ values = list(qmark_c.positiontup)
743
+ escaped = qmark_c.escaped_bind_names
744
+
745
+ for post_param in (
746
+ qmark_c.post_compile_params | qmark_c.literal_execute_params
747
+ ):
748
+ name = qmark_c.bind_names[post_param]
749
+ if name in values:
750
+ values = [v for v in values if v != name]
751
+ positions = []
752
+ pos_by_value = defaultdict(list)
753
+ for v in values:
754
+ try:
755
+ if v in pos_by_value:
756
+ start = pos_by_value[v][-1]
757
+ else:
758
+ start = 0
759
+ esc = escaped.get(v, v)
760
+ pos = stmt.index("%%(%s)s" % (esc,), start) + 2
761
+ positions.append(pos)
762
+ pos_by_value[v].append(pos)
763
+ except ValueError:
764
+ msg = "Expected to find bindparam %r in %r" % (v, stmt)
765
+ assert False, msg
766
+
767
+ ordered = all(
768
+ positions[i - 1] < positions[i]
769
+ for i in range(1, len(positions))
770
+ )
771
+
772
+ expected = [v for _, v in sorted(zip(positions, values))]
773
+
774
+ msg = (
775
+ "Order of parameters %s does not match the order "
776
+ "in the statement %s. Statement %r" % (values, expected, stmt)
777
+ )
778
+
779
+ is_true(ordered, msg)
780
+
781
+
782
+ class ComparesTables:
783
+ def assert_tables_equal(
784
+ self,
785
+ table,
786
+ reflected_table,
787
+ strict_types=False,
788
+ strict_constraints=True,
789
+ ):
790
+ assert len(table.c) == len(reflected_table.c)
791
+ for c, reflected_c in zip(table.c, reflected_table.c):
792
+ eq_(c.name, reflected_c.name)
793
+ assert reflected_c is reflected_table.c[c.name]
794
+
795
+ if strict_constraints:
796
+ eq_(c.primary_key, reflected_c.primary_key)
797
+ eq_(c.nullable, reflected_c.nullable)
798
+
799
+ if strict_types:
800
+ msg = "Type '%s' doesn't correspond to type '%s'"
801
+ assert isinstance(reflected_c.type, type(c.type)), msg % (
802
+ reflected_c.type,
803
+ c.type,
804
+ )
805
+ else:
806
+ self.assert_types_base(reflected_c, c)
807
+
808
+ if isinstance(c.type, sqltypes.String):
809
+ eq_(c.type.length, reflected_c.type.length)
810
+
811
+ if strict_constraints:
812
+ eq_(
813
+ {f.column.name for f in c.foreign_keys},
814
+ {f.column.name for f in reflected_c.foreign_keys},
815
+ )
816
+ if c.server_default:
817
+ assert isinstance(
818
+ reflected_c.server_default, schema.FetchedValue
819
+ )
820
+
821
+ if strict_constraints:
822
+ assert len(table.primary_key) == len(reflected_table.primary_key)
823
+ for c in table.primary_key:
824
+ assert reflected_table.primary_key.columns[c.name] is not None
825
+
826
+ def assert_types_base(self, c1, c2):
827
+ assert c1.type._compare_type_affinity(
828
+ c2.type
829
+ ), "On column %r, type '%s' doesn't correspond to type '%s'" % (
830
+ c1.name,
831
+ c1.type,
832
+ c2.type,
833
+ )
834
+
835
+
836
+ class AssertsExecutionResults:
837
+ def assert_result(self, result, class_, *objects):
838
+ result = list(result)
839
+ print(repr(result))
840
+ self.assert_list(result, class_, objects)
841
+
842
+ def assert_list(self, result, class_, list_):
843
+ self.assert_(
844
+ len(result) == len(list_),
845
+ "result list is not the same size as test list, "
846
+ + "for class "
847
+ + class_.__name__,
848
+ )
849
+ for i in range(0, len(list_)):
850
+ self.assert_row(class_, result[i], list_[i])
851
+
852
+ def assert_row(self, class_, rowobj, desc):
853
+ self.assert_(
854
+ rowobj.__class__ is class_, "item class is not " + repr(class_)
855
+ )
856
+ for key, value in desc.items():
857
+ if isinstance(value, tuple):
858
+ if isinstance(value[1], list):
859
+ self.assert_list(getattr(rowobj, key), value[0], value[1])
860
+ else:
861
+ self.assert_row(value[0], getattr(rowobj, key), value[1])
862
+ else:
863
+ self.assert_(
864
+ getattr(rowobj, key) == value,
865
+ "attribute %s value %s does not match %s"
866
+ % (key, getattr(rowobj, key), value),
867
+ )
868
+
869
+ def assert_unordered_result(self, result, cls, *expected):
870
+ """As assert_result, but the order of objects is not considered.
871
+
872
+ The algorithm is very expensive but not a big deal for the small
873
+ numbers of rows that the test suite manipulates.
874
+ """
875
+
876
+ class immutabledict(dict):
877
+ def __hash__(self):
878
+ return id(self)
879
+
880
+ found = util.IdentitySet(result)
881
+ expected = {immutabledict(e) for e in expected}
882
+
883
+ for wrong in filterfalse(lambda o: isinstance(o, cls), found):
884
+ fail(
885
+ 'Unexpected type "%s", expected "%s"'
886
+ % (type(wrong).__name__, cls.__name__)
887
+ )
888
+
889
+ if len(found) != len(expected):
890
+ fail(
891
+ 'Unexpected object count "%s", expected "%s"'
892
+ % (len(found), len(expected))
893
+ )
894
+
895
+ NOVALUE = object()
896
+
897
+ def _compare_item(obj, spec):
898
+ for key, value in spec.items():
899
+ if isinstance(value, tuple):
900
+ try:
901
+ self.assert_unordered_result(
902
+ getattr(obj, key), value[0], *value[1]
903
+ )
904
+ except AssertionError:
905
+ return False
906
+ else:
907
+ if getattr(obj, key, NOVALUE) != value:
908
+ return False
909
+ return True
910
+
911
+ for expected_item in expected:
912
+ for found_item in found:
913
+ if _compare_item(found_item, expected_item):
914
+ found.remove(found_item)
915
+ break
916
+ else:
917
+ fail(
918
+ "Expected %s instance with attributes %s not found."
919
+ % (cls.__name__, repr(expected_item))
920
+ )
921
+ return True
922
+
923
+ def sql_execution_asserter(self, db=None):
924
+ if db is None:
925
+ from . import db as db
926
+
927
+ return assertsql.assert_engine(db)
928
+
929
+ def assert_sql_execution(self, db, callable_, *rules):
930
+ with self.sql_execution_asserter(db) as asserter:
931
+ result = callable_()
932
+ asserter.assert_(*rules)
933
+ return result
934
+
935
+ def assert_sql(self, db, callable_, rules):
936
+ newrules = []
937
+ for rule in rules:
938
+ if isinstance(rule, dict):
939
+ newrule = assertsql.AllOf(
940
+ *[assertsql.CompiledSQL(k, v) for k, v in rule.items()]
941
+ )
942
+ else:
943
+ newrule = assertsql.CompiledSQL(*rule)
944
+ newrules.append(newrule)
945
+
946
+ return self.assert_sql_execution(db, callable_, *newrules)
947
+
948
+ def assert_sql_count(self, db, callable_, count):
949
+ return self.assert_sql_execution(
950
+ db, callable_, assertsql.CountStatements(count)
951
+ )
952
+
953
+ @contextlib.contextmanager
954
+ def assert_execution(self, db, *rules):
955
+ with self.sql_execution_asserter(db) as asserter:
956
+ yield
957
+ asserter.assert_(*rules)
958
+
959
+ def assert_statement_count(self, db, count):
960
+ return self.assert_execution(db, assertsql.CountStatements(count))
961
+
962
+ @contextlib.contextmanager
963
+ def assert_statement_count_multi_db(self, dbs, counts):
964
+ recs = [
965
+ (self.sql_execution_asserter(db), db, count)
966
+ for (db, count) in zip(dbs, counts)
967
+ ]
968
+ asserters = []
969
+ for ctx, db, count in recs:
970
+ asserters.append(ctx.__enter__())
971
+ try:
972
+ yield
973
+ finally:
974
+ for asserter, (ctx, db, count) in zip(asserters, recs):
975
+ ctx.__exit__(None, None, None)
976
+ asserter.assert_(assertsql.CountStatements(count))
977
+
978
+
979
+ class ComparesIndexes:
980
+ def compare_table_index_with_expected(
981
+ self, table: schema.Table, expected: list, dialect_name: str
982
+ ):
983
+ eq_(len(table.indexes), len(expected))
984
+ idx_dict = {idx.name: idx for idx in table.indexes}
985
+ for exp in expected:
986
+ idx = idx_dict[exp["name"]]
987
+ eq_(idx.unique, exp["unique"])
988
+ cols = [c for c in exp["column_names"] if c is not None]
989
+ eq_(len(idx.columns), len(cols))
990
+ for c in cols:
991
+ is_true(c in idx.columns)
992
+ exprs = exp.get("expressions")
993
+ if exprs:
994
+ eq_(len(idx.expressions), len(exprs))
995
+ for idx_exp, expr, col in zip(
996
+ idx.expressions, exprs, exp["column_names"]
997
+ ):
998
+ if col is None:
999
+ eq_(idx_exp.text, expr)
1000
+ if (
1001
+ exp.get("dialect_options")
1002
+ and f"{dialect_name}_include" in exp["dialect_options"]
1003
+ ):
1004
+ eq_(
1005
+ idx.dialect_options[dialect_name]["include"],
1006
+ exp["dialect_options"][f"{dialect_name}_include"],
1007
+ )