advanced.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 always create the ``default`` database first.
  90. However, no guarantees are made on the creation order of any other
  91. databases in your test setup.
  92. If your database configuration requires a specific creation order, you
  93. can specify the dependencies that exist using the
  94. :setting:`TEST_DEPENDENCIES` setting. Consider the following
  95. (simplified) example database configuration::
  96. DATABASES = {
  97. 'default': {
  98. # ... db settings
  99. 'TEST_DEPENDENCIES': ['diamonds']
  100. },
  101. 'diamonds': {
  102. # ... db settings
  103. },
  104. 'clubs': {
  105. # ... db settings
  106. 'TEST_DEPENDENCIES': ['diamonds']
  107. },
  108. 'spades': {
  109. # ... db settings
  110. 'TEST_DEPENDENCIES': ['diamonds','hearts']
  111. },
  112. 'hearts': {
  113. # ... db settings
  114. 'TEST_DEPENDENCIES': ['diamonds','clubs']
  115. }
  116. }
  117. Under this configuration, the ``diamonds`` database will be created first,
  118. as it is the only database alias without dependencies. The ``default`` and
  119. ``clubs`` alias will be created next (although the order of creation of this
  120. pair is not guaranteed); then ``hearts``; and finally ``spades``.
  121. If there are any circular dependencies in the
  122. :setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
  123. exception will be raised.
  124. Running tests outside the test runner
  125. =====================================
  126. If you want to run tests outside of ``./manage.py test`` -- for example,
  127. from a shell prompt -- you will need to set up the test
  128. environment first. Django provides a convenience method to do this::
  129. >>> from django.test.utils import setup_test_environment
  130. >>> setup_test_environment()
  131. :func:`~django.test.utils.setup_test_environment` puts several Django features
  132. into modes that allow for repeatable testing, but does not create the test
  133. databases; :func:`django.test.simple.DjangoTestSuiteRunner.setup_databases`
  134. takes care of that.
  135. The call to :func:`~django.test.utils.setup_test_environment` is made
  136. automatically as part of the setup of ``./manage.py test``. You only
  137. need to manually invoke this method if you're not using running your
  138. tests via Django's test runner.
  139. .. _other-testing-frameworks:
  140. Using different testing frameworks
  141. ==================================
  142. Clearly, :mod:`doctest` and :mod:`unittest` are not the only Python testing
  143. frameworks. While Django doesn't provide explicit support for alternative
  144. frameworks, it does provide a way to invoke tests constructed for an
  145. alternative framework as if they were normal Django tests.
  146. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  147. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  148. ``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
  149. testing behavior. This behavior involves:
  150. #. Performing global pre-test setup.
  151. #. Looking for unit tests and doctests in the ``models.py`` and
  152. ``tests.py`` files in each installed application.
  153. #. Creating the test databases.
  154. #. Running ``syncdb`` to install models and initial data into the test
  155. databases.
  156. #. Running the unit tests and doctests that are found.
  157. #. Destroying the test databases.
  158. #. Performing global post-test teardown.
  159. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  160. that class, Django will execute your test runner whenever you run
  161. ``./manage.py test``. In this way, it is possible to use any test framework
  162. that can be executed from Python code, or to modify the Django test execution
  163. process to satisfy whatever testing requirements you may have.
  164. .. _topics-testing-test_runner:
  165. Defining a test runner
  166. ----------------------
  167. .. currentmodule:: django.test.simple
  168. A test runner is a class defining a ``run_tests()`` method. Django ships
  169. with a ``DjangoTestSuiteRunner`` class that defines the default Django
  170. testing behavior. This class defines the ``run_tests()`` entry point,
  171. plus a selection of other methods that are used to by ``run_tests()`` to
  172. set up, execute and tear down the test suite.
  173. .. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
  174. ``verbosity`` determines the amount of notification and debug information
  175. that will be printed to the console; ``0`` is no output, ``1`` is normal
  176. output, and ``2`` is verbose output.
  177. If ``interactive`` is ``True``, the test suite has permission to ask the
  178. user for instructions when the test suite is executed. An example of this
  179. behavior would be asking for permission to delete an existing test
  180. database. If ``interactive`` is ``False``, the test suite must be able to
  181. run without any manual intervention.
  182. If ``failfast`` is ``True``, the test suite will stop running after the
  183. first test failure is detected.
  184. Django will, from time to time, extend the capabilities of
  185. the test runner by adding new arguments. The ``**kwargs`` declaration
  186. allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
  187. write your own test runner, ensure accept and handle the ``**kwargs``
  188. parameter.
  189. Your test runner may also define additional command-line options.
  190. If you add an ``option_list`` attribute to a subclassed test runner,
  191. those options will be added to the list of command-line options that
  192. the :djadmin:`test` command can use.
  193. Attributes
  194. ~~~~~~~~~~
  195. .. attribute:: DjangoTestSuiteRunner.option_list
  196. This is the tuple of ``optparse`` options which will be fed into the
  197. management command's ``OptionParser`` for parsing arguments. See the
  198. documentation for Python's ``optparse`` module for more details.
  199. Methods
  200. ~~~~~~~
  201. .. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  202. Run the test suite.
  203. ``test_labels`` is a list of strings describing the tests to be run. A test
  204. label can take one of three forms:
  205. * ``app.TestCase.test_method`` -- Run a single test method in a test
  206. case.
  207. * ``app.TestCase`` -- Run all the test methods in a test case.
  208. * ``app`` -- Search for and run all tests in the named application.
  209. If ``test_labels`` has a value of ``None``, the test runner should run
  210. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  211. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  212. suite that is executed by the test runner. These extra tests are run
  213. in addition to those discovered in the modules listed in ``test_labels``.
  214. This method should return the number of tests that failed.
  215. .. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
  216. Sets up the test environment by calling
  217. :func:`~django.test.utils.setup_test_environment` and setting
  218. :setting:`DEBUG` to ``False``.
  219. .. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  220. Constructs a test suite that matches the test labels provided.
  221. ``test_labels`` is a list of strings describing the tests to be run. A test
  222. label can take one of three forms:
  223. * ``app.TestCase.test_method`` -- Run a single test method in a test
  224. case.
  225. * ``app.TestCase`` -- Run all the test methods in a test case.
  226. * ``app`` -- Search for and run all tests in the named application.
  227. If ``test_labels`` has a value of ``None``, the test runner should run
  228. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  229. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  230. suite that is executed by the test runner. These extra tests are run
  231. in addition to those discovered in the modules listed in ``test_labels``.
  232. Returns a ``TestSuite`` instance ready to be run.
  233. .. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
  234. Creates the test databases.
  235. Returns a data structure that provides enough detail to undo the changes
  236. that have been made. This data will be provided to the ``teardown_databases()``
  237. function at the conclusion of testing.
  238. .. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
  239. Runs the test suite.
  240. Returns the result produced by the running the test suite.
  241. .. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
  242. Destroys the test databases, restoring pre-test conditions.
  243. ``old_config`` is a data structure defining the changes in the
  244. database configuration that need to be reversed. It is the return
  245. value of the ``setup_databases()`` method.
  246. .. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
  247. Restores the pre-test environment.
  248. .. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
  249. Computes and returns a return code based on a test suite, and the result
  250. from that test suite.
  251. Testing utilities
  252. -----------------
  253. django.test.utils
  254. ~~~~~~~~~~~~~~~~~
  255. .. module:: django.test.utils
  256. :synopsis: Helpers to write custom test runners.
  257. To assist in the creation of your own test runner, Django provides a number of
  258. utility methods in the ``django.test.utils`` module.
  259. .. function:: setup_test_environment()
  260. Performs any global pre-test setup, such as the installing the
  261. instrumentation of the template rendering system and setting up
  262. the dummy email outbox.
  263. .. function:: teardown_test_environment()
  264. Performs any global post-test teardown, such as removing the black
  265. magic hooks into the template system and restoring normal email
  266. services.
  267. django.db.connection.creation
  268. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  269. .. currentmodule:: django.db.connection.creation
  270. The creation module of the database backend also provides some utilities that
  271. can be useful during testing.
  272. .. function:: create_test_db([verbosity=1, autoclobber=False])
  273. Creates a new test database and runs ``syncdb`` against it.
  274. ``verbosity`` has the same behavior as in ``run_tests()``.
  275. ``autoclobber`` describes the behavior that will occur if a
  276. database with the same name as the test database is discovered:
  277. * If ``autoclobber`` is ``False``, the user will be asked to
  278. approve destroying the existing database. ``sys.exit`` is
  279. called if the user does not approve.
  280. * If autoclobber is ``True``, the database will be destroyed
  281. without consulting the user.
  282. Returns the name of the test database that it created.
  283. ``create_test_db()`` has the side effect of modifying the value of
  284. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  285. database.
  286. .. function:: destroy_test_db(old_database_name, [verbosity=1])
  287. Destroys the database whose name is the value of :setting:`NAME` in
  288. :setting:`DATABASES`, and sets :setting:`NAME` to the value of
  289. ``old_database_name``.
  290. The ``verbosity`` argument has the same behavior as for
  291. :class:`~django.test.simple.DjangoTestSuiteRunner`.
  292. .. _topics-testing-code-coverage:
  293. Integration with coverage.py
  294. ============================
  295. Code coverage describes how much source code has been tested. It shows which
  296. parts of your code are being exercised by tests and which are not. It's an
  297. important part of testing applications, so it's strongly recommended to check
  298. the coverage of your tests.
  299. Django can be easily integrated with `coverage.py`_, a tool for measuring code
  300. coverage of Python programs. First, `install coverage.py`_. Next, run the
  301. following from your project folder containing ``manage.py``::
  302. coverage run --source='.' manage.py test myapp
  303. This runs your tests and collects coverage data of the executed files in your
  304. project. You can see a report of this data by typing following command::
  305. coverage report
  306. Note that some Django code was executed while running tests, but it is not
  307. listed here because of the ``source`` flag passed to the previous command.
  308. For more options like annotated HTML listings detailing missed lines, see the
  309. `coverage.py`_ docs.
  310. .. _coverage.py: http://nedbatchelder.com/code/coverage/
  311. .. _install coverage.py: http://pypi.python.org/pypi/coverage