You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

763 lines
23KB

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