advanced.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. =======================
  2. Advanced testing topics
  3. =======================
  4. The request factory
  5. ===================
  6. .. currentmodule:: django.test
  7. .. class:: RequestFactory
  8. The :class:`~django.test.RequestFactory` shares the same API as
  9. the test client. However, instead of behaving like a browser, the
  10. RequestFactory provides a way to generate a request instance that can
  11. be used as the first argument to any view. This means you can test a
  12. view function the same way as you would test any other function -- as
  13. a black box, with exactly known inputs, testing for specific outputs.
  14. The API for the :class:`~django.test.RequestFactory` is a slightly
  15. restricted subset of the test client API:
  16. * It only has access to the HTTP methods :meth:`~Client.get()`,
  17. :meth:`~Client.post()`, :meth:`~Client.put()`,
  18. :meth:`~Client.delete()`, :meth:`~Client.head()` and
  19. :meth:`~Client.options()`.
  20. * These methods accept all the same arguments *except* for
  21. ``follows``. Since this is just a factory for producing
  22. requests, it's up to you to handle the response.
  23. * It does not support middleware. Session and authentication
  24. attributes must be supplied by the test itself if required
  25. for the view to function properly.
  26. Example
  27. -------
  28. The following is a simple unit test using the request factory::
  29. from django.contrib.auth.models import User
  30. from django.test import TestCase, RequestFactory
  31. class SimpleTest(TestCase):
  32. def setUp(self):
  33. # Every test needs access to the request factory.
  34. self.factory = RequestFactory()
  35. self.user = User.objects.create_user(
  36. username='jacob', email='jacob@…', password='top_secret')
  37. def test_details(self):
  38. # Create an instance of a GET request.
  39. request = self.factory.get('/customer/details')
  40. # Recall that middleware are not supported. You can simulate a
  41. # logged-in user by setting request.user manually.
  42. request.user = self.user
  43. # Test my_view() as if it were deployed at /customer/details
  44. response = my_view(request)
  45. self.assertEqual(response.status_code, 200)
  46. .. _topics-testing-advanced-multidb:
  47. Tests and multiple databases
  48. ============================
  49. .. _topics-testing-primaryreplica:
  50. Testing primary/replica configurations
  51. --------------------------------------
  52. If you're testing a multiple database configuration with primary/replica
  53. (referred to as master/slave by some databases) replication, this strategy of
  54. creating test databases poses a problem.
  55. When the test databases are created, there won't be any replication,
  56. and as a result, data created on the primary won't be seen on the
  57. replica.
  58. To compensate for this, Django allows you to define that a database is
  59. a *test mirror*. Consider the following (simplified) example database
  60. configuration::
  61. DATABASES = {
  62. 'default': {
  63. 'ENGINE': 'django.db.backends.mysql',
  64. 'NAME': 'myproject',
  65. 'HOST': 'dbprimary',
  66. # ... plus some other settings
  67. },
  68. 'replica': {
  69. 'ENGINE': 'django.db.backends.mysql',
  70. 'NAME': 'myproject',
  71. 'HOST': 'dbreplica',
  72. 'TEST_MIRROR': 'default'
  73. # ... plus some other settings
  74. }
  75. }
  76. In this setup, we have two database servers: ``dbprimary``, described
  77. by the database alias ``default``, and ``dbreplica`` described by the
  78. alias ``replica``. As you might expect, ``dbreplica`` has been configured
  79. by the database administrator as a read replica of ``dbprimary``, so in
  80. normal activity, any write to ``default`` will appear on ``replica``.
  81. If Django created two independent test databases, this would break any
  82. tests that expected replication to occur. However, the ``replica``
  83. database has been configured as a test mirror (using the
  84. :setting:`TEST_MIRROR` setting), indicating that under testing,
  85. ``replica`` should be treated as a mirror of ``default``.
  86. When the test environment is configured, a test version of ``replica``
  87. will *not* be created. Instead the connection to ``replica``
  88. will be redirected to point at ``default``. As a result, writes to
  89. ``default`` will appear on ``replica`` -- but because they are actually
  90. the same database, not because there is data replication between the
  91. two databases.
  92. .. _topics-testing-creation-dependencies:
  93. Controlling creation order for test databases
  94. ---------------------------------------------
  95. By default, Django will assume all databases depend on the ``default``
  96. database and therefore always create the ``default`` database first.
  97. However, no guarantees are made on the creation order of any other
  98. databases in your test setup.
  99. If your database configuration requires a specific creation order, you
  100. can specify the dependencies that exist using the
  101. :setting:`TEST_DEPENDENCIES` setting. Consider the following
  102. (simplified) example database configuration::
  103. DATABASES = {
  104. 'default': {
  105. # ... db settings
  106. 'TEST_DEPENDENCIES': ['diamonds']
  107. },
  108. 'diamonds': {
  109. # ... db settings
  110. 'TEST_DEPENDENCIES': []
  111. },
  112. 'clubs': {
  113. # ... db settings
  114. 'TEST_DEPENDENCIES': ['diamonds']
  115. },
  116. 'spades': {
  117. # ... db settings
  118. 'TEST_DEPENDENCIES': ['diamonds','hearts']
  119. },
  120. 'hearts': {
  121. # ... db settings
  122. 'TEST_DEPENDENCIES': ['diamonds','clubs']
  123. }
  124. }
  125. Under this configuration, the ``diamonds`` database will be created first,
  126. as it is the only database alias without dependencies. The ``default`` and
  127. ``clubs`` alias will be created next (although the order of creation of this
  128. pair is not guaranteed); then ``hearts``; and finally ``spades``.
  129. If there are any circular dependencies in the
  130. :setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
  131. exception will be raised.
  132. Advanced features of ``TransactionTestCase``
  133. ============================================
  134. .. attribute:: TransactionTestCase.available_apps
  135. .. warning::
  136. This attribute is a private API. It may be changed or removed without
  137. a deprecation period in the future, for instance to accommodate changes
  138. in application loading.
  139. It's used to optimize Django's own test suite, which contains hundreds
  140. of models but no relations between models in different applications.
  141. By default, ``available_apps`` is set to ``None``. After each test, Django
  142. calls :djadmin:`flush` to reset the database state. This empties all tables
  143. and emits the :data:`~django.db.models.signals.post_migrate` signal, which
  144. re-creates one content type and three permissions for each model. This
  145. operation gets expensive proportionally to the number of models.
  146. Setting ``available_apps`` to a list of applications instructs Django to
  147. behave as if only the models from these applications were available. The
  148. behavior of ``TransactionTestCase`` changes as follows:
  149. - :data:`~django.db.models.signals.post_migrate` is fired before each
  150. test to create the content types and permissions for each model in
  151. available apps, in case they're missing.
  152. - After each test, Django empties only tables corresponding to models in
  153. available apps. However, at the database level, truncation may cascade to
  154. related models in unavailable apps. Furthermore
  155. :data:`~django.db.models.signals.post_migrate` isn't fired; it will be
  156. fired by the next ``TransactionTestCase``, after the correct set of
  157. applications is selected.
  158. Since the database isn't fully flushed, if a test creates instances of
  159. models not included in ``available_apps``, they will leak and they may
  160. cause unrelated tests to fail. Be careful with tests that use sessions;
  161. the default session engine stores them in the database.
  162. Since :data:`~django.db.models.signals.post_migrate` isn't emitted after
  163. flushing the database, its state after a ``TransactionTestCase`` isn't the
  164. same as after a ``TestCase``: it's missing the rows created by listeners
  165. to :data:`~django.db.models.signals.post_migrate`. Considering the
  166. :ref:`order in which tests are executed <order-of-tests>`, this isn't an
  167. issue, provided either all ``TransactionTestCase`` in a given test suite
  168. declare ``available_apps``, or none of them.
  169. ``available_apps`` is mandatory in Django's own test suite.
  170. .. attribute:: TransactionTestCase.reset_sequences
  171. Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
  172. sure sequences are always reset before the test run::
  173. class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
  174. reset_sequences = True
  175. def test_animal_pk(self):
  176. lion = Animal.objects.create(name="lion", sound="roar")
  177. # lion.pk is guaranteed to always be 1
  178. self.assertEqual(lion.pk, 1)
  179. Unless you are explicitly testing primary keys sequence numbers, it is
  180. recommended that you do not hard code primary key values in tests.
  181. Using ``reset_sequences = True`` will slow down the test, since the primary
  182. key reset is an relatively expensive database operation.
  183. Running tests outside the test runner
  184. =====================================
  185. If you want to run tests outside of ``./manage.py test`` -- for example,
  186. from a shell prompt -- you will need to set up the test
  187. environment first. Django provides a convenience method to do this::
  188. >>> from django.test.utils import setup_test_environment
  189. >>> setup_test_environment()
  190. :func:`~django.test.utils.setup_test_environment` puts several Django features
  191. into modes that allow for repeatable testing, but does not create the test
  192. databases; :func:`django.test.runner.DiscoverRunner.setup_databases`
  193. takes care of that.
  194. The call to :func:`~django.test.utils.setup_test_environment` is made
  195. automatically as part of the setup of ``./manage.py test``. You only
  196. need to manually invoke this method if you're not using running your
  197. tests via Django's test runner.
  198. .. versionchanged:: 1.7
  199. If you are not using a management command to invoke the tests, you will also
  200. need to first setup Django itself using :func:`django.setup()`.
  201. .. _other-testing-frameworks:
  202. Using different testing frameworks
  203. ==================================
  204. Clearly, :mod:`unittest` is not the only Python testing framework. While Django
  205. doesn't provide explicit support for alternative frameworks, it does provide a
  206. way to invoke tests constructed for an alternative framework as if they were
  207. normal Django tests.
  208. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  209. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  210. ``'django.test.runner.DiscoverRunner'``. This class defines the default Django
  211. testing behavior. This behavior involves:
  212. #. Performing global pre-test setup.
  213. #. Looking for tests in any file below the current directory whose name matches
  214. the pattern ``test*.py``.
  215. #. Creating the test databases.
  216. #. Running ``migrate`` to install models and initial data into the test
  217. databases.
  218. #. Running the tests that were found.
  219. #. Destroying the test databases.
  220. #. Performing global post-test teardown.
  221. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  222. that class, Django will execute your test runner whenever you run
  223. ``./manage.py test``. In this way, it is possible to use any test framework
  224. that can be executed from Python code, or to modify the Django test execution
  225. process to satisfy whatever testing requirements you may have.
  226. .. _topics-testing-test_runner:
  227. Defining a test runner
  228. ----------------------
  229. .. currentmodule:: django.test.runner
  230. A test runner is a class defining a ``run_tests()`` method. Django ships
  231. with a ``DiscoverRunner`` class that defines the default Django testing
  232. behavior. This class defines the ``run_tests()`` entry point, plus a
  233. selection of other methods that are used to by ``run_tests()`` to set up,
  234. execute and tear down the test suite.
  235. .. class:: DiscoverRunner(pattern='test*.py', top_level=None, verbosity=1, interactive=True, failfast=True, **kwargs)
  236. ``DiscoverRunner`` will search for tests in any file matching ``pattern``.
  237. ``top_level`` can be used to specify the directory containing your
  238. top-level Python modules. Usually Django can figure this out automatically,
  239. so it's not necessary to specify this option. If specified, it should
  240. generally be the directory containing your ``manage.py`` file.
  241. ``verbosity`` determines the amount of notification and debug information
  242. that will be printed to the console; ``0`` is no output, ``1`` is normal
  243. output, and ``2`` is verbose output.
  244. If ``interactive`` is ``True``, the test suite has permission to ask the
  245. user for instructions when the test suite is executed. An example of this
  246. behavior would be asking for permission to delete an existing test
  247. database. If ``interactive`` is ``False``, the test suite must be able to
  248. run without any manual intervention.
  249. If ``failfast`` is ``True``, the test suite will stop running after the
  250. first test failure is detected.
  251. Django may, from time to time, extend the capabilities of the test runner
  252. by adding new arguments. The ``**kwargs`` declaration allows for this
  253. expansion. If you subclass ``DiscoverRunner`` or write your own test
  254. runner, ensure it accepts ``**kwargs``.
  255. Your test runner may also define additional command-line options.
  256. Create or override an ``add_arguments(cls, parser)`` class method and add
  257. custom arguments by calling ``parser.add_argument()`` inside the method, so
  258. that the :djadmin:`test` command will be able to use those arguments.
  259. .. versionchanged:: 1.8
  260. Previously, you had to provide an ``option_list`` attribute to a
  261. subclassed test runner to add options to the list of command-line
  262. options that the :djadmin:`test` command could use.
  263. Attributes
  264. ~~~~~~~~~~
  265. .. attribute:: DiscoverRunner.test_suite
  266. .. versionadded:: 1.7
  267. The class used to build the test suite. By default it is set to
  268. ``unittest.TestSuite``. This can be overridden if you wish to implement
  269. different logic for collecting tests.
  270. .. attribute:: DiscoverRunner.test_runner
  271. .. versionadded:: 1.7
  272. This is the class of the low-level test runner which is used to execute
  273. the individual tests and format the results. By default it is set to
  274. ``unittest.TextTestRunner``. Despite the unfortunate similarity in
  275. naming conventions, this is not the same type of class as
  276. ``DiscoverRunner``, which covers a broader set of responsibilities. You
  277. can override this attribute to modify the way tests are run and reported.
  278. .. attribute:: DiscoverRunner.test_loader
  279. This is the class that loads tests, whether from TestCases or modules or
  280. otherwise and bundles them into test suites for the runner to execute.
  281. By default it is set to ``unittest.defaultTestLoader``. You can override
  282. this attribute if your tests are going to be loaded in unusual ways.
  283. .. attribute:: DiscoverRunner.option_list
  284. This is the tuple of ``optparse`` options which will be fed into the
  285. management command's ``OptionParser`` for parsing arguments. See the
  286. documentation for Python's ``optparse`` module for more details.
  287. .. deprecated:: 1.8
  288. You should now override the :meth:`~DiscoverRunner.add_arguments` class
  289. method to add custom arguments accepted by the :djadmin:`test`
  290. management command.
  291. Methods
  292. ~~~~~~~
  293. .. method:: DiscoverRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  294. Run the test suite.
  295. ``test_labels`` allows you to specify which tests to run and supports
  296. several formats (see :meth:`DiscoverRunner.build_suite` for a list of
  297. supported formats).
  298. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  299. suite that is executed by the test runner. These extra tests are run
  300. in addition to those discovered in the modules listed in ``test_labels``.
  301. This method should return the number of tests that failed.
  302. .. classmethod:: DiscoverRunner.add_arguments(parser)
  303. .. versionadded:: 1.8
  304. Override this class method to add custom arguments accepted by the
  305. :djadmin:`test` management command. See
  306. :py:meth:`argparse.ArgumentParser.add_argument()` for details about adding
  307. arguments to a parser.
  308. .. method:: DiscoverRunner.setup_test_environment(**kwargs)
  309. Sets up the test environment by calling
  310. :func:`~django.test.utils.setup_test_environment` and setting
  311. :setting:`DEBUG` to ``False``.
  312. .. method:: DiscoverRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  313. Constructs a test suite that matches the test labels provided.
  314. ``test_labels`` is a list of strings describing the tests to be run. A test
  315. label can take one of four forms:
  316. * ``path.to.test_module.TestCase.test_method`` -- Run a single test method
  317. in a test case.
  318. * ``path.to.test_module.TestCase`` -- Run all the test methods in a test
  319. case.
  320. * ``path.to.module`` -- Search for and run all tests in the named Python
  321. package or module.
  322. * ``path/to/directory`` -- Search for and run all tests below the named
  323. directory.
  324. If ``test_labels`` has a value of ``None``, the test runner will search for
  325. tests in all files below the current directory whose names match its
  326. ``pattern`` (see above).
  327. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  328. suite that is executed by the test runner. These extra tests are run
  329. in addition to those discovered in the modules listed in ``test_labels``.
  330. Returns a ``TestSuite`` instance ready to be run.
  331. .. method:: DiscoverRunner.setup_databases(**kwargs)
  332. Creates the test databases.
  333. Returns a data structure that provides enough detail to undo the changes
  334. that have been made. This data will be provided to the ``teardown_databases()``
  335. function at the conclusion of testing.
  336. .. method:: DiscoverRunner.run_suite(suite, **kwargs)
  337. Runs the test suite.
  338. Returns the result produced by the running the test suite.
  339. .. method:: DiscoverRunner.teardown_databases(old_config, **kwargs)
  340. Destroys the test databases, restoring pre-test conditions.
  341. ``old_config`` is a data structure defining the changes in the
  342. database configuration that need to be reversed. It is the return
  343. value of the ``setup_databases()`` method.
  344. .. method:: DiscoverRunner.teardown_test_environment(**kwargs)
  345. Restores the pre-test environment.
  346. .. method:: DiscoverRunner.suite_result(suite, result, **kwargs)
  347. Computes and returns a return code based on a test suite, and the result
  348. from that test suite.
  349. Testing utilities
  350. -----------------
  351. django.test.utils
  352. ~~~~~~~~~~~~~~~~~
  353. .. module:: django.test.utils
  354. :synopsis: Helpers to write custom test runners.
  355. To assist in the creation of your own test runner, Django provides a number of
  356. utility methods in the ``django.test.utils`` module.
  357. .. function:: setup_test_environment()
  358. Performs any global pre-test setup, such as the installing the
  359. instrumentation of the template rendering system and setting up
  360. the dummy email outbox.
  361. .. function:: teardown_test_environment()
  362. Performs any global post-test teardown, such as removing the black
  363. magic hooks into the template system and restoring normal email
  364. services.
  365. django.db.connection.creation
  366. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  367. .. currentmodule:: django.db.connection.creation
  368. The creation module of the database backend also provides some utilities that
  369. can be useful during testing.
  370. .. function:: create_test_db([verbosity=1, autoclobber=False, serialize=True, keepdb=False])
  371. Creates a new test database and runs ``migrate`` against it.
  372. ``verbosity`` has the same behavior as in ``run_tests()``.
  373. ``autoclobber`` describes the behavior that will occur if a
  374. database with the same name as the test database is discovered:
  375. * If ``autoclobber`` is ``False``, the user will be asked to
  376. approve destroying the existing database. ``sys.exit`` is
  377. called if the user does not approve.
  378. * If autoclobber is ``True``, the database will be destroyed
  379. without consulting the user.
  380. ``serialize`` determines if Django serializes the database into an
  381. in-memory JSON string before running tests (used to restore the database
  382. state between tests if you don't have transactions). You can set this to
  383. False to significantly speed up creation time if you know you don't need
  384. data persistence outside of test fixtures.
  385. ``keepdb`` determines if the test run should use an existing
  386. database, or create a new one. If ``True``, the existing
  387. database will be used, or created if not present. If ``False``,
  388. a new database will be created, prompting the user to remove
  389. the existing one, if present.
  390. Returns the name of the test database that it created.
  391. ``create_test_db()`` has the side effect of modifying the value of
  392. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  393. database.
  394. .. versionchanged:: 1.7
  395. The ``serialize`` argument was added.
  396. .. versionchanged:: 1.8
  397. The ``keepdb`` argument was added.
  398. .. function:: destroy_test_db(old_database_name, [verbosity=1, keepdb=False])
  399. Destroys the database whose name is the value of :setting:`NAME` in
  400. :setting:`DATABASES`, and sets :setting:`NAME` to the value of
  401. ``old_database_name``.
  402. The ``verbosity`` argument has the same behavior as for
  403. :class:`~django.test.runner.DiscoverRunner`.
  404. If the ``keepdb`` argument is ``True``, then the connection to the
  405. database will be closed, but the database will not be destroyed.
  406. .. versionchanged:: 1.8
  407. The ``keepdb`` argument was added.
  408. .. _topics-testing-code-coverage:
  409. Integration with coverage.py
  410. ============================
  411. Code coverage describes how much source code has been tested. It shows which
  412. parts of your code are being exercised by tests and which are not. It's an
  413. important part of testing applications, so it's strongly recommended to check
  414. the coverage of your tests.
  415. Django can be easily integrated with `coverage.py`_, a tool for measuring code
  416. coverage of Python programs. First, `install coverage.py`_. Next, run the
  417. following from your project folder containing ``manage.py``::
  418. coverage run --source='.' manage.py test myapp
  419. This runs your tests and collects coverage data of the executed files in your
  420. project. You can see a report of this data by typing following command::
  421. coverage report
  422. Note that some Django code was executed while running tests, but it is not
  423. listed here because of the ``source`` flag passed to the previous command.
  424. For more options like annotated HTML listings detailing missed lines, see the
  425. `coverage.py`_ docs.
  426. .. _coverage.py: http://nedbatchelder.com/code/coverage/
  427. .. _install coverage.py: https://pypi.python.org/pypi/coverage