assertions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. # testing/assertions.py
  2. # Copyright (C) 2005-2024 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. from __future__ import absolute_import
  8. from collections import defaultdict
  9. import contextlib
  10. from copy import copy
  11. import re
  12. import sys
  13. import warnings
  14. from . import assertsql
  15. from . import config
  16. from . import engines
  17. from . import mock
  18. from .exclusions import db_spec
  19. from .util import fail
  20. from .. import exc as sa_exc
  21. from .. import schema
  22. from .. import sql
  23. from .. import types as sqltypes
  24. from .. import util
  25. from ..engine import default
  26. from ..engine import url
  27. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  28. from ..util import compat
  29. from ..util import decorator
  30. def expect_warnings(*messages, **kw):
  31. """Context manager which expects one or more warnings.
  32. With no arguments, squelches all SAWarning and RemovedIn20Warning emitted via
  33. sqlalchemy.util.warn and sqlalchemy.util.warn_limited. Otherwise
  34. pass string expressions that will match selected warnings via regex;
  35. all non-matching warnings are sent through.
  36. The expect version **asserts** that the warnings were in fact seen.
  37. Note that the test suite sets SAWarning warnings to raise exceptions.
  38. """ # noqa
  39. return _expect_warnings(
  40. (sa_exc.RemovedIn20Warning, sa_exc.SAWarning), messages, **kw
  41. )
  42. @contextlib.contextmanager
  43. def expect_warnings_on(db, *messages, **kw):
  44. """Context manager which expects one or more warnings on specific
  45. dialects.
  46. The expect version **asserts** that the warnings were in fact seen.
  47. """
  48. spec = db_spec(db)
  49. if isinstance(db, util.string_types) and not spec(config._current):
  50. yield
  51. else:
  52. with expect_warnings(*messages, **kw):
  53. yield
  54. def emits_warning(*messages):
  55. """Decorator form of expect_warnings().
  56. Note that emits_warning does **not** assert that the warnings
  57. were in fact seen.
  58. """
  59. @decorator
  60. def decorate(fn, *args, **kw):
  61. with expect_warnings(assert_=False, *messages):
  62. return fn(*args, **kw)
  63. return decorate
  64. def expect_deprecated(*messages, **kw):
  65. return _expect_warnings(sa_exc.SADeprecationWarning, messages, **kw)
  66. def expect_deprecated_20(*messages, **kw):
  67. return _expect_warnings(sa_exc.Base20DeprecationWarning, messages, **kw)
  68. def emits_warning_on(db, *messages):
  69. """Mark a test as emitting a warning on a specific dialect.
  70. With no arguments, squelches all SAWarning failures. Or pass one or more
  71. strings; these will be matched to the root of the warning description by
  72. warnings.filterwarnings().
  73. Note that emits_warning_on does **not** assert that the warnings
  74. were in fact seen.
  75. """
  76. @decorator
  77. def decorate(fn, *args, **kw):
  78. with expect_warnings_on(db, assert_=False, *messages):
  79. return fn(*args, **kw)
  80. return decorate
  81. def uses_deprecated(*messages):
  82. """Mark a test as immune from fatal deprecation warnings.
  83. With no arguments, squelches all SADeprecationWarning failures.
  84. Or pass one or more strings; these will be matched to the root
  85. of the warning description by warnings.filterwarnings().
  86. As a special case, you may pass a function name prefixed with //
  87. and it will be re-written as needed to match the standard warning
  88. verbiage emitted by the sqlalchemy.util.deprecated decorator.
  89. Note that uses_deprecated does **not** assert that the warnings
  90. were in fact seen.
  91. """
  92. @decorator
  93. def decorate(fn, *args, **kw):
  94. with expect_deprecated(*messages, assert_=False):
  95. return fn(*args, **kw)
  96. return decorate
  97. _FILTERS = None
  98. _SEEN = None
  99. _EXC_CLS = None
  100. @contextlib.contextmanager
  101. def _expect_warnings(
  102. exc_cls,
  103. messages,
  104. regex=True,
  105. search_msg=False,
  106. assert_=True,
  107. py2konly=False,
  108. raise_on_any_unexpected=False,
  109. squelch_other_warnings=False,
  110. ):
  111. global _FILTERS, _SEEN, _EXC_CLS
  112. if regex or search_msg:
  113. filters = [re.compile(msg, re.I | re.S) for msg in messages]
  114. else:
  115. filters = list(messages)
  116. if _FILTERS is not None:
  117. # nested call; update _FILTERS and _SEEN, return. outer
  118. # block will assert our messages
  119. assert _SEEN is not None
  120. assert _EXC_CLS is not None
  121. _FILTERS.extend(filters)
  122. _SEEN.update(filters)
  123. _EXC_CLS += (exc_cls,)
  124. yield
  125. else:
  126. seen = _SEEN = set(filters)
  127. _FILTERS = filters
  128. _EXC_CLS = (exc_cls,)
  129. if raise_on_any_unexpected:
  130. def real_warn(msg, *arg, **kw):
  131. raise AssertionError("Got unexpected warning: %r" % msg)
  132. else:
  133. real_warn = warnings.warn
  134. def our_warn(msg, *arg, **kw):
  135. if isinstance(msg, _EXC_CLS):
  136. exception = type(msg)
  137. msg = str(msg)
  138. elif arg:
  139. exception = arg[0]
  140. else:
  141. exception = None
  142. if not exception or not issubclass(exception, _EXC_CLS):
  143. if not squelch_other_warnings:
  144. return real_warn(msg, *arg, **kw)
  145. else:
  146. return
  147. if not filters and not raise_on_any_unexpected:
  148. return
  149. for filter_ in filters:
  150. if (
  151. (search_msg and filter_.search(msg))
  152. or (regex and filter_.match(msg))
  153. or (not regex and filter_ == msg)
  154. ):
  155. seen.discard(filter_)
  156. break
  157. else:
  158. if not squelch_other_warnings:
  159. real_warn(msg, *arg, **kw)
  160. with mock.patch("warnings.warn", our_warn), mock.patch(
  161. "sqlalchemy.util.SQLALCHEMY_WARN_20", True
  162. ), mock.patch(
  163. "sqlalchemy.util.deprecations.SQLALCHEMY_WARN_20", True
  164. ), mock.patch(
  165. "sqlalchemy.engine.row.LegacyRow._default_key_style", 2
  166. ):
  167. try:
  168. yield
  169. finally:
  170. _SEEN = _FILTERS = _EXC_CLS = None
  171. if assert_ and (not py2konly or not compat.py3k):
  172. assert not seen, "Warnings were not seen: %s" % ", ".join(
  173. "%r" % (s.pattern if regex else s) for s in seen
  174. )
  175. def global_cleanup_assertions():
  176. """Check things that have to be finalized at the end of a test suite.
  177. Hardcoded at the moment, a modular system can be built here
  178. to support things like PG prepared transactions, tables all
  179. dropped, etc.
  180. """
  181. _assert_no_stray_pool_connections()
  182. def _assert_no_stray_pool_connections():
  183. engines.testing_reaper.assert_all_closed()
  184. def int_within_variance(expected, received, variance):
  185. deviance = int(expected * variance)
  186. assert (
  187. abs(received - expected) < deviance
  188. ), "Given int value %s is not within %d%% of expected value %s" % (
  189. received,
  190. variance * 100,
  191. expected,
  192. )
  193. def eq_regex(a, b, msg=None):
  194. assert re.match(b, a), msg or "%r !~ %r" % (a, b)
  195. def eq_(a, b, msg=None):
  196. """Assert a == b, with repr messaging on failure."""
  197. assert a == b, msg or "%r != %r" % (a, b)
  198. def ne_(a, b, msg=None):
  199. """Assert a != b, with repr messaging on failure."""
  200. assert a != b, msg or "%r == %r" % (a, b)
  201. def le_(a, b, msg=None):
  202. """Assert a <= b, with repr messaging on failure."""
  203. assert a <= b, msg or "%r != %r" % (a, b)
  204. def is_instance_of(a, b, msg=None):
  205. assert isinstance(a, b), msg or "%r is not an instance of %r" % (a, b)
  206. def is_none(a, msg=None):
  207. is_(a, None, msg=msg)
  208. def is_not_none(a, msg=None):
  209. is_not(a, None, msg=msg)
  210. def is_true(a, msg=None):
  211. is_(bool(a), True, msg=msg)
  212. def is_false(a, msg=None):
  213. is_(bool(a), False, msg=msg)
  214. def is_(a, b, msg=None):
  215. """Assert a is b, with repr messaging on failure."""
  216. assert a is b, msg or "%r is not %r" % (a, b)
  217. def is_not(a, b, msg=None):
  218. """Assert a is not b, with repr messaging on failure."""
  219. assert a is not b, msg or "%r is %r" % (a, b)
  220. # deprecated. See #5429
  221. is_not_ = is_not
  222. def in_(a, b, msg=None):
  223. """Assert a in b, with repr messaging on failure."""
  224. assert a in b, msg or "%r not in %r" % (a, b)
  225. def not_in(a, b, msg=None):
  226. """Assert a in not b, with repr messaging on failure."""
  227. assert a not in b, msg or "%r is in %r" % (a, b)
  228. # deprecated. See #5429
  229. not_in_ = not_in
  230. def startswith_(a, fragment, msg=None):
  231. """Assert a.startswith(fragment), with repr messaging on failure."""
  232. assert a.startswith(fragment), msg or "%r does not start with %r" % (
  233. a,
  234. fragment,
  235. )
  236. def eq_ignore_whitespace(a, b, msg=None):
  237. a = re.sub(r"^\s+?|\n", "", a)
  238. a = re.sub(r" {2,}", " ", a)
  239. a = re.sub(r"\t", "", a)
  240. b = re.sub(r"^\s+?|\n", "", b)
  241. b = re.sub(r" {2,}", " ", b)
  242. b = re.sub(r"\t", "", b)
  243. assert a == b, msg or "%r != %r" % (a, b)
  244. def _assert_proper_exception_context(exception):
  245. """assert that any exception we're catching does not have a __context__
  246. without a __cause__, and that __suppress_context__ is never set.
  247. Python 3 will report nested as exceptions as "during the handling of
  248. error X, error Y occurred". That's not what we want to do. we want
  249. these exceptions in a cause chain.
  250. """
  251. if not util.py3k:
  252. return
  253. if (
  254. exception.__context__ is not exception.__cause__
  255. and not exception.__suppress_context__
  256. ):
  257. assert False, (
  258. "Exception %r was correctly raised but did not set a cause, "
  259. "within context %r as its cause."
  260. % (exception, exception.__context__)
  261. )
  262. def assert_raises(except_cls, callable_, *args, **kw):
  263. return _assert_raises(except_cls, callable_, args, kw, check_context=True)
  264. def assert_raises_context_ok(except_cls, callable_, *args, **kw):
  265. return _assert_raises(except_cls, callable_, args, kw)
  266. def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
  267. return _assert_raises(
  268. except_cls, callable_, args, kwargs, msg=msg, check_context=True
  269. )
  270. def assert_warns(except_cls, callable_, *args, **kwargs):
  271. """legacy adapter function for functions that were previously using
  272. assert_raises with SAWarning or similar.
  273. has some workarounds to accommodate the fact that the callable completes
  274. with this approach rather than stopping at the exception raise.
  275. """
  276. with _expect_warnings(except_cls, [".*"], squelch_other_warnings=True):
  277. return callable_(*args, **kwargs)
  278. def assert_warns_message(except_cls, msg, callable_, *args, **kwargs):
  279. """legacy adapter function for functions that were previously using
  280. assert_raises with SAWarning or similar.
  281. has some workarounds to accommodate the fact that the callable completes
  282. with this approach rather than stopping at the exception raise.
  283. Also uses regex.search() to match the given message to the error string
  284. rather than regex.match().
  285. """
  286. with _expect_warnings(
  287. except_cls,
  288. [msg],
  289. search_msg=True,
  290. regex=False,
  291. squelch_other_warnings=True,
  292. ):
  293. return callable_(*args, **kwargs)
  294. def assert_raises_message_context_ok(
  295. except_cls, msg, callable_, *args, **kwargs
  296. ):
  297. return _assert_raises(except_cls, callable_, args, kwargs, msg=msg)
  298. def _assert_raises(
  299. except_cls, callable_, args, kwargs, msg=None, check_context=False
  300. ):
  301. with _expect_raises(except_cls, msg, check_context) as ec:
  302. callable_(*args, **kwargs)
  303. return ec.error
  304. class _ErrorContainer(object):
  305. error = None
  306. @contextlib.contextmanager
  307. def _expect_raises(except_cls, msg=None, check_context=False):
  308. if (
  309. isinstance(except_cls, type)
  310. and issubclass(except_cls, Warning)
  311. or isinstance(except_cls, Warning)
  312. ):
  313. raise TypeError(
  314. "Use expect_warnings for warnings, not "
  315. "expect_raises / assert_raises"
  316. )
  317. ec = _ErrorContainer()
  318. if check_context:
  319. are_we_already_in_a_traceback = sys.exc_info()[0]
  320. try:
  321. yield ec
  322. success = False
  323. except except_cls as err:
  324. ec.error = err
  325. success = True
  326. if msg is not None:
  327. assert re.search(
  328. msg, util.text_type(err), re.UNICODE
  329. ), "%r !~ %s" % (msg, err)
  330. if check_context and not are_we_already_in_a_traceback:
  331. _assert_proper_exception_context(err)
  332. print(util.text_type(err).encode("utf-8"))
  333. # it's generally a good idea to not carry traceback objects outside
  334. # of the except: block, but in this case especially we seem to have
  335. # hit some bug in either python 3.10.0b2 or greenlet or both which
  336. # this seems to fix:
  337. # https://github.com/python-greenlet/greenlet/issues/242
  338. del ec
  339. # assert outside the block so it works for AssertionError too !
  340. assert success, "Callable did not raise an exception"
  341. def expect_raises(except_cls, check_context=True):
  342. return _expect_raises(except_cls, check_context=check_context)
  343. def expect_raises_message(except_cls, msg, check_context=True):
  344. return _expect_raises(except_cls, msg=msg, check_context=check_context)
  345. class AssertsCompiledSQL(object):
  346. def assert_compile(
  347. self,
  348. clause,
  349. result,
  350. params=None,
  351. checkparams=None,
  352. for_executemany=False,
  353. check_literal_execute=None,
  354. check_post_param=None,
  355. dialect=None,
  356. checkpositional=None,
  357. check_prefetch=None,
  358. use_default_dialect=False,
  359. allow_dialect_select=False,
  360. supports_default_values=True,
  361. supports_default_metavalue=True,
  362. literal_binds=False,
  363. render_postcompile=False,
  364. schema_translate_map=None,
  365. render_schema_translate=False,
  366. default_schema_name=None,
  367. from_linting=False,
  368. check_param_order=True,
  369. ):
  370. if use_default_dialect:
  371. dialect = default.DefaultDialect()
  372. dialect.supports_default_values = supports_default_values
  373. dialect.supports_default_metavalue = supports_default_metavalue
  374. elif allow_dialect_select:
  375. dialect = None
  376. else:
  377. if dialect is None:
  378. dialect = getattr(self, "__dialect__", None)
  379. if dialect is None:
  380. dialect = config.db.dialect
  381. elif dialect == "default" or dialect == "default_qmark":
  382. if dialect == "default":
  383. dialect = default.DefaultDialect()
  384. else:
  385. dialect = default.DefaultDialect(paramstyle="qmark")
  386. dialect.supports_default_values = supports_default_values
  387. dialect.supports_default_metavalue = supports_default_metavalue
  388. elif dialect == "default_enhanced":
  389. dialect = default.StrCompileDialect()
  390. elif isinstance(dialect, util.string_types):
  391. dialect = url.URL.create(dialect).get_dialect()()
  392. if default_schema_name:
  393. dialect.default_schema_name = default_schema_name
  394. kw = {}
  395. compile_kwargs = {}
  396. if schema_translate_map:
  397. kw["schema_translate_map"] = schema_translate_map
  398. if params is not None:
  399. kw["column_keys"] = list(params)
  400. if literal_binds:
  401. compile_kwargs["literal_binds"] = True
  402. if render_postcompile:
  403. compile_kwargs["render_postcompile"] = True
  404. if for_executemany:
  405. kw["for_executemany"] = True
  406. if render_schema_translate:
  407. kw["render_schema_translate"] = True
  408. if from_linting or getattr(self, "assert_from_linting", False):
  409. kw["linting"] = sql.FROM_LINTING
  410. from sqlalchemy import orm
  411. if isinstance(clause, orm.Query):
  412. stmt = clause._statement_20()
  413. stmt._label_style = LABEL_STYLE_TABLENAME_PLUS_COL
  414. clause = stmt
  415. if compile_kwargs:
  416. kw["compile_kwargs"] = compile_kwargs
  417. class DontAccess(object):
  418. def __getattribute__(self, key):
  419. raise NotImplementedError(
  420. "compiler accessed .statement; use "
  421. "compiler.current_executable"
  422. )
  423. class CheckCompilerAccess(object):
  424. def __init__(self, test_statement):
  425. self.test_statement = test_statement
  426. self._annotations = {}
  427. self.supports_execution = getattr(
  428. test_statement, "supports_execution", False
  429. )
  430. if self.supports_execution:
  431. self._execution_options = test_statement._execution_options
  432. if hasattr(test_statement, "_returning"):
  433. self._returning = test_statement._returning
  434. if hasattr(test_statement, "_inline"):
  435. self._inline = test_statement._inline
  436. if hasattr(test_statement, "_return_defaults"):
  437. self._return_defaults = test_statement._return_defaults
  438. def _default_dialect(self):
  439. return self.test_statement._default_dialect()
  440. def compile(self, dialect, **kw):
  441. return self.test_statement.compile.__func__(
  442. self, dialect=dialect, **kw
  443. )
  444. def _compiler(self, dialect, **kw):
  445. return self.test_statement._compiler.__func__(
  446. self, dialect, **kw
  447. )
  448. def _compiler_dispatch(self, compiler, **kwargs):
  449. if hasattr(compiler, "statement"):
  450. with mock.patch.object(
  451. compiler, "statement", DontAccess()
  452. ):
  453. return self.test_statement._compiler_dispatch(
  454. compiler, **kwargs
  455. )
  456. else:
  457. return self.test_statement._compiler_dispatch(
  458. compiler, **kwargs
  459. )
  460. # no construct can assume it's the "top level" construct in all cases
  461. # as anything can be nested. ensure constructs don't assume they
  462. # are the "self.statement" element
  463. c = CheckCompilerAccess(clause).compile(dialect=dialect, **kw)
  464. if isinstance(clause, sqltypes.TypeEngine):
  465. cache_key_no_warnings = clause._static_cache_key
  466. if cache_key_no_warnings:
  467. hash(cache_key_no_warnings)
  468. else:
  469. cache_key_no_warnings = clause._generate_cache_key()
  470. if cache_key_no_warnings:
  471. hash(cache_key_no_warnings[0])
  472. param_str = repr(getattr(c, "params", {}))
  473. if util.py3k:
  474. param_str = param_str.encode("utf-8").decode("ascii", "ignore")
  475. print(
  476. ("\nSQL String:\n" + util.text_type(c) + param_str).encode(
  477. "utf-8"
  478. )
  479. )
  480. else:
  481. print(
  482. "\nSQL String:\n"
  483. + util.text_type(c).encode("utf-8")
  484. + param_str
  485. )
  486. cc = re.sub(r"[\n\t]", "", util.text_type(c))
  487. eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
  488. if checkparams is not None:
  489. eq_(c.construct_params(params), checkparams)
  490. if checkpositional is not None:
  491. p = c.construct_params(params, escape_names=False)
  492. eq_(tuple([p[x] for x in c.positiontup]), checkpositional)
  493. if check_prefetch is not None:
  494. eq_(c.prefetch, check_prefetch)
  495. if check_literal_execute is not None:
  496. eq_(
  497. {
  498. c.bind_names[b]: b.effective_value
  499. for b in c.literal_execute_params
  500. },
  501. check_literal_execute,
  502. )
  503. if check_post_param is not None:
  504. eq_(
  505. {
  506. c.bind_names[b]: b.effective_value
  507. for b in c.post_compile_params
  508. },
  509. check_post_param,
  510. )
  511. if check_param_order and getattr(c, "params", None):
  512. def get_dialect(paramstyle, positional):
  513. cp = copy(dialect)
  514. cp.paramstyle = paramstyle
  515. cp.positional = positional
  516. return cp
  517. pyformat_dialect = get_dialect("pyformat", False)
  518. pyformat_c = clause.compile(dialect=pyformat_dialect, **kw)
  519. stmt = re.sub(r"[\n\t]", "", pyformat_c.string)
  520. qmark_dialect = get_dialect("qmark", True)
  521. qmark_c = clause.compile(dialect=qmark_dialect, **kw)
  522. values = list(qmark_c.positiontup)
  523. escaped = qmark_c.escaped_bind_names
  524. for post_param in (
  525. qmark_c.post_compile_params | qmark_c.literal_execute_params
  526. ):
  527. name = qmark_c.bind_names[post_param]
  528. if name in values:
  529. values = [v for v in values if v != name]
  530. positions = []
  531. pos_by_value = defaultdict(list)
  532. for v in values:
  533. try:
  534. if v in pos_by_value:
  535. start = pos_by_value[v][-1]
  536. else:
  537. start = 0
  538. esc = escaped.get(v, v)
  539. pos = stmt.index("%%(%s)s" % (esc,), start) + 2
  540. positions.append(pos)
  541. pos_by_value[v].append(pos)
  542. except ValueError:
  543. msg = "Expected to find bindparam %r in %r" % (v, stmt)
  544. assert False, msg
  545. ordered = all(
  546. positions[i - 1] < positions[i]
  547. for i in range(1, len(positions))
  548. )
  549. expected = [v for _, v in sorted(zip(positions, values))]
  550. msg = (
  551. "Order of parameters %s does not match the order "
  552. "in the statement %s. Statement %r" % (values, expected, stmt)
  553. )
  554. is_true(ordered, msg)
  555. class ComparesTables(object):
  556. def assert_tables_equal(self, table, reflected_table, strict_types=False):
  557. assert len(table.c) == len(reflected_table.c)
  558. for c, reflected_c in zip(table.c, reflected_table.c):
  559. eq_(c.name, reflected_c.name)
  560. assert reflected_c is reflected_table.c[c.name]
  561. eq_(c.primary_key, reflected_c.primary_key)
  562. eq_(c.nullable, reflected_c.nullable)
  563. if strict_types:
  564. msg = "Type '%s' doesn't correspond to type '%s'"
  565. assert isinstance(reflected_c.type, type(c.type)), msg % (
  566. reflected_c.type,
  567. c.type,
  568. )
  569. else:
  570. self.assert_types_base(reflected_c, c)
  571. if isinstance(c.type, sqltypes.String):
  572. eq_(c.type.length, reflected_c.type.length)
  573. eq_(
  574. {f.column.name for f in c.foreign_keys},
  575. {f.column.name for f in reflected_c.foreign_keys},
  576. )
  577. if c.server_default:
  578. assert isinstance(
  579. reflected_c.server_default, schema.FetchedValue
  580. )
  581. assert len(table.primary_key) == len(reflected_table.primary_key)
  582. for c in table.primary_key:
  583. assert reflected_table.primary_key.columns[c.name] is not None
  584. def assert_types_base(self, c1, c2):
  585. assert c1.type._compare_type_affinity(
  586. c2.type
  587. ), "On column %r, type '%s' doesn't correspond to type '%s'" % (
  588. c1.name,
  589. c1.type,
  590. c2.type,
  591. )
  592. class AssertsExecutionResults(object):
  593. def assert_result(self, result, class_, *objects):
  594. result = list(result)
  595. print(repr(result))
  596. self.assert_list(result, class_, objects)
  597. def assert_list(self, result, class_, list_):
  598. self.assert_(
  599. len(result) == len(list_),
  600. "result list is not the same size as test list, "
  601. + "for class "
  602. + class_.__name__,
  603. )
  604. for i in range(0, len(list_)):
  605. self.assert_row(class_, result[i], list_[i])
  606. def assert_row(self, class_, rowobj, desc):
  607. self.assert_(
  608. rowobj.__class__ is class_, "item class is not " + repr(class_)
  609. )
  610. for key, value in desc.items():
  611. if isinstance(value, tuple):
  612. if isinstance(value[1], list):
  613. self.assert_list(getattr(rowobj, key), value[0], value[1])
  614. else:
  615. self.assert_row(value[0], getattr(rowobj, key), value[1])
  616. else:
  617. self.assert_(
  618. getattr(rowobj, key) == value,
  619. "attribute %s value %s does not match %s"
  620. % (key, getattr(rowobj, key), value),
  621. )
  622. def assert_unordered_result(self, result, cls, *expected):
  623. """As assert_result, but the order of objects is not considered.
  624. The algorithm is very expensive but not a big deal for the small
  625. numbers of rows that the test suite manipulates.
  626. """
  627. class immutabledict(dict):
  628. def __hash__(self):
  629. return id(self)
  630. found = util.IdentitySet(result)
  631. expected = {immutabledict(e) for e in expected}
  632. for wrong in util.itertools_filterfalse(
  633. lambda o: isinstance(o, cls), found
  634. ):
  635. fail(
  636. 'Unexpected type "%s", expected "%s"'
  637. % (type(wrong).__name__, cls.__name__)
  638. )
  639. if len(found) != len(expected):
  640. fail(
  641. 'Unexpected object count "%s", expected "%s"'
  642. % (len(found), len(expected))
  643. )
  644. NOVALUE = object()
  645. def _compare_item(obj, spec):
  646. for key, value in spec.items():
  647. if isinstance(value, tuple):
  648. try:
  649. self.assert_unordered_result(
  650. getattr(obj, key), value[0], *value[1]
  651. )
  652. except AssertionError:
  653. return False
  654. else:
  655. if getattr(obj, key, NOVALUE) != value:
  656. return False
  657. return True
  658. for expected_item in expected:
  659. for found_item in found:
  660. if _compare_item(found_item, expected_item):
  661. found.remove(found_item)
  662. break
  663. else:
  664. fail(
  665. "Expected %s instance with attributes %s not found."
  666. % (cls.__name__, repr(expected_item))
  667. )
  668. return True
  669. def sql_execution_asserter(self, db=None):
  670. if db is None:
  671. from . import db as db
  672. return assertsql.assert_engine(db)
  673. def assert_sql_execution(self, db, callable_, *rules):
  674. with self.sql_execution_asserter(db) as asserter:
  675. result = callable_()
  676. asserter.assert_(*rules)
  677. return result
  678. def assert_sql(self, db, callable_, rules):
  679. newrules = []
  680. for rule in rules:
  681. if isinstance(rule, dict):
  682. newrule = assertsql.AllOf(
  683. *[assertsql.CompiledSQL(k, v) for k, v in rule.items()]
  684. )
  685. else:
  686. newrule = assertsql.CompiledSQL(*rule)
  687. newrules.append(newrule)
  688. return self.assert_sql_execution(db, callable_, *newrules)
  689. def assert_sql_count(self, db, callable_, count):
  690. self.assert_sql_execution(
  691. db, callable_, assertsql.CountStatements(count)
  692. )
  693. def assert_multiple_sql_count(self, dbs, callable_, counts):
  694. recs = [
  695. (self.sql_execution_asserter(db), db, count)
  696. for (db, count) in zip(dbs, counts)
  697. ]
  698. asserters = []
  699. for ctx, db, count in recs:
  700. asserters.append(ctx.__enter__())
  701. try:
  702. return callable_()
  703. finally:
  704. for asserter, (ctx, db, count) in zip(asserters, recs):
  705. ctx.__exit__(None, None, None)
  706. asserter.assert_(assertsql.CountStatements(count))
  707. @contextlib.contextmanager
  708. def assert_execution(self, db, *rules):
  709. with self.sql_execution_asserter(db) as asserter:
  710. yield
  711. asserter.assert_(*rules)
  712. def assert_statement_count(self, db, count):
  713. return self.assert_execution(db, assertsql.CountStatements(count))