fixtures.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. """All pytest-django fixtures"""
  2. import os
  3. from contextlib import contextmanager
  4. from functools import partial
  5. from typing import (
  6. Any, Callable, Generator, Iterable, List, Optional, Tuple, Union,
  7. )
  8. import pytest
  9. from . import live_server_helper
  10. from .django_compat import is_django_unittest
  11. from .lazy_django import get_django_version, skip_if_no_django
  12. TYPE_CHECKING = False
  13. if TYPE_CHECKING:
  14. from typing import Literal
  15. import django
  16. _DjangoDbDatabases = Optional[Union["Literal['__all__']", Iterable[str]]]
  17. # transaction, reset_sequences, databases, serialized_rollback
  18. _DjangoDb = Tuple[bool, bool, _DjangoDbDatabases, bool]
  19. __all__ = [
  20. "django_db_setup",
  21. "db",
  22. "transactional_db",
  23. "django_db_reset_sequences",
  24. "django_db_serialized_rollback",
  25. "admin_user",
  26. "django_user_model",
  27. "django_username_field",
  28. "client",
  29. "async_client",
  30. "admin_client",
  31. "rf",
  32. "async_rf",
  33. "settings",
  34. "live_server",
  35. "_live_server_helper",
  36. "django_assert_num_queries",
  37. "django_assert_max_num_queries",
  38. "django_capture_on_commit_callbacks",
  39. ]
  40. @pytest.fixture(scope="session")
  41. def django_db_modify_db_settings_tox_suffix() -> None:
  42. skip_if_no_django()
  43. tox_environment = os.getenv("TOX_PARALLEL_ENV")
  44. if tox_environment:
  45. # Put a suffix like _py27-django21 on tox workers
  46. _set_suffix_to_test_databases(suffix=tox_environment)
  47. @pytest.fixture(scope="session")
  48. def django_db_modify_db_settings_xdist_suffix(request) -> None:
  49. skip_if_no_django()
  50. xdist_suffix = getattr(request.config, "workerinput", {}).get("workerid")
  51. if xdist_suffix:
  52. # Put a suffix like _gw0, _gw1 etc on xdist processes
  53. _set_suffix_to_test_databases(suffix=xdist_suffix)
  54. @pytest.fixture(scope="session")
  55. def django_db_modify_db_settings_parallel_suffix(
  56. django_db_modify_db_settings_tox_suffix: None,
  57. django_db_modify_db_settings_xdist_suffix: None,
  58. ) -> None:
  59. skip_if_no_django()
  60. @pytest.fixture(scope="session")
  61. def django_db_modify_db_settings(
  62. django_db_modify_db_settings_parallel_suffix: None,
  63. ) -> None:
  64. skip_if_no_django()
  65. @pytest.fixture(scope="session")
  66. def django_db_use_migrations(request) -> bool:
  67. return not request.config.getvalue("nomigrations")
  68. @pytest.fixture(scope="session")
  69. def django_db_keepdb(request) -> bool:
  70. return request.config.getvalue("reuse_db")
  71. @pytest.fixture(scope="session")
  72. def django_db_createdb(request) -> bool:
  73. return request.config.getvalue("create_db")
  74. @pytest.fixture(scope="session")
  75. def django_db_setup(
  76. request,
  77. django_test_environment: None,
  78. django_db_blocker,
  79. django_db_use_migrations: bool,
  80. django_db_keepdb: bool,
  81. django_db_createdb: bool,
  82. django_db_modify_db_settings: None,
  83. ) -> None:
  84. """Top level fixture to ensure test databases are available"""
  85. from django.test.utils import setup_databases, teardown_databases
  86. setup_databases_args = {}
  87. if not django_db_use_migrations:
  88. _disable_migrations()
  89. if django_db_keepdb and not django_db_createdb:
  90. setup_databases_args["keepdb"] = True
  91. with django_db_blocker.unblock():
  92. db_cfg = setup_databases(
  93. verbosity=request.config.option.verbose,
  94. interactive=False,
  95. **setup_databases_args
  96. )
  97. def teardown_database() -> None:
  98. with django_db_blocker.unblock():
  99. try:
  100. teardown_databases(db_cfg, verbosity=request.config.option.verbose)
  101. except Exception as exc:
  102. request.node.warn(
  103. pytest.PytestWarning(
  104. "Error when trying to teardown test databases: %r" % exc
  105. )
  106. )
  107. if not django_db_keepdb:
  108. request.addfinalizer(teardown_database)
  109. @pytest.fixture()
  110. def _django_db_helper(
  111. request,
  112. django_db_setup: None,
  113. django_db_blocker,
  114. ) -> None:
  115. from django import VERSION
  116. if is_django_unittest(request):
  117. return
  118. marker = request.node.get_closest_marker("django_db")
  119. if marker:
  120. (
  121. transactional,
  122. reset_sequences,
  123. databases,
  124. serialized_rollback,
  125. ) = validate_django_db(marker)
  126. else:
  127. (
  128. transactional,
  129. reset_sequences,
  130. databases,
  131. serialized_rollback,
  132. ) = False, False, None, False
  133. transactional = transactional or reset_sequences or (
  134. "transactional_db" in request.fixturenames
  135. or "live_server" in request.fixturenames
  136. )
  137. reset_sequences = reset_sequences or (
  138. "django_db_reset_sequences" in request.fixturenames
  139. )
  140. serialized_rollback = serialized_rollback or (
  141. "django_db_serialized_rollback" in request.fixturenames
  142. )
  143. django_db_blocker.unblock()
  144. request.addfinalizer(django_db_blocker.restore)
  145. import django.db
  146. import django.test
  147. if transactional:
  148. test_case_class = django.test.TransactionTestCase
  149. else:
  150. test_case_class = django.test.TestCase
  151. _reset_sequences = reset_sequences
  152. _serialized_rollback = serialized_rollback
  153. _databases = databases
  154. class PytestDjangoTestCase(test_case_class): # type: ignore[misc,valid-type]
  155. reset_sequences = _reset_sequences
  156. serialized_rollback = _serialized_rollback
  157. if _databases is not None:
  158. databases = _databases
  159. # For non-transactional tests, skip executing `django.test.TestCase`'s
  160. # `setUpClass`/`tearDownClass`, only execute the super class ones.
  161. #
  162. # `TestCase`'s class setup manages the `setUpTestData`/class-level
  163. # transaction functionality. We don't use it; instead we (will) offer
  164. # our own alternatives. So it only adds overhead, and does some things
  165. # which conflict with our (planned) functionality, particularly, it
  166. # closes all database connections in `tearDownClass` which inhibits
  167. # wrapping tests in higher-scoped transactions.
  168. #
  169. # It's possible a new version of Django will add some unrelated
  170. # functionality to these methods, in which case skipping them completely
  171. # would not be desirable. Let's cross that bridge when we get there...
  172. if not transactional:
  173. @classmethod
  174. def setUpClass(cls) -> None:
  175. super(django.test.TestCase, cls).setUpClass()
  176. if (3, 2) <= VERSION < (4, 1):
  177. django.db.transaction.Atomic._ensure_durability = False
  178. @classmethod
  179. def tearDownClass(cls) -> None:
  180. if (3, 2) <= VERSION < (4, 1):
  181. django.db.transaction.Atomic._ensure_durability = True
  182. super(django.test.TestCase, cls).tearDownClass()
  183. PytestDjangoTestCase.setUpClass()
  184. if VERSION >= (4, 0):
  185. request.addfinalizer(PytestDjangoTestCase.doClassCleanups)
  186. request.addfinalizer(PytestDjangoTestCase.tearDownClass)
  187. test_case = PytestDjangoTestCase(methodName="__init__")
  188. test_case._pre_setup()
  189. request.addfinalizer(test_case._post_teardown)
  190. def validate_django_db(marker) -> "_DjangoDb":
  191. """Validate the django_db marker.
  192. It checks the signature and creates the ``transaction``,
  193. ``reset_sequences``, ``databases`` and ``serialized_rollback`` attributes on
  194. the marker which will have the correct values.
  195. Sequence reset and serialized_rollback are only allowed when combined with
  196. transaction.
  197. """
  198. def apifun(
  199. transaction: bool = False,
  200. reset_sequences: bool = False,
  201. databases: "_DjangoDbDatabases" = None,
  202. serialized_rollback: bool = False,
  203. ) -> "_DjangoDb":
  204. return transaction, reset_sequences, databases, serialized_rollback
  205. return apifun(*marker.args, **marker.kwargs)
  206. def _disable_migrations() -> None:
  207. from django.conf import settings
  208. from django.core.management.commands import migrate
  209. class DisableMigrations:
  210. def __contains__(self, item: str) -> bool:
  211. return True
  212. def __getitem__(self, item: str) -> None:
  213. return None
  214. settings.MIGRATION_MODULES = DisableMigrations()
  215. class MigrateSilentCommand(migrate.Command):
  216. def handle(self, *args, **kwargs):
  217. kwargs["verbosity"] = 0
  218. return super().handle(*args, **kwargs)
  219. migrate.Command = MigrateSilentCommand
  220. def _set_suffix_to_test_databases(suffix: str) -> None:
  221. from django.conf import settings
  222. for db_settings in settings.DATABASES.values():
  223. test_name = db_settings.get("TEST", {}).get("NAME")
  224. if not test_name:
  225. if db_settings["ENGINE"] == "django.db.backends.sqlite3":
  226. continue
  227. test_name = "test_{}".format(db_settings["NAME"])
  228. if test_name == ":memory:":
  229. continue
  230. db_settings.setdefault("TEST", {})
  231. db_settings["TEST"]["NAME"] = "{}_{}".format(test_name, suffix)
  232. # ############### User visible fixtures ################
  233. @pytest.fixture(scope="function")
  234. def db(_django_db_helper: None) -> None:
  235. """Require a django test database.
  236. This database will be setup with the default fixtures and will have
  237. the transaction management disabled. At the end of the test the outer
  238. transaction that wraps the test itself will be rolled back to undo any
  239. changes to the database (in case the backend supports transactions).
  240. This is more limited than the ``transactional_db`` fixture but
  241. faster.
  242. If both ``db`` and ``transactional_db`` are requested,
  243. ``transactional_db`` takes precedence.
  244. """
  245. # The `_django_db_helper` fixture checks if `db` is requested.
  246. @pytest.fixture(scope="function")
  247. def transactional_db(_django_db_helper: None) -> None:
  248. """Require a django test database with transaction support.
  249. This will re-initialise the django database for each test and is
  250. thus slower than the normal ``db`` fixture.
  251. If you want to use the database with transactions you must request
  252. this resource.
  253. If both ``db`` and ``transactional_db`` are requested,
  254. ``transactional_db`` takes precedence.
  255. """
  256. # The `_django_db_helper` fixture checks if `transactional_db` is requested.
  257. @pytest.fixture(scope="function")
  258. def django_db_reset_sequences(
  259. _django_db_helper: None,
  260. transactional_db: None,
  261. ) -> None:
  262. """Require a transactional test database with sequence reset support.
  263. This requests the ``transactional_db`` fixture, and additionally
  264. enforces a reset of all auto increment sequences. If the enquiring
  265. test relies on such values (e.g. ids as primary keys), you should
  266. request this resource to ensure they are consistent across tests.
  267. """
  268. # The `_django_db_helper` fixture checks if `django_db_reset_sequences`
  269. # is requested.
  270. @pytest.fixture(scope="function")
  271. def django_db_serialized_rollback(
  272. _django_db_helper: None,
  273. db: None,
  274. ) -> None:
  275. """Require a test database with serialized rollbacks.
  276. This requests the ``db`` fixture, and additionally performs rollback
  277. emulation - serializes the database contents during setup and restores
  278. it during teardown.
  279. This fixture may be useful for transactional tests, so is usually combined
  280. with ``transactional_db``, but can also be useful on databases which do not
  281. support transactions.
  282. Note that this will slow down that test suite by approximately 3x.
  283. """
  284. # The `_django_db_helper` fixture checks if `django_db_serialized_rollback`
  285. # is requested.
  286. @pytest.fixture()
  287. def client() -> "django.test.client.Client":
  288. """A Django test client instance."""
  289. skip_if_no_django()
  290. from django.test.client import Client
  291. return Client()
  292. @pytest.fixture()
  293. def async_client() -> "django.test.client.AsyncClient":
  294. """A Django test async client instance."""
  295. skip_if_no_django()
  296. from django.test.client import AsyncClient
  297. return AsyncClient()
  298. @pytest.fixture()
  299. def django_user_model(db: None):
  300. """The class of Django's user model."""
  301. from django.contrib.auth import get_user_model
  302. return get_user_model()
  303. @pytest.fixture()
  304. def django_username_field(django_user_model) -> str:
  305. """The fieldname for the username used with Django's user model."""
  306. return django_user_model.USERNAME_FIELD
  307. @pytest.fixture()
  308. def admin_user(
  309. db: None,
  310. django_user_model,
  311. django_username_field: str,
  312. ):
  313. """A Django admin user.
  314. This uses an existing user with username "admin", or creates a new one with
  315. password "password".
  316. """
  317. UserModel = django_user_model
  318. username_field = django_username_field
  319. username = "admin@example.com" if username_field == "email" else "admin"
  320. try:
  321. # The default behavior of `get_by_natural_key()` is to look up by `username_field`.
  322. # However the user model is free to override it with any sort of custom behavior.
  323. # The Django authentication backend already assumes the lookup is by username,
  324. # so we can assume so as well.
  325. user = UserModel._default_manager.get_by_natural_key(username)
  326. except UserModel.DoesNotExist:
  327. user_data = {}
  328. if "email" in UserModel.REQUIRED_FIELDS:
  329. user_data["email"] = "admin@example.com"
  330. user_data["password"] = "password"
  331. user_data[username_field] = username
  332. user = UserModel._default_manager.create_superuser(**user_data)
  333. return user
  334. @pytest.fixture()
  335. def admin_client(
  336. db: None,
  337. admin_user,
  338. ) -> "django.test.client.Client":
  339. """A Django test client logged in as an admin user."""
  340. from django.test.client import Client
  341. client = Client()
  342. client.force_login(admin_user)
  343. return client
  344. @pytest.fixture()
  345. def rf() -> "django.test.client.RequestFactory":
  346. """RequestFactory instance"""
  347. skip_if_no_django()
  348. from django.test.client import RequestFactory
  349. return RequestFactory()
  350. @pytest.fixture()
  351. def async_rf() -> "django.test.client.AsyncRequestFactory":
  352. """AsyncRequestFactory instance"""
  353. skip_if_no_django()
  354. from django.test.client import AsyncRequestFactory
  355. return AsyncRequestFactory()
  356. class SettingsWrapper:
  357. _to_restore = [] # type: List[Any]
  358. def __delattr__(self, attr: str) -> None:
  359. from django.test import override_settings
  360. override = override_settings()
  361. override.enable()
  362. from django.conf import settings
  363. delattr(settings, attr)
  364. self._to_restore.append(override)
  365. def __setattr__(self, attr: str, value) -> None:
  366. from django.test import override_settings
  367. override = override_settings(**{attr: value})
  368. override.enable()
  369. self._to_restore.append(override)
  370. def __getattr__(self, attr: str):
  371. from django.conf import settings
  372. return getattr(settings, attr)
  373. def finalize(self) -> None:
  374. for override in reversed(self._to_restore):
  375. override.disable()
  376. del self._to_restore[:]
  377. @pytest.fixture()
  378. def settings():
  379. """A Django settings object which restores changes after the testrun"""
  380. skip_if_no_django()
  381. wrapper = SettingsWrapper()
  382. yield wrapper
  383. wrapper.finalize()
  384. @pytest.fixture(scope="session")
  385. def live_server(request):
  386. """Run a live Django server in the background during tests
  387. The address the server is started from is taken from the
  388. --liveserver command line option or if this is not provided from
  389. the DJANGO_LIVE_TEST_SERVER_ADDRESS environment variable. If
  390. neither is provided ``localhost`` is used. See the Django
  391. documentation for its full syntax.
  392. NOTE: If the live server needs database access to handle a request
  393. your test will have to request database access. Furthermore
  394. when the tests want to see data added by the live-server (or
  395. the other way around) transactional database access will be
  396. needed as data inside a transaction is not shared between
  397. the live server and test code.
  398. Static assets will be automatically served when
  399. ``django.contrib.staticfiles`` is available in INSTALLED_APPS.
  400. """
  401. skip_if_no_django()
  402. addr = request.config.getvalue("liveserver") or os.getenv(
  403. "DJANGO_LIVE_TEST_SERVER_ADDRESS"
  404. ) or "localhost"
  405. server = live_server_helper.LiveServer(addr)
  406. request.addfinalizer(server.stop)
  407. return server
  408. @pytest.fixture(autouse=True, scope="function")
  409. def _live_server_helper(request) -> None:
  410. """Helper to make live_server work, internal to pytest-django.
  411. This helper will dynamically request the transactional_db fixture
  412. for a test which uses the live_server fixture. This allows the
  413. server and test to access the database without having to mark
  414. this explicitly which is handy since it is usually required and
  415. matches the Django behaviour.
  416. The separate helper is required since live_server can not request
  417. transactional_db directly since it is session scoped instead of
  418. function-scoped.
  419. It will also override settings only for the duration of the test.
  420. """
  421. if "live_server" not in request.fixturenames:
  422. return
  423. request.getfixturevalue("transactional_db")
  424. live_server = request.getfixturevalue("live_server")
  425. live_server._live_server_modified_settings.enable()
  426. request.addfinalizer(live_server._live_server_modified_settings.disable)
  427. @contextmanager
  428. def _assert_num_queries(
  429. config,
  430. num: int,
  431. exact: bool = True,
  432. connection=None,
  433. info=None,
  434. ) -> Generator["django.test.utils.CaptureQueriesContext", None, None]:
  435. from django.test.utils import CaptureQueriesContext
  436. if connection is None:
  437. from django.db import connection as conn
  438. else:
  439. conn = connection
  440. verbose = config.getoption("verbose") > 0
  441. with CaptureQueriesContext(conn) as context:
  442. yield context
  443. num_performed = len(context)
  444. if exact:
  445. failed = num != num_performed
  446. else:
  447. failed = num_performed > num
  448. if failed:
  449. msg = "Expected to perform {} queries {}{}".format(
  450. num,
  451. "" if exact else "or less ",
  452. "but {} done".format(
  453. num_performed == 1 and "1 was" or "{} were".format(num_performed)
  454. ),
  455. )
  456. if info:
  457. msg += "\n{}".format(info)
  458. if verbose:
  459. sqls = (q["sql"] for q in context.captured_queries)
  460. msg += "\n\nQueries:\n========\n\n" + "\n\n".join(sqls)
  461. else:
  462. msg += " (add -v option to show queries)"
  463. pytest.fail(msg)
  464. @pytest.fixture(scope="function")
  465. def django_assert_num_queries(pytestconfig):
  466. return partial(_assert_num_queries, pytestconfig)
  467. @pytest.fixture(scope="function")
  468. def django_assert_max_num_queries(pytestconfig):
  469. return partial(_assert_num_queries, pytestconfig, exact=False)
  470. @contextmanager
  471. def _capture_on_commit_callbacks(
  472. *,
  473. using: Optional[str] = None,
  474. execute: bool = False
  475. ):
  476. from django.db import DEFAULT_DB_ALIAS, connections
  477. from django.test import TestCase
  478. if using is None:
  479. using = DEFAULT_DB_ALIAS
  480. # Polyfill of Django code as of Django 3.2.
  481. if get_django_version() < (3, 2):
  482. callbacks = [] # type: List[Callable[[], Any]]
  483. start_count = len(connections[using].run_on_commit)
  484. try:
  485. yield callbacks
  486. finally:
  487. run_on_commit = connections[using].run_on_commit[start_count:]
  488. callbacks[:] = [func for sids, func in run_on_commit]
  489. if execute:
  490. for callback in callbacks:
  491. callback()
  492. else:
  493. with TestCase.captureOnCommitCallbacks(using=using, execute=execute) as callbacks:
  494. yield callbacks
  495. @pytest.fixture(scope="function")
  496. def django_capture_on_commit_callbacks():
  497. return _capture_on_commit_callbacks