fixtures.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. """All pytest-django fixtures"""
  2. from __future__ import with_statement
  3. import os
  4. import pytest
  5. from . import live_server_helper
  6. from .django_compat import is_django_unittest
  7. from .pytest_compat import getfixturevalue
  8. from .lazy_django import get_django_version, skip_if_no_django
  9. __all__ = ['django_db_setup', 'db', 'transactional_db', 'admin_user',
  10. 'django_user_model', 'django_username_field',
  11. 'client', 'admin_client', 'rf', 'settings', 'live_server',
  12. '_live_server_helper']
  13. @pytest.fixture(scope='session')
  14. def django_db_modify_db_settings_xdist_suffix(request):
  15. skip_if_no_django()
  16. from django.conf import settings
  17. for db_settings in settings.DATABASES.values():
  18. try:
  19. test_name = db_settings['TEST']['NAME']
  20. except KeyError:
  21. test_name = None
  22. if not test_name:
  23. if db_settings['ENGINE'] == 'django.db.backends.sqlite3':
  24. return ':memory:'
  25. else:
  26. test_name = 'test_{}'.format(db_settings['NAME'])
  27. # Put a suffix like _gw0, _gw1 etc on xdist processes
  28. xdist_suffix = getattr(request.config, 'slaveinput', {}).get('slaveid')
  29. if test_name != ':memory:' and xdist_suffix is not None:
  30. test_name = '{}_{}'.format(test_name, xdist_suffix)
  31. db_settings.setdefault('TEST', {})
  32. db_settings['TEST']['NAME'] = test_name
  33. @pytest.fixture(scope='session')
  34. def django_db_modify_db_settings(django_db_modify_db_settings_xdist_suffix):
  35. skip_if_no_django()
  36. @pytest.fixture(scope='session')
  37. def django_db_use_migrations(request):
  38. return not request.config.getvalue('nomigrations')
  39. @pytest.fixture(scope='session')
  40. def django_db_keepdb(request):
  41. return (request.config.getvalue('reuse_db') and not
  42. request.config.getvalue('create_db'))
  43. @pytest.fixture(scope='session')
  44. def django_db_setup(
  45. request,
  46. django_test_environment,
  47. django_db_blocker,
  48. django_db_use_migrations,
  49. django_db_keepdb,
  50. django_db_modify_db_settings,
  51. ):
  52. """Top level fixture to ensure test databases are available"""
  53. from .compat import setup_databases, teardown_databases
  54. setup_databases_args = {}
  55. if not django_db_use_migrations:
  56. _disable_native_migrations()
  57. if django_db_keepdb:
  58. if get_django_version() >= (1, 8):
  59. setup_databases_args['keepdb'] = True
  60. else:
  61. # Django 1.7 compatibility
  62. from .db_reuse import monkey_patch_creation_for_db_reuse
  63. with django_db_blocker.unblock():
  64. monkey_patch_creation_for_db_reuse()
  65. with django_db_blocker.unblock():
  66. db_cfg = setup_databases(
  67. verbosity=pytest.config.option.verbose,
  68. interactive=False,
  69. **setup_databases_args
  70. )
  71. def teardown_database():
  72. with django_db_blocker.unblock():
  73. teardown_databases(
  74. db_cfg,
  75. verbosity=pytest.config.option.verbose,
  76. )
  77. if not django_db_keepdb:
  78. request.addfinalizer(teardown_database)
  79. def _django_db_fixture_helper(transactional, request, django_db_blocker):
  80. if is_django_unittest(request):
  81. return
  82. if not transactional and 'live_server' in request.funcargnames:
  83. # Do nothing, we get called with transactional=True, too.
  84. return
  85. django_db_blocker.unblock()
  86. request.addfinalizer(django_db_blocker.restore)
  87. if transactional:
  88. from django.test import TransactionTestCase as django_case
  89. else:
  90. from django.test import TestCase as django_case
  91. test_case = django_case(methodName='__init__')
  92. test_case._pre_setup()
  93. request.addfinalizer(test_case._post_teardown)
  94. def _disable_native_migrations():
  95. from django.conf import settings
  96. from .migrations import DisableMigrations
  97. settings.MIGRATION_MODULES = DisableMigrations()
  98. # ############### User visible fixtures ################
  99. @pytest.fixture(scope='function')
  100. def db(request, django_db_setup, django_db_blocker):
  101. """Require a django test database
  102. This database will be setup with the default fixtures and will have
  103. the transaction management disabled. At the end of the test the outer
  104. transaction that wraps the test itself will be rolled back to undo any
  105. changes to the database (in case the backend supports transactions).
  106. This is more limited than the ``transactional_db`` resource but
  107. faster.
  108. If both this and ``transactional_db`` are requested then the
  109. database setup will behave as only ``transactional_db`` was
  110. requested.
  111. """
  112. if 'transactional_db' in request.funcargnames \
  113. or 'live_server' in request.funcargnames:
  114. getfixturevalue(request, 'transactional_db')
  115. else:
  116. _django_db_fixture_helper(False, request, django_db_blocker)
  117. @pytest.fixture(scope='function')
  118. def transactional_db(request, django_db_setup, django_db_blocker):
  119. """Require a django test database with transaction support
  120. This will re-initialise the django database for each test and is
  121. thus slower than the normal ``db`` fixture.
  122. If you want to use the database with transactions you must request
  123. this resource. If both this and ``db`` are requested then the
  124. database setup will behave as only ``transactional_db`` was
  125. requested.
  126. """
  127. _django_db_fixture_helper(True, request, django_db_blocker)
  128. @pytest.fixture()
  129. def client():
  130. """A Django test client instance."""
  131. skip_if_no_django()
  132. from django.test.client import Client
  133. return Client()
  134. @pytest.fixture()
  135. def django_user_model(db):
  136. """The class of Django's user model."""
  137. from django.contrib.auth import get_user_model
  138. return get_user_model()
  139. @pytest.fixture()
  140. def django_username_field(django_user_model):
  141. """The fieldname for the username used with Django's user model."""
  142. return django_user_model.USERNAME_FIELD
  143. @pytest.fixture()
  144. def admin_user(db, django_user_model, django_username_field):
  145. """A Django admin user.
  146. This uses an existing user with username "admin", or creates a new one with
  147. password "password".
  148. """
  149. UserModel = django_user_model
  150. username_field = django_username_field
  151. try:
  152. user = UserModel._default_manager.get(**{username_field: 'admin'})
  153. except UserModel.DoesNotExist:
  154. extra_fields = {}
  155. if username_field != 'username':
  156. extra_fields[username_field] = 'admin'
  157. user = UserModel._default_manager.create_superuser(
  158. 'admin', 'admin@example.com', 'password', **extra_fields)
  159. return user
  160. @pytest.fixture()
  161. def admin_client(db, admin_user):
  162. """A Django test client logged in as an admin user."""
  163. from django.test.client import Client
  164. client = Client()
  165. client.login(username=admin_user.username, password='password')
  166. return client
  167. @pytest.fixture()
  168. def rf():
  169. """RequestFactory instance"""
  170. skip_if_no_django()
  171. from django.test.client import RequestFactory
  172. return RequestFactory()
  173. class SettingsWrapper(object):
  174. _to_restore = []
  175. def __delattr__(self, attr):
  176. from django.test import override_settings
  177. override = override_settings()
  178. override.enable()
  179. from django.conf import settings
  180. delattr(settings, attr)
  181. self._to_restore.append(override)
  182. def __setattr__(self, attr, value):
  183. from django.test import override_settings
  184. override = override_settings(**{
  185. attr: value
  186. })
  187. override.enable()
  188. self._to_restore.append(override)
  189. def __getattr__(self, item):
  190. from django.conf import settings
  191. return getattr(settings, item)
  192. def finalize(self):
  193. for override in reversed(self._to_restore):
  194. override.disable()
  195. del self._to_restore[:]
  196. @pytest.yield_fixture()
  197. def settings():
  198. """A Django settings object which restores changes after the testrun"""
  199. skip_if_no_django()
  200. wrapper = SettingsWrapper()
  201. yield wrapper
  202. wrapper.finalize()
  203. @pytest.fixture(scope='session')
  204. def live_server(request):
  205. """Run a live Django server in the background during tests
  206. The address the server is started from is taken from the
  207. --liveserver command line option or if this is not provided from
  208. the DJANGO_LIVE_TEST_SERVER_ADDRESS environment variable. If
  209. neither is provided ``localhost:8081,8100-8200`` is used. See the
  210. Django documentation for it's full syntax.
  211. NOTE: If the live server needs database access to handle a request
  212. your test will have to request database access. Furthermore
  213. when the tests want to see data added by the live-server (or
  214. the other way around) transactional database access will be
  215. needed as data inside a transaction is not shared between
  216. the live server and test code.
  217. Static assets will be automatically served when
  218. ``django.contrib.staticfiles`` is available in INSTALLED_APPS.
  219. """
  220. skip_if_no_django()
  221. import django
  222. addr = (request.config.getvalue('liveserver') or
  223. os.getenv('DJANGO_LIVE_TEST_SERVER_ADDRESS'))
  224. if addr and django.VERSION >= (1, 11) and ':' in addr:
  225. request.config.warn('D001', 'Specifying a live server port is not supported '
  226. 'in Django 1.11. This will be an error in a future '
  227. 'pytest-django release.')
  228. if not addr:
  229. if django.VERSION < (1, 11):
  230. addr = 'localhost:8081,8100-8200'
  231. else:
  232. addr = 'localhost'
  233. server = live_server_helper.LiveServer(addr)
  234. request.addfinalizer(server.stop)
  235. return server
  236. @pytest.fixture(autouse=True, scope='function')
  237. def _live_server_helper(request):
  238. """Helper to make live_server work, internal to pytest-django.
  239. This helper will dynamically request the transactional_db fixture
  240. for a test which uses the live_server fixture. This allows the
  241. server and test to access the database without having to mark
  242. this explicitly which is handy since it is usually required and
  243. matches the Django behaviour.
  244. The separate helper is required since live_server can not request
  245. transactional_db directly since it is session scoped instead of
  246. function-scoped.
  247. """
  248. if 'live_server' in request.funcargnames:
  249. getfixturevalue(request, 'transactional_db')