assertions.py 25 KB

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