advanced.txt 20 KB

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