Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 1582 lines (1126 sloc) 63.149 kB
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
1 ===========================
2 Testing Django applications
3 ===========================
4
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
5 .. module:: django.test
6 :synopsis: Testing tools for Django applications.
7
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
8 Automated testing is an extremely useful bug-killing tool for the modern
9 Web developer. You can use a collection of tests -- a **test suite** -- to
45bfe77 Fixed #4366 -- Fixed a small typo. Thanks, Ivan Sagalaev.
mtredinnick authored
10 solve, or avoid, a number of problems:
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
11
12 * When you're writing new code, you can use tests to validate your code
13 works as expected.
14
15 * When you're refactoring or modifying old code, you can use tests to
16 ensure your changes haven't affected your application's behavior
17 unexpectedly.
18
19 Testing a Web application is a complex task, because a Web application is made
20 of several layers of logic -- from HTTP-level request handling, to form
21 validation and processing, to template rendering. With Django's test-execution
22 framework and assorted utilities, you can simulate requests, insert test data,
23 inspect your application's output and generally verify your code is doing what
24 it should be doing.
25
26 The best part is, it's really easy.
27
941725a *Finally* edited docs/testing.txt
adrian authored
28 This document is split into two primary sections. First, we explain how to
29 write tests with Django. Then, we explain how to run them.
30
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
31 Writing tests
32 =============
33
941725a *Finally* edited docs/testing.txt
adrian authored
34 There are two primary ways to write tests with Django, corresponding to the
35 two test frameworks that ship in the Python standard library. The two
36 frameworks are:
37
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
38 * **Doctests** -- tests that are embedded in your functions' docstrings and
39 are written in a way that emulates a session of the Python interactive
40 interpreter. For example::
41
42 def my_func(a_list, idx):
43 """
44 >>> a = ['larry', 'curly', 'moe']
45 >>> my_func(a, 0)
46 'larry'
47 >>> my_func(a, 1)
48 'curly'
941725a *Finally* edited docs/testing.txt
adrian authored
49 """
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
50 return a_list[idx]
941725a *Finally* edited docs/testing.txt
adrian authored
51
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
52 * **Unit tests** -- tests that are expressed as methods on a Python class
53 that subclasses ``unittest.TestCase``. For example::
941725a *Finally* edited docs/testing.txt
adrian authored
54
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
55 import unittest
941725a *Finally* edited docs/testing.txt
adrian authored
56
077f4d5 Fixed #7962 -- Corrected typo in testing docs. Thanks to cgod for the…
russellm authored
57 class MyFuncTestCase(unittest.TestCase):
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
58 def testBasic(self):
59 a = ['larry', 'curly', 'moe']
60 self.assertEquals(my_func(a, 0), 'larry')
61 self.assertEquals(my_func(a, 1), 'curly')
941725a *Finally* edited docs/testing.txt
adrian authored
62
63 You can choose the test framework you like, depending on which syntax you
64 prefer, or you can mix and match, using one framework for some of your code and
65 the other framework for other code. You can also use any *other* Python test
66 frameworks, as we'll explain in a bit.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
67
68 Writing doctests
69 ----------------
70
941725a *Finally* edited docs/testing.txt
adrian authored
71 Doctests use Python's standard doctest_ module, which searches your docstrings
72 for statements that resemble a session of the Python interactive interpreter.
73 A full explanation of how doctest works is out of the scope of this document;
74 read Python's official documentation for the details.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
75
76 .. admonition:: What's a **docstring**?
77
941725a *Finally* edited docs/testing.txt
adrian authored
78 A good explanation of docstrings (and some guidelines for using them
9384aaf Tiny reST fix to testing.txt.
jacob authored
79 effectively) can be found in :pep:`257`:
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
80
81 A docstring is a string literal that occurs as the first statement in
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
82 a module, function, class, or method definition. Such a docstring
83 becomes the ``__doc__`` special attribute of that object.
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
84
941725a *Finally* edited docs/testing.txt
adrian authored
85 For example, this function has a docstring that describes what it does::
86
87 def add_two(num):
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
88 "Return the result of adding two to the provided number."
89 return num + 2
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
90
941725a *Finally* edited docs/testing.txt
adrian authored
91 Because tests often make great documentation, putting tests directly in
92 your docstrings is an effective way to document *and* test your code.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
93
941725a *Finally* edited docs/testing.txt
adrian authored
94 For a given Django application, the test runner looks for doctests in two
95 places:
96
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
97 * The ``models.py`` file. You can define module-level doctests and/or a
98 doctest for individual models. It's common practice to put
99 application-level doctests in the module docstring and model-level
100 doctests in the model docstrings.
941725a *Finally* edited docs/testing.txt
adrian authored
101
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
102 * A file called ``tests.py`` in the application directory -- i.e., the
103 directory that holds ``models.py``. This file is a hook for any and all
104 doctests you want to write that aren't necessarily related to models.
941725a *Finally* edited docs/testing.txt
adrian authored
105
106 Here is an example model doctest::
107
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
108 # models.py
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
109
6b685fd Fixed #4877 -- Fixed typo in testing documentation, patch from John S…
gwilson authored
110 from django.db import models
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
111
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
112 class Animal(models.Model):
113 """
114 An animal that knows how to make noise
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
115
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
116 # Create some animals
117 >>> lion = Animal.objects.create(name="lion", sound="roar")
118 >>> cat = Animal.objects.create(name="cat", sound="meow")
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
119
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
120 # Make 'em speak
121 >>> lion.speak()
122 'The lion says "roar"'
123 >>> cat.speak()
124 'The cat says "meow"'
125 """
e877bab Fixed #2101 -- Renamed `maxlength` argument to `max_length` for oldfo…
gwilson authored
126 name = models.CharField(max_length=20)
127 sound = models.CharField(max_length=20)
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
128
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
129 def speak(self):
130 return 'The %s says "%s"' % (self.name, self.sound)
131
8720ecb A few fixes for the testing documentation:
gwilson authored
132 When you :ref:`run your tests <running-tests>`, the test runner will find this
133 docstring, notice that portions of it look like an interactive Python session,
134 and execute those lines while checking that the results match.
135
136 In the case of model tests, note that the test runner takes care of creating
137 its own test database. That is, any test that accesses a database -- by
138 creating and saving model instances, for example -- will not affect your
4d927c7 A whole lotta documentation fixes: Fixes #8704, #8826, #8980, #9243, …
jacob authored
139 production database. However, the database is not refreshed between doctests,
0a154a3 Fixed #11253 -- Normalized the way the docs refer to TestCase.assert*…
russellm authored
140 so if your doctest requires a certain state you should consider flushing the
141 database or loading a fixture. (See the section on fixtures, below, for more
4d927c7 A whole lotta documentation fixes: Fixes #8704, #8826, #8980, #9243, …
jacob authored
142 on this.) Note that to use this feature, the database user Django is connecting
143 as must have ``CREATE DATABASE`` rights.
941725a *Finally* edited docs/testing.txt
adrian authored
144
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
145 For more details about how doctest works, see the `standard library
8720ecb A few fixes for the testing documentation:
gwilson authored
146 documentation for doctest`_.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
147
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
148 .. _doctest: http://docs.python.org/library/doctest.html
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
149 .. _standard library documentation for doctest: doctest_
150
941725a *Finally* edited docs/testing.txt
adrian authored
151 Writing unit tests
152 ------------------
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
153
154 Like doctests, Django's unit tests use a standard library module: unittest_.
941725a *Finally* edited docs/testing.txt
adrian authored
155 This module uses a different way of defining tests, taking a class-based
156 approach.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
157
941725a *Finally* edited docs/testing.txt
adrian authored
158 As with doctests, for a given Django application, the test runner looks for
159 unit tests in two places:
160
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
161 * The ``models.py`` file. The test runner looks for any subclass of
162 ``unittest.TestCase`` in this module.
941725a *Finally* edited docs/testing.txt
adrian authored
163
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
164 * A file called ``tests.py`` in the application directory -- i.e., the
165 directory that holds ``models.py``. Again, the test runner looks for any
166 subclass of ``unittest.TestCase`` in this module.
941725a *Finally* edited docs/testing.txt
adrian authored
167
168 This example ``unittest.TestCase`` subclass is equivalent to the example given
169 in the doctest section above::
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
170
171 import unittest
172 from myapp.models import Animal
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
173
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
174 class AnimalTestCase(unittest.TestCase):
175 def setUp(self):
176 self.lion = Animal.objects.create(name="lion", sound="roar")
177 self.cat = Animal.objects.create(name="cat", sound="meow")
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
178
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
179 def testSpeaking(self):
180 self.assertEquals(self.lion.speak(), 'The lion says "roar"')
181 self.assertEquals(self.cat.speak(), 'The cat says "meow"')
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
182
8720ecb A few fixes for the testing documentation:
gwilson authored
183 When you :ref:`run your tests <running-tests>`, the default behavior of the
184 test utility is to find all the test cases (that is, subclasses of
185 ``unittest.TestCase``) in ``models.py`` and ``tests.py``, automatically build a
186 test suite out of those test cases, and run that suite.
31b0400 Fixed #3782 -- Added support for the suite() method recommended by th…
russellm authored
187
af9589b Fixed #9477 -- Removed and edited a bunch of references to "development
mtredinnick authored
188 There is a second way to define the test suite for a module: if you define a
189 function called ``suite()`` in either ``models.py`` or ``tests.py``, the
190 Django test runner will use that function to construct the test suite for that
191 module. This follows the `suggested organization`_ for unit tests. See the
192 Python documentation for more details on how to construct a complex test
193 suite.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
194
195 For more details about ``unittest``, see the `standard library unittest
196 documentation`_.
197
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
198 .. _unittest: http://docs.python.org/library/unittest.html
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
199 .. _standard library unittest documentation: unittest_
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
200 .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
201
202 Which should I use?
203 -------------------
204
941725a *Finally* edited docs/testing.txt
adrian authored
205 Because Django supports both of the standard Python test frameworks, it's up to
206 you and your tastes to decide which one to use. You can even decide to use
207 *both*.
208
209 For developers new to testing, however, this choice can seem confusing. Here,
210 then, are a few key differences to help you decide which approach is right for
211 you:
212
4e660b6 Fixed some ReST errors in docs/testing.txt
adrian authored
213 * If you've been using Python for a while, ``doctest`` will probably feel
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
214 more "pythonic". It's designed to make writing tests as easy as possible,
215 so it requires no overhead of writing classes or methods. You simply put
216 tests in docstrings. This has the added advantage of serving as
217 documentation (and correct documentation, at that!).
941725a *Finally* edited docs/testing.txt
adrian authored
218
219 If you're just getting started with testing, using doctests will probably
220 get you started faster.
221
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
222 * The ``unittest`` framework will probably feel very familiar to developers
941725a *Finally* edited docs/testing.txt
adrian authored
223 coming from Java. ``unittest`` is inspired by Java's JUnit, so you'll
224 feel at home with this method if you've used JUnit or any test framework
225 inspired by JUnit.
226
b562ff3 Removed stray tabs mistakenly added to docs/testing.txt in [5889]
adrian authored
227 * If you need to write a bunch of tests that share similar code, then
228 you'll appreciate the ``unittest`` framework's organization around
229 classes and methods. This makes it easy to abstract common tasks into
230 common methods. The framework also supports explicit setup and/or cleanup
231 routines, which give you a high level of control over the environment
232 in which your test cases are run.
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
233
234 Again, remember that you can use both systems side-by-side (even in the same
941725a *Finally* edited docs/testing.txt
adrian authored
235 app). In the end, most projects will eventually end up using both. Each shines
54d1ad0 Added a rough cut of a document on using the new testing framework.
jacob authored
236 in different circumstances.
237
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
238 .. _running-tests:
239
941725a *Finally* edited docs/testing.txt
adrian authored
240 Running tests
241 =============
242
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
243 Once you've written tests, run them using the :djadmin:`test` subcommand of
244 your project's ``manage.py`` utility::
941725a *Finally* edited docs/testing.txt
adrian authored
245
246 $ ./manage.py test
247
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
248 By default, this will run every test in every application in
249 :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
250 application, add the application name to the command line. For example, if your
251 :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
252 ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
253 with this command::
941725a *Finally* edited docs/testing.txt
adrian authored
254
6acf9c8 Fixed #8578: Corrected a typo in a shell example in the testing docs.…
russellm authored
255 $ ./manage.py test animals
941725a *Finally* edited docs/testing.txt
adrian authored
256
257 Note that we used ``animals``, not ``myproject.animals``.
258
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
259 .. versionadded:: 1.0
260 You can now choose which test to run.
261
ba1f5a2 Fixed #6364 -- Added the ability to run individual doctests.
russellm authored
262 You can be even *more* specific by naming an individual test case. To
263 run a single test case in an application (for example, the
264 ``AnimalTestCase`` described in the "Writing unit tests" section), add
265 the name of the test case to the label on the command line::
941725a *Finally* edited docs/testing.txt
adrian authored
266
267 $ ./manage.py test animals.AnimalTestCase
268
ba1f5a2 Fixed #6364 -- Added the ability to run individual doctests.
russellm authored
269 And it gets even more granular than that! To run a *single* test
270 method inside a test case, add the name of the test method to the
271 label::
941725a *Finally* edited docs/testing.txt
adrian authored
272
273 $ ./manage.py test animals.AnimalTestCase.testFluffyAnimals
274
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
275 .. versionadded:: 1.2
ba1f5a2 Fixed #6364 -- Added the ability to run individual doctests.
russellm authored
276 The ability to select individual doctests was added.
277
278 You can use the same rules if you're using doctests. Django will use the
279 test label as a path to the test method or class that you want to run.
280 If your ``models.py`` or ``tests.py`` has a function with a doctest, or
281 class with a class-level doctest, you can invoke that test by appending the
282 name of the test method or class to the label::
283
284 $ ./manage.py test animals.classify
285
286 If you want to run the doctest for a specific method in a class, add the
287 name of the method to the label::
288
289 $ ./manage.py test animals.Classifier.run
290
291 If you're using a ``__test__`` dictionary to specify doctests for a
292 module, Django will use the label as a key in the ``__test__`` dictionary
293 for defined in ``models.py`` and ``tests.py``.
294
295 .. versionadded:: 1.2
2a31f2d Fixed #12624 -- Modified test runners to be class based.
russellm authored
296 You can now trigger a graceful exit from a test run by pressing ``Ctrl-C``.
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
297
2a31f2d Fixed #12624 -- Modified test runners to be class based.
russellm authored
298 If you press ``Ctrl-C`` while the tests are running, the test runner will
c6aae66 Typo fix for doc added in r12034. Thanks Alex Gaynor.
kmtracey authored
299 wait for the currently running test to complete and then exit gracefully.
2a31f2d Fixed #12624 -- Modified test runners to be class based.
russellm authored
300 During a graceful exit the test runner will output details of any test
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
301 failures, report on how many tests were run and how many errors and failures
2a31f2d Fixed #12624 -- Modified test runners to be class based.
russellm authored
302 were encountered, and destroy any test databases as usual. Thus pressing
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
303 ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
2a31f2d Fixed #12624 -- Modified test runners to be class based.
russellm authored
304 option, notice that some tests are unexpectedly failing, and want to get details
1d2aa2d Fixed #12364: Added graceful exit from a test run when Ctrl-C is pres…
kmtracey authored
305 on the failures without waiting for the full test run to complete.
306
307 If you do not want to wait for the currently running test to finish, you
308 can press ``Ctrl-C`` a second time and the test run will halt immediately,
309 but not gracefully. No details of the tests run before the interruption will
310 be reported, and any test databases created by the run will not be destroyed.
311
e4b4d21 Fixed #14274 -- Added admonition about using -Wall when you run tests…
russellm authored
312 .. admonition:: Test with warnings enabled
313
314 It is a good idea to run your tests with ``python -Wall manage.py
315 test``. This will allow you to catch any deprecation warnings that
316 might be in your code. Django (as well as many other libraries) use
317 warnings to flag when features are deprecated. It can also flag
318 areas in your code that are not strictly wrong, but may benefit
319 from a better implementation.
320
3ae8cac Fixed #3051 -- Documented the requirements for standalone testing. Th…
russellm authored
321 Running tests outside the test runner
d21bf5e Fixed #14112 -- Various Markup fixes for the docs. Thanks to ramiro f…
russellm authored
322 -------------------------------------
3ae8cac Fixed #3051 -- Documented the requirements for standalone testing. Th…
russellm authored
323
324 If you want to run tests outside of ``./manage.py test`` -- for example,
325 from a shell prompt -- you will need to set up the test
326 environment first. Django provides a convenience method to do this::
327
328 >>> from django.test.utils import setup_test_environment
329 >>> setup_test_environment()
330
331 This convenience method sets up the test database, and puts other
332 Django features into modes that allow for repeatable testing.
333
334 The call to :meth:`~django.test.utils.setup_test_environment` is made
335 automatically as part of the setup of `./manage.py test`. You only
336 need to manually invoke this method if you're not using running your
337 tests via Django's test runner.
338
e668700 Split up the documentation of the test database and the test output.
mtredinnick authored
339 The test database
340 -----------------
941725a *Finally* edited docs/testing.txt
adrian authored
341
8720ecb A few fixes for the testing documentation:
gwilson authored
342 Tests that require a database (namely, model tests) will not use your "real"
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
343 (production) database. Separate, blank databases are created for the tests.
941725a *Finally* edited docs/testing.txt
adrian authored
344
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
345 Regardless of whether the tests pass or fail, the test databases are destroyed
e668700 Split up the documentation of the test database and the test output.
mtredinnick authored
346 when all the tests have been executed.
941725a *Finally* edited docs/testing.txt
adrian authored
347
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
348 By default the test databases get their names by prepending ``test_``
a871a5c Fixed #12542 -- Added the TEST_MIRROR setting, allowing testing of re…
russellm authored
349 to the value of the :setting:`NAME` settings for the databases
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
350 defined in :setting:`DATABASES`. When using the SQLite database engine
351 the tests will by default use an in-memory database (i.e., the
352 database will be created in memory, bypassing the filesystem
353 entirely!). If you want to use a different database name, specify
a871a5c Fixed #12542 -- Added the TEST_MIRROR setting, allowing testing of re…
russellm authored
354 :setting:`TEST_NAME` in the dictionary for any given database in
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
355 :setting:`DATABASES`.
356
357 Aside from using a separate database, the test runner will otherwise
358 use all of the same database settings you have in your settings file:
359 :setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
360 database is created by the user specified by ``USER``, so you'll need
361 to make sure that the given user account has sufficient privileges to
362 create a new database on the system.
941725a *Finally* edited docs/testing.txt
adrian authored
363
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
364 .. versionadded:: 1.0
365
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
366 For fine-grained control over the character encoding of your test
367 database, use the :setting:`TEST_CHARSET` option. If you're using
368 MySQL, you can also use the :setting:`TEST_COLLATION` option to
369 control the particular collation used by the test database. See the
38f5bcf Fixed #14141: docs now use the :doc: construct for links between docu…
jacob authored
370 :doc:`settings documentation </ref/settings>` for details of these
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
371 advanced settings.
941725a *Finally* edited docs/testing.txt
adrian authored
372
a871a5c Fixed #12542 -- Added the TEST_MIRROR setting, allowing testing of re…
russellm authored
373 .. _topics-testing-masterslave:
374
375 Testing master/slave configurations
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377
378 .. versionadded:: 1.2
379
380 If you're testing a multiple database configuration with master/slave
381 replication, this strategy of creating test databases poses a problem.
382 When the test databases are created, there won't be any replication,
383 and as a result, data created on the master won't be seen on the
384 slave.
385
386 To compensate for this, Django allows you to define that a database is
387 a *test mirror*. Consider the following (simplified) example database
388 configuration::
389
390 DATABASES = {
391 'default': {
392 'ENGINE': 'django.db.backends.mysql',
393 'NAME': 'myproject',
394 'HOST': 'dbmaster',
395 # ... plus some other settings
396 },
397 'slave': {
398 'ENGINE': 'django.db.backends.mysql',
399 'NAME': 'myproject',
400 'HOST': 'dbslave',
401 'TEST_MIRROR': 'default'
402 # ... plus some other settings
403 }
404 }
405
406 In this setup, we have two database servers: ``dbmaster``, described
407 by the database alias ``default``, and ``dbslave`` described by the
408 alias ``slave``. As you might expect, ``dbslave`` has been configured
409 by the database administrator as a read slave of ``dbmaster``, so in
410 normal activity, any write to ``default`` will appear on ``slave``.
411
412 If Django created two independent test databases, this would break any
413 tests that expected replication to occur. However, the ``slave``
414 database has been configured as a test mirror (using the
415 :setting:`TEST_MIRROR` setting), indicating that under testing,
416 ``slave`` should be treated as a mirror of ``default``.
417
418 When the test environment is configured, a test version of ``slave``
419 will *not* be created. Instead the connection to ``slave``
420 will be redirected to point at ``default``. As a result, writes to
421 ``default`` will appear on ``slave`` -- but because they are actually
422 the same database, not because there is data replication between the
423 two databases.
424
dea1a6a Fixed #8401: Added a note on the fact that DEBUG=False is forced duri…
russellm authored
425 Other test conditions
426 ---------------------
427
428 Regardless of the value of the :setting:`DEBUG` setting in your configuration
d21bf5e Fixed #14112 -- Various Markup fixes for the docs. Thanks to ramiro f…
russellm authored
429 file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
dea1a6a Fixed #8401: Added a note on the fact that DEBUG=False is forced duri…
russellm authored
430 the observed output of your code matches what will be seen in a production
431 setting.
432
e668700 Split up the documentation of the test database and the test output.
mtredinnick authored
433 Understanding the test output
434 -----------------------------
435
436 When you run your tests, you'll see a number of messages as the test runner
437 prepares itself. You can control the level of detail of these messages with the
438 ``verbosity`` option on the command line::
439
440 Creating test database...
441 Creating table myapp_animal
442 Creating table myapp_mineral
443 Loading 'initial_data' fixtures...
444 No fixtures found.
445
446 This tells you that the test runner is creating a test database, as described
447 in the previous section.
448
941725a *Finally* edited docs/testing.txt
adrian authored
449 Once the test database has been created, Django will run your tests.
450 If everything goes well, you'll see something like this::
451
452 ----------------------------------------------------------------------
453 Ran 22 tests in 0.221s
454
455 OK
456
457 If there are test failures, however, you'll see full details about which tests
458 failed::
459
460 ======================================================================
461 FAIL: Doctest: ellington.core.throttle.models
462 ----------------------------------------------------------------------
463 Traceback (most recent call last):
464 File "/dev/django/test/doctest.py", line 2153, in runTest
465 raise self.failureException(self.format_failure(new.getvalue()))
466 AssertionError: Failed doctest test for myapp.models
467 File "/dev/myapp/models.py", line 0, in models
468
469 ----------------------------------------------------------------------
470 File "/dev/myapp/models.py", line 14, in myapp.models
471 Failed example:
472 throttle.check("actor A", "action one", limit=2, hours=1)
473 Expected:
474 True
475 Got:
476 False
477
478 ----------------------------------------------------------------------
479 Ran 2 tests in 0.048s
480
481 FAILED (failures=1)
482
483 A full explanation of this error output is beyond the scope of this document,
484 but it's pretty intuitive. You can consult the documentation of Python's
485 ``unittest`` library for details.
486
487 Note that the return code for the test-runner script is the total number of
488 failed and erroneous tests. If all the tests pass, the return code is 0. This
489 feature is useful if you're using the test-runner script in a shell script and
490 need to test for success or failure at that level.
491
492 Testing tools
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
493 =============
494
941725a *Finally* edited docs/testing.txt
adrian authored
495 Django provides a small set of tools that come in handy when writing tests.
496
497 The test client
498 ---------------
499
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
500 .. module:: django.test.client
501 :synopsis: Django's test client.
502
941725a *Finally* edited docs/testing.txt
adrian authored
503 The test client is a Python class that acts as a dummy Web browser, allowing
504 you to test your views and interact with your Django-powered application
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
505 programmatically.
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
506
941725a *Finally* edited docs/testing.txt
adrian authored
507 Some of the things you can do with the test client are:
043f485 Fixed ReST error in docs/testing.txt
adrian authored
508
941725a *Finally* edited docs/testing.txt
adrian authored
509 * Simulate GET and POST requests on a URL and observe the response --
510 everything from low-level HTTP (result headers and status codes) to
511 page content.
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
512
941725a *Finally* edited docs/testing.txt
adrian authored
513 * Test that the correct view is executed for a given URL.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
514
941725a *Finally* edited docs/testing.txt
adrian authored
515 * Test that a given request is rendered by a given Django template, with
516 a template context that contains certain values.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
517
941725a *Finally* edited docs/testing.txt
adrian authored
518 Note that the test client is not intended to be a replacement for Twill_,
519 Selenium_, or other "in-browser" frameworks. Django's test client has
520 a different focus. In short:
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
521
941725a *Finally* edited docs/testing.txt
adrian authored
522 * Use Django's test client to establish that the correct view is being
523 called and that the view is collecting the correct context data.
043f485 Fixed ReST error in docs/testing.txt
adrian authored
524
941725a *Finally* edited docs/testing.txt
adrian authored
525 * Use in-browser frameworks such as Twill and Selenium to test *rendered*
526 HTML and the *behavior* of Web pages, namely JavaScript functionality.
527
528 A comprehensive test suite should use a combination of both test types.
043f485 Fixed ReST error in docs/testing.txt
adrian authored
529
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
530 .. _Twill: http://twill.idyll.org/
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
531 .. _Selenium: http://seleniumhq.org/
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
532
941725a *Finally* edited docs/testing.txt
adrian authored
533 Overview and a quick example
534 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
535
536 To use the test client, instantiate ``django.test.client.Client`` and retrieve
537 Web pages::
538
539 >>> from django.test.client import Client
540 >>> c = Client()
541 >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
542 >>> response.status_code
543 200
544 >>> response = c.get('/customer/details/')
545 >>> response.content
546 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'
547
548 As this example suggests, you can instantiate ``Client`` from within a session
549 of the Python interactive interpreter.
550
551 Note a few important things about how the test client works:
552
553 * The test client does *not* require the Web server to be running. In fact,
554 it will run just fine with no Web server running at all! That's because
555 it avoids the overhead of HTTP and deals directly with the Django
556 framework. This helps make the unit tests run quickly.
557
558 * When retrieving pages, remember to specify the *path* of the URL, not the
559 whole domain. For example, this is correct::
560
561 >>> c.get('/login/')
562
563 This is incorrect::
564
565 >>> c.get('http://www.example.com/login/')
566
567 The test client is not capable of retrieving Web pages that are not
568 powered by your Django project. If you need to retrieve other Web pages,
569 use a Python standard library module such as urllib_ or urllib2_.
570
571 * To resolve URLs, the test client uses whatever URLconf is pointed-to by
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
572 your :setting:`ROOT_URLCONF` setting.
941725a *Finally* edited docs/testing.txt
adrian authored
573
574 * Although the above example would work in the Python interactive
575 interpreter, some of the test client's functionality, notably the
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
576 template-related functionality, is only available *while tests are
577 running*.
941725a *Finally* edited docs/testing.txt
adrian authored
578
579 The reason for this is that Django's test runner performs a bit of black
580 magic in order to determine which template was loaded by a given view.
581 This black magic (essentially a patching of Django's template system in
582 memory) only happens during test running.
583
e631f6f Fixed #14116 -- Added a flag to enable CSRF checks in the test client…
russellm authored
584 * By default, the test client will disable any CSRF checks
585 performed by your site.
586
0c49dae Fixed #14225 -- Added a documentation marker (and a 1.2.2 release not…
russellm authored
587 .. versionadded:: 1.2.2
588
e631f6f Fixed #14116 -- Added a flag to enable CSRF checks in the test client…
russellm authored
589 If, for some reason, you *want* the test client to perform CSRF
590 checks, you can create an instance of the test client that
591 enforces CSRF checks. To do this, pass in the
592 ``enforce_csrf_checks`` argument when you construct your
593 client::
594
595 >>> from django.test import Client
596 >>> csrf_client = Client(enforce_csrf_checks=True)
597
598
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
599 .. _urllib: http://docs.python.org/library/urllib.html
600 .. _urllib2: http://docs.python.org/library/urllib2.html
941725a *Finally* edited docs/testing.txt
adrian authored
601
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
602 Making requests
603 ~~~~~~~~~~~~~~~
604
941725a *Finally* edited docs/testing.txt
adrian authored
605 Use the ``django.test.client.Client`` class to make requests. It requires no
8720ecb A few fixes for the testing documentation:
gwilson authored
606 arguments at time of construction:
941725a *Finally* edited docs/testing.txt
adrian authored
607
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
608 .. class:: Client()
941725a *Finally* edited docs/testing.txt
adrian authored
609
8720ecb A few fixes for the testing documentation:
gwilson authored
610 Once you have a ``Client`` instance, you can call any of the following
611 methods:
612
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
613 .. method:: Client.get(path, data={}, follow=False, **extra)
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
614
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
615
8720ecb A few fixes for the testing documentation:
gwilson authored
616 Makes a GET request on the provided ``path`` and returns a ``Response``
617 object, which is documented below.
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
618
8720ecb A few fixes for the testing documentation:
gwilson authored
619 The key-value pairs in the ``data`` dictionary are used to create a GET
620 data payload. For example::
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
621
8720ecb A few fixes for the testing documentation:
gwilson authored
622 >>> c = Client()
623 >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
624
8720ecb A few fixes for the testing documentation:
gwilson authored
625 ...will result in the evaluation of a GET request equivalent to::
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
626
8720ecb A few fixes for the testing documentation:
gwilson authored
627 /customers/details/?name=fred&age=7
941725a *Finally* edited docs/testing.txt
adrian authored
628
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
629 The ``extra`` keyword arguments parameter can be used to specify
630 headers to be sent in the request. For example::
631
632 >>> c = Client()
633 >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
634 ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
635
636 ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
637 details view, which is a good way to test code paths that use the
638 :meth:`django.http.HttpRequest.is_ajax()` method.
639
2f9e299 Changed a few versionadded doc directives from "development" to "1.1".
mtredinnick authored
640 .. versionadded:: 1.1
daa3117 Fixed #9351 -- Modified the test client to pass on URL encoded parame…
russellm authored
641
642 If you already have the GET arguments in URL-encoded form, you can
643 use that encoding instead of using the data argument. For example,
644 the previous GET request could also be posed as::
645
646 >>> c = Client()
647 >>> c.get('/customers/details/?name=fred&age=7')
648
76fdb9b Fixed #11961: Corrected a few typos in docs/testing.txt. Thanks to ti…
ubernostrum authored
649 If you provide a URL with both an encoded GET data and a data argument,
daa3117 Fixed #9351 -- Modified the test client to pass on URL encoded parame…
russellm authored
650 the data argument will take precedence.
651
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
652 If you set ``follow`` to ``True`` the client will follow any redirects
653 and a ``redirect_chain`` attribute will be set in the response object
654 containing tuples of the intermediate urls and status codes.
655
656 If you had an url ``/redirect_me/`` that redirected to ``/next/``, that
657 redirected to ``/final/``, this is what you'd see::
658
0bb5630 Fixed #10971 -- Corrected code example involving redirect_chain in th…
kmtracey authored
659 >>> response = c.get('/redirect_me/', follow=True)
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
660 >>> response.redirect_chain
661 [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
662
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
663 .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
664
8720ecb A few fixes for the testing documentation:
gwilson authored
665 Makes a POST request on the provided ``path`` and returns a
666 ``Response`` object, which is documented below.
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
667
8720ecb A few fixes for the testing documentation:
gwilson authored
668 The key-value pairs in the ``data`` dictionary are used to submit POST
669 data. For example::
941725a *Finally* edited docs/testing.txt
adrian authored
670
8720ecb A few fixes for the testing documentation:
gwilson authored
671 >>> c = Client()
672 >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
941725a *Finally* edited docs/testing.txt
adrian authored
673
8720ecb A few fixes for the testing documentation:
gwilson authored
674 ...will result in the evaluation of a POST request to this URL::
941725a *Finally* edited docs/testing.txt
adrian authored
675
8720ecb A few fixes for the testing documentation:
gwilson authored
676 /login/
941725a *Finally* edited docs/testing.txt
adrian authored
677
8720ecb A few fixes for the testing documentation:
gwilson authored
678 ...with this POST data::
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
679
8720ecb A few fixes for the testing documentation:
gwilson authored
680 name=fred&passwd=secret
941725a *Finally* edited docs/testing.txt
adrian authored
681
8720ecb A few fixes for the testing documentation:
gwilson authored
682 If you provide ``content_type`` (e.g., ``text/xml`` for an XML
683 payload), the contents of ``data`` will be sent as-is in the POST
684 request, using ``content_type`` in the HTTP ``Content-Type`` header.
941725a *Finally* edited docs/testing.txt
adrian authored
685
8720ecb A few fixes for the testing documentation:
gwilson authored
686 If you don't provide a value for ``content_type``, the values in
687 ``data`` will be transmitted with a content type of
688 ``multipart/form-data``. In this case, the key-value pairs in ``data``
689 will be encoded as a multipart message and used to create the POST data
690 payload.
941725a *Finally* edited docs/testing.txt
adrian authored
691
8720ecb A few fixes for the testing documentation:
gwilson authored
692 To submit multiple values for a given key -- for example, to specify
693 the selections for a ``<select multiple>`` -- provide the values as a
694 list or tuple for the required key. For example, this value of ``data``
695 would submit three selected values for the field named ``choices``::
941725a *Finally* edited docs/testing.txt
adrian authored
696
8720ecb A few fixes for the testing documentation:
gwilson authored
697 {'choices': ('a', 'b', 'd')}
941725a *Finally* edited docs/testing.txt
adrian authored
698
8720ecb A few fixes for the testing documentation:
gwilson authored
699 Submitting files is a special case. To POST a file, you need only
700 provide the file field name as a key, and a file handle to the file you
701 wish to upload as a value. For example::
941725a *Finally* edited docs/testing.txt
adrian authored
702
8720ecb A few fixes for the testing documentation:
gwilson authored
703 >>> c = Client()
704 >>> f = open('wishlist.doc')
705 >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
706 >>> f.close()
941725a *Finally* edited docs/testing.txt
adrian authored
707
8720ecb A few fixes for the testing documentation:
gwilson authored
708 (The name ``attachment`` here is not relevant; use whatever name your
709 file-processing code expects.)
941725a *Finally* edited docs/testing.txt
adrian authored
710
ce7877c Fixed #12412 -- Clarified the documentation around file handling by t…
russellm authored
711 Note that if you wish to use the same file handle for multiple
712 ``post()`` calls then you will need to manually reset the file
713 pointer between posts. The easiest way to do this is to
714 manually close the file after it has been provided to
715 ``post()``, as demonstrated above.
716
717 You should also ensure that the file is opened in a way that
718 allows the data to be read. If your file contains binary data
719 such as an image, this means you will need to open the file in
720 ``rb`` (read binary) mode.
941725a *Finally* edited docs/testing.txt
adrian authored
721
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
722 The ``extra`` argument acts the same as for :meth:`Client.get`.
723
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
724 .. versionchanged:: 1.1
daa3117 Fixed #9351 -- Modified the test client to pass on URL encoded parame…
russellm authored
725
726 If the URL you request with a POST contains encoded parameters, these
727 parameters will be made available in the request.GET data. For example,
728 if you were to make the request::
729
730 >>> c.post('/login/?vistor=true', {'name': 'fred', 'passwd': 'secret'})
731
732 ... the view handling this request could interrogate request.POST
733 to retrieve the username and password, and could interrogate request.GET
734 to determine if the user was a visitor.
735
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
736 If you set ``follow`` to ``True`` the client will follow any redirects
737 and a ``redirect_chain`` attribute will be set in the response object
738 containing tuples of the intermediate urls and status codes.
739
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
740 .. method:: Client.head(path, data={}, follow=False, **extra)
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
741
2f9e299 Changed a few versionadded doc directives from "development" to "1.1".
mtredinnick authored
742 .. versionadded:: 1.1
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
743
744 Makes a HEAD request on the provided ``path`` and returns a ``Response``
745 object. Useful for testing RESTful interfaces. Acts just like
746 :meth:`Client.get` except it does not return a message body.
747
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
748 If you set ``follow`` to ``True`` the client will follow any redirects
749 and a ``redirect_chain`` attribute will be set in the response object
750 containing tuples of the intermediate urls and status codes.
751
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
752 .. method:: Client.options(path, data={}, follow=False, **extra)
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
753
2f9e299 Changed a few versionadded doc directives from "development" to "1.1".
mtredinnick authored
754 .. versionadded:: 1.1
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
755
756 Makes an OPTIONS request on the provided ``path`` and returns a
757 ``Response`` object. Useful for testing RESTful interfaces.
758
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
759 If you set ``follow`` to ``True`` the client will follow any redirects
760 and a ``redirect_chain`` attribute will be set in the response object
761 containing tuples of the intermediate urls and status codes.
762
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
763 The ``extra`` argument acts the same as for :meth:`Client.get`.
764
765 .. method:: Client.put(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
766
2f9e299 Changed a few versionadded doc directives from "development" to "1.1".
mtredinnick authored
767 .. versionadded:: 1.1
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
768
76fdb9b Fixed #11961: Corrected a few typos in docs/testing.txt. Thanks to ti…
ubernostrum authored
769 Makes a PUT request on the provided ``path`` and returns a
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
770 ``Response`` object. Useful for testing RESTful interfaces. Acts just
6458125 Fixed #9499: Corrected self-reference in test client put method doc. …
kmtracey authored
771 like :meth:`Client.post` except with the PUT request method.
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
772
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
773 If you set ``follow`` to ``True`` the client will follow any redirects
774 and a ``redirect_chain`` attribute will be set in the response object
775 containing tuples of the intermediate urls and status codes.
776
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
777 .. method:: Client.delete(path, follow=False, **extra)
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
778
2f9e299 Changed a few versionadded doc directives from "development" to "1.1".
mtredinnick authored
779 .. versionadded:: 1.1
cda4a1c Fixed #5888 -- Added methods to the test client to support HEAD, PUT,…
mtredinnick authored
780
781 Makes an DELETE request on the provided ``path`` and returns a
782 ``Response`` object. Useful for testing RESTful interfaces.
783
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
784 If you set ``follow`` to ``True`` the client will follow any redirects
785 and a ``redirect_chain`` attribute will be set in the response object
786 containing tuples of the intermediate urls and status codes.
787
d7e9ff4 Fixed #9607 -- Added documentation for the ``extra`` argument in test…
russellm authored
788 The ``extra`` argument acts the same as for :meth:`Client.get`.
789
8720ecb A few fixes for the testing documentation:
gwilson authored
790 .. method:: Client.login(**credentials)
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
791
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
792 .. versionadded:: 1.0
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
793
38f5bcf Fixed #14141: docs now use the :doc: construct for links between docu…
jacob authored
794 If your site uses Django's :doc:`authentication system</topics/auth>`
8720ecb A few fixes for the testing documentation:
gwilson authored
795 and you deal with logging in users, you can use the test client's
796 ``login()`` method to simulate the effect of a user logging into the
797 site.
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
798
8720ecb A few fixes for the testing documentation:
gwilson authored
799 After you call this method, the test client will have all the cookies
800 and session data required to pass any login-based tests that may form
801 part of a view.
941725a *Finally* edited docs/testing.txt
adrian authored
802
8720ecb A few fixes for the testing documentation:
gwilson authored
803 The format of the ``credentials`` argument depends on which
804 :ref:`authentication backend <authentication-backends>` you're using
805 (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
806 setting). If you're using the standard authentication backend provided
807 by Django (``ModelBackend``), ``credentials`` should be the user's
808 username and password, provided as keyword arguments::
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
809
8720ecb A few fixes for the testing documentation:
gwilson authored
810 >>> c = Client()
811 >>> c.login(username='fred', password='secret')
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
812
8720ecb A few fixes for the testing documentation:
gwilson authored
813 # Now you can access a view that's only available to logged-in users.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
814
8720ecb A few fixes for the testing documentation:
gwilson authored
815 If you're using a different authentication backend, this method may
816 require different credentials. It requires whichever credentials are
817 required by your backend's ``authenticate()`` method.
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
818
8720ecb A few fixes for the testing documentation:
gwilson authored
819 ``login()`` returns ``True`` if it the credentials were accepted and
820 login was successful.
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
821
8720ecb A few fixes for the testing documentation:
gwilson authored
822 Finally, you'll need to remember to create user accounts before you can
823 use this method. As we explained above, the test runner is executed
824 using a test database, which contains no users by default. As a result,
825 user accounts that are valid on your production site will not work
826 under test conditions. You'll need to create users as part of the test
827 suite -- either manually (using the Django model API) or with a test
b3516c7 Fixed #10908 -- Clarified the procedure for creating test users in th…
russellm authored
828 fixture. Remember that if you want your test user to have a password,
829 you can't set the user's password by setting the password attribute
830 directly -- you must use the
831 :meth:`~django.contrib.auth.models.User.set_password()` function to
832 store a correctly hashed password. Alternatively, you can use the
833 :meth:`~django.contrib.auth.models.UserManager.create_user` helper
834 method to create a new user with a correctly hashed password.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
835
8720ecb A few fixes for the testing documentation:
gwilson authored
836 .. method:: Client.logout()
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
837
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
838 .. versionadded:: 1.0
f38ee5a Fixed #5189 -- Added logout method to test Client. Thanks, Jakub Wisn…
russellm authored
839
38f5bcf Fixed #14141: docs now use the :doc: construct for links between docu…
jacob authored
840 If your site uses Django's :doc:`authentication system</topics/auth>`,
8720ecb A few fixes for the testing documentation:
gwilson authored
841 the ``logout()`` method can be used to simulate the effect of a user
842 logging out of your site.
f38ee5a Fixed #5189 -- Added logout method to test Client. Thanks, Jakub Wisn…
russellm authored
843
8720ecb A few fixes for the testing documentation:
gwilson authored
844 After you call this method, the test client will have all the cookies
845 and session data cleared to defaults. Subsequent requests will appear
846 to come from an AnonymousUser.
f38ee5a Fixed #5189 -- Added logout method to test Client. Thanks, Jakub Wisn…
russellm authored
847
941725a *Finally* edited docs/testing.txt
adrian authored
848 Testing responses
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
849 ~~~~~~~~~~~~~~~~~
850
941725a *Finally* edited docs/testing.txt
adrian authored
851 The ``get()`` and ``post()`` methods both return a ``Response`` object. This
852 ``Response`` object is *not* the same as the ``HttpResponse`` object returned
7b22818 Fixed #4360 -- Corrected where HTTP headers are in the test response.…
mtredinnick authored
853 Django views; the test response object has some additional data useful for
854 test code to verify.
941725a *Finally* edited docs/testing.txt
adrian authored
855
4e660b6 Fixed some ReST errors in docs/testing.txt
adrian authored
856 Specifically, a ``Response`` object has the following attributes:
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
857
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
858 .. class:: Response()
941725a *Finally* edited docs/testing.txt
adrian authored
859
8720ecb A few fixes for the testing documentation:
gwilson authored
860 .. attribute:: client
861
862 The test client that was used to make the request that resulted in the
863 response.
864
865 .. attribute:: content
866
867 The body of the response, as a string. This is the final page content as
868 rendered by the view, or any error message.
941725a *Finally* edited docs/testing.txt
adrian authored
869
8720ecb A few fixes for the testing documentation:
gwilson authored
870 .. attribute:: context
711e266 Fixed #4988 -- In the test client, Added tracking of the client and r…
russellm authored
871
8720ecb A few fixes for the testing documentation:
gwilson authored
872 The template ``Context`` instance that was used to render the template that
873 produced the response content.
711e266 Fixed #4988 -- In the test client, Added tracking of the client and r…
russellm authored
874
8720ecb A few fixes for the testing documentation:
gwilson authored
875 If the rendered page used multiple templates, then ``context`` will be a
876 list of ``Context`` objects, in the order in which they were rendered.
711e266 Fixed #4988 -- In the test client, Added tracking of the client and r…
russellm authored
877
056281d Fixed #10482 -- Unified access to response.context when inspecting re…
russellm authored
878 .. versionadded:: 1.1
879
880 Regardless of the number of templates used during rendering, you can
881 retrieve context values using the ``[]`` operator. For example, the
882 context variable ``name`` could be retrieved using::
883
884 >>> response = client.get('/foo/')
885 >>> response.context['name']
886 'Arthur'
887
8720ecb A few fixes for the testing documentation:
gwilson authored
888 .. attribute:: request
711e266 Fixed #4988 -- In the test client, Added tracking of the client and r…
russellm authored
889
8720ecb A few fixes for the testing documentation:
gwilson authored
890 The request data that stimulated the response.
941725a *Finally* edited docs/testing.txt
adrian authored
891
8720ecb A few fixes for the testing documentation:
gwilson authored
892 .. attribute:: status_code
893
894 The HTTP status of the response, as an integer. See RFC2616_ for a full
895 list of HTTP status codes.
896
897 .. attribute:: template
898
899 The ``Template`` instance that was used to render the final content. Use
900 ``template.name`` to get the template's file name, if the template was
901 loaded from a file. (The name is a string such as ``'admin/index.html'``.)
902
903 If the rendered page used multiple templates -- e.g., using :ref:`template
904 inheritance<template-inheritance>` -- then ``template`` will be a list of
905 ``Template`` instances, in the order in which they were rendered.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
906
3d45af7 Fixed #7583 -- Corrected the testing docs that referred to the defunc…
russellm authored
907 You can also use dictionary syntax on the response object to query the value
908 of any settings in the HTTP headers. For example, you could determine the
909 content type of a response using ``response['Content-Type']``.
910
17f3f5e Refs #2333 - Made minor formatting modifications to test framework do…
russellm authored
911 .. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
912
2c41011 Fixed #3162 -- Added coded to catch and rethrow exceptions that are t…
russellm authored
913 Exceptions
914 ~~~~~~~~~~
915
941725a *Finally* edited docs/testing.txt
adrian authored
916 If you point the test client at a view that raises an exception, that exception
8f70d72 Fixed #11215 -- Replaced erroneous catch with except in testing doc.
kmtracey authored
917 will be visible in the test case. You can then use a standard ``try...except``
941725a *Finally* edited docs/testing.txt
adrian authored
918 block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
2c41011 Fixed #3162 -- Added coded to catch and rethrow exceptions that are t…
russellm authored
919
941725a *Finally* edited docs/testing.txt
adrian authored
920 The only exceptions that are not visible to the test client are ``Http404``,
043f485 Fixed ReST error in docs/testing.txt
adrian authored
921 ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
941725a *Finally* edited docs/testing.txt
adrian authored
922 internally and converts them into the appropriate HTTP response codes. In these
923 cases, you can check ``response.status_code`` in your test.
2c41011 Fixed #3162 -- Added coded to catch and rethrow exceptions that are t…
russellm authored
924
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
925 Persistent state
926 ~~~~~~~~~~~~~~~~
927
941725a *Finally* edited docs/testing.txt
adrian authored
928 The test client is stateful. If a response returns a cookie, then that cookie
929 will be stored in the test client and sent with all subsequent ``get()`` and
930 ``post()`` requests.
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
931
941725a *Finally* edited docs/testing.txt
adrian authored
932 Expiration policies for these cookies are not followed. If you want a cookie
933 to expire, either delete it manually or create a new ``Client`` instance (which
934 will effectively delete all cookies).
935
936 A test client has two attributes that store persistent state information. You
937 can access these properties as part of a test condition.
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
938
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
939 .. attribute:: Client.cookies
0534ca0 Corrected some formatting in the testing docs.
russellm authored
940
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
941 A Python ``SimpleCookie`` object, containing the current values of all the
942 client cookies. See the `Cookie module documentation`_ for more.
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
943
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
944 .. attribute:: Client.session
0534ca0 Corrected some formatting in the testing docs.
russellm authored
945
8720ecb A few fixes for the testing documentation:
gwilson authored
946 A dictionary-like object containing session information. See the
38f5bcf Fixed #14141: docs now use the :doc: construct for links between docu…
jacob authored
947 :doc:`session documentation</topics/http/sessions>` for full details.
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
948
2eca0cd Fixed #13754 - Add a note about a test client session property gotcha
lukeplant authored
949 To modify the session and then save it, it must be stored in a variable
950 first (because a new ``SessionStore`` is created every time this property
951 is accessed)::
952
953 def test_something(self):
954 session = self.client.session
955 session['somekey'] = 'test'
956 session.save()
957
4c50c2b Fixed several broken and redirecting URLs in the documentation (fixes…
gwilson authored
958 .. _Cookie module documentation: http://docs.python.org/library/cookie.html
043f485 Fixed ReST error in docs/testing.txt
adrian authored
959
70e851c Added a ``session`` attribute to the test Client, to make it easier t…
russellm authored
960 Example
961 ~~~~~~~
962
941725a *Finally* edited docs/testing.txt
adrian authored
963 The following is a simple unit test using the test client::
043f485 Fixed ReST error in docs/testing.txt
adrian authored
964
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
965 import unittest
966 from django.test.client import Client
043f485 Fixed ReST error in docs/testing.txt
adrian authored
967
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
968 class SimpleTest(unittest.TestCase):
969 def setUp(self):
941725a *Finally* edited docs/testing.txt
adrian authored
970 # Every test needs a client.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
971 self.client = Client()
941725a *Finally* edited docs/testing.txt
adrian authored
972
043f485 Fixed ReST error in docs/testing.txt
adrian authored
973 def test_details(self):
941725a *Finally* edited docs/testing.txt
adrian authored
974 # Issue a GET request.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
975 response = self.client.get('/customer/details/')
043f485 Fixed ReST error in docs/testing.txt
adrian authored
976
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
977 # Check that the response is 200 OK.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
978 self.failUnlessEqual(response.status_code, 200)
941725a *Finally* edited docs/testing.txt
adrian authored
979
980 # Check that the rendered context contains 5 customers.
3ece3d3 Refs #2333 - Added documentation for the test Client, and removed a s…
russellm authored
981 self.failUnlessEqual(len(response.context['customers']), 5)
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
982
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
983 TestCase
04e2fd5 Refs #2333 - Added more documentation for testing framework, and clar…
russellm authored
984 --------
985
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
986 .. currentmodule:: django.test
987
941725a *Finally* edited docs/testing.txt
adrian authored
988 Normal Python unit test classes extend a base class of ``unittest.TestCase``.
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
989 Django provides an extension of this base class:
990
991 .. class:: TestCase()
992
993 This class provides some additional capabilities that can be useful for testing
994 Web sites.
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
995
941725a *Finally* edited docs/testing.txt
adrian authored
996 Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
997 just change the base class of your test from ``unittest.TestCase`` to
998 ``django.test.TestCase``. All of the standard Python unit test functionality
999 will continue to be available, but it will be augmented with some useful
1000 additions.
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1001
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1002 .. versionadded:: 1.1
1003
1004 .. class:: TransactionTestCase()
1005
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1006 Django ``TestCase`` classes make use of database transaction facilities, if
1007 available, to speed up the process of resetting the database to a known state
1008 at the beginning of each test. A consequence of this, however, is that the
1009 effects of transaction commit and rollback cannot be tested by a Django
1010 ``TestCase`` class. If your test requires testing of such transactional
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1011 behavior, you should use a Django ``TransactionTestCase``.
1012
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1013 ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
1014 in which the database is reset to a known state and the ability for test code
fd2da46 Fixed #10433: Corrected typo in test doc. Thanks Matt Doran.
kmtracey authored
1015 to test the effects of commit and rollback. A ``TransactionTestCase`` resets
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1016 the database before the test runs by truncating all tables and reloading
1017 initial data. A ``TransactionTestCase`` may call commit and rollback and
1018 observe the effects of these calls on the database.
1019
1020 A ``TestCase``, on the other hand, does not truncate tables and reload initial
1021 data at the beginning of a test. Instead, it encloses the test code in a
1022 database transaction that is rolled back at the end of the test. It also
1023 prevents the code under test from issuing any commit or rollback operations
1024 on the database, to ensure that the rollback at the end of the test restores
1025 the database to its initial state. In order to guarantee that all ``TestCase``
1026 code starts with a clean database, the Django test runner runs all ``TestCase``
1027 tests first, before any other tests (e.g. doctests) that may alter the
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1028 database without restoring it to its original state.
1029
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1030 When running on a database that does not support rollback (e.g. MySQL with the
1031 MyISAM storage engine), ``TestCase`` falls back to initializing the database
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1032 by truncating tables and reloading initial data.
1033
1034
1035 .. note::
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1036 The ``TestCase`` use of rollback to un-do the effects of the test code
1037 may reveal previously-undetected errors in test code. For example,
1038 test code that assumes primary keys values will be assigned starting at
1039 one may find that assumption no longer holds true when rollbacks instead
1040 of table truncation are being used to reset the database. Similarly,
1041 the reordering of tests so that all ``TestCase`` classes run first may
1042 reveal unexpected dependencies on test case ordering. In such cases a
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1043 quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
1044 A better long-term fix, that allows the test to take advantage of the
1045 speed benefit of ``TestCase``, is to fix the underlying test problem.
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1046
468f008 Fixed #8138 -- Changed django.test.TestCase to rollback tests (when t…
kmtracey authored
1047
941725a *Finally* edited docs/testing.txt
adrian authored
1048 Default test client
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1049 ~~~~~~~~~~~~~~~~~~~
941725a *Finally* edited docs/testing.txt
adrian authored
1050
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
1051 .. versionadded:: 1.0
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1052
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1053 .. attribute:: TestCase.client
1054
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1055 Every test case in a ``django.test.TestCase`` instance has access to an
941725a *Finally* edited docs/testing.txt
adrian authored
1056 instance of a Django test client. This client can be accessed as
1057 ``self.client``. This client is recreated for each test, so you don't have to
1058 worry about state (such as cookies) carrying over from one test to another.
1059
1060 This means, instead of instantiating a ``Client`` in each test::
1061
1062 import unittest
1063 from django.test.client import Client
1064
1065 class SimpleTest(unittest.TestCase):
1066 def test_details(self):
1067 client = Client()
1068 response = client.get('/customer/details/')
1069 self.failUnlessEqual(response.status_code, 200)
1070
1071 def test_index(self):
1072 client = Client()
1073 response = client.get('/customer/index/')
1074 self.failUnlessEqual(response.status_code, 200)
1075
1076 ...you can just refer to ``self.client``, like so::
1077
1078 from django.test import TestCase
1079
1080 class SimpleTest(TestCase):
1081 def test_details(self):
1082 response = self.client.get('/customer/details/')
1083 self.failUnlessEqual(response.status_code, 200)
1084
1085 def test_index(self):
1086 response = self.client.get('/customer/index/')
1087 self.failUnlessEqual(response.status_code, 200)
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1088
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1089 .. _topics-testing-fixtures:
1090
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1091 Fixture loading
1092 ~~~~~~~~~~~~~~~
1093
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1094 .. attribute:: TestCase.fixtures
1095
941725a *Finally* edited docs/testing.txt
adrian authored
1096 A test case for a database-backed Web site isn't much use if there isn't any
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1097 data in the database. To make it easy to put test data into the database,
941725a *Finally* edited docs/testing.txt
adrian authored
1098 Django's custom ``TestCase`` class provides a way of loading **fixtures**.
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1099
941725a *Finally* edited docs/testing.txt
adrian authored
1100 A fixture is a collection of data that Django knows how to import into a
1101 database. For example, if your site has user accounts, you might set up a
1102 fixture of fake user accounts in order to populate your database during tests.
1103
4783f63 Clarified some markup in the discussion of fixture loading in testcases.
russellm authored
1104 The most straightforward way of creating a fixture is to use the
1105 :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
1106 already have some data in your database. See the :djadmin:`dumpdata
1107 documentation<dumpdata>` for more details.
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1108
1109 .. note::
4783f63 Clarified some markup in the discussion of fixture loading in testcases.
russellm authored
1110 If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
1111 already used a fixture without even knowing it! When you call
1112 :djadmin:`syncdb` in the database for the first time, Django
1113 installs a fixture called ``initial_data``. This gives you a way
1114 of populating a new database with any initial data, such as a
1115 default set of categories.
941725a *Finally* edited docs/testing.txt
adrian authored
1116
4783f63 Clarified some markup in the discussion of fixture loading in testcases.
russellm authored
1117 Fixtures with other names can always be installed manually using
1118 the :djadmin:`manage.py loaddata<loaddata>` command.
941725a *Finally* edited docs/testing.txt
adrian authored
1119
98ec433 Fixed a whole bunch of small docs typos, errors, and ommissions.
jacob authored
1120 Once you've created a fixture and placed it in a ``fixtures`` directory in one
1121 of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
4783f63 Clarified some markup in the discussion of fixture loading in testcases.
russellm authored
1122 specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
98ec433 Fixed a whole bunch of small docs typos, errors, and ommissions.
jacob authored
1123 subclass::
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1124
1125 from django.test import TestCase
1126 from myapp.models import Animal
1127
1128 class AnimalTestCase(TestCase):
1129 fixtures = ['mammals.json', 'birds']
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
1130
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1131 def setUp(self):
941725a *Finally* edited docs/testing.txt
adrian authored
1132 # Test definitions as before.
33bcb7b Fixed #12204 -- Corrected the use of :djadmin: links in the testing d…
russellm authored
1133 call_setup_methods()
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1134
5fb8660 Fixed #4460 -- Added the ability to be more specific in the test case…
russellm authored
1135 def testFluffyAnimals(self):
941725a *Finally* edited docs/testing.txt
adrian authored
1136 # A test that uses the fixtures.
33bcb7b Fixed #12204 -- Corrected the use of :djadmin: links in the testing d…
russellm authored
1137 call_some_test_code()
5fb8660 Fixed #4460 -- Added the ability to be more specific in the test case…
russellm authored
1138
941725a *Finally* edited docs/testing.txt
adrian authored
1139 Here's specifically what will happen:
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1140
941725a *Finally* edited docs/testing.txt
adrian authored
1141 * At the start of each test case, before ``setUp()`` is run, Django will
1142 flush the database, returning the database to the state it was in
33bcb7b Fixed #12204 -- Corrected the use of :djadmin: links in the testing d…
russellm authored
1143 directly after :djadmin:`syncdb` was called.
f38ee5a Fixed #5189 -- Added logout method to test Client. Thanks, Jakub Wisn…
russellm authored
1144
941725a *Finally* edited docs/testing.txt
adrian authored
1145 * Then, all the named fixtures are installed. In this example, Django will
1146 install any JSON fixture named ``mammals``, followed by any fixture named
33bcb7b Fixed #12204 -- Corrected the use of :djadmin: links in the testing d…
russellm authored
1147 ``birds``. See the :djadmin:`loaddata` documentation for more
8720ecb A few fixes for the testing documentation:
gwilson authored
1148 details on defining and installing fixtures.
8ca40bd Fixes #2333 -- Added test fixtures framework.
russellm authored
1149
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
1150 This flush/load procedure is repeated for each test in the test case, so you
8720ecb A few fixes for the testing documentation:
gwilson authored
1151 can be certain that the outcome of a test will not be affected by another test,
1152 or by the order of test execution.
941725a *Finally* edited docs/testing.txt
adrian authored
1153
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1154 URLconf configuration
1155 ~~~~~~~~~~~~~~~~~~~~~
1156
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
1157 .. versionadded:: 1.0
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1158
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1159 .. attribute:: TestCase.urls
1160
8720ecb A few fixes for the testing documentation:
gwilson authored
1161 If your application provides views, you may want to include tests that use the
1162 test client to exercise those views. However, an end user is free to deploy the
1163 views in your application at any URL of their choosing. This means that your
1164 tests can't rely upon the fact that your views will be available at a
1165 particular URL.
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1166
1167 In order to provide a reliable URL space for your test,
1168 ``django.test.TestCase`` provides the ability to customize the URLconf
8720ecb A few fixes for the testing documentation:
gwilson authored
1169 configuration for the duration of the execution of a test suite. If your
1170 ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
1171 the value of that attribute as the ``ROOT_URLCONF`` for the duration of that
1172 test.
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1173
1174 For example::
1175
1176 from django.test import TestCase
8720ecb A few fixes for the testing documentation:
gwilson authored
1177
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1178 class TestMyViews(TestCase):
1179 urls = 'myapp.test_urls'
1180
1181 def testIndexPageView(self):
1182 # Here you'd test your view using ``Client``.
33bcb7b Fixed #12204 -- Corrected the use of :djadmin: links in the testing d…
russellm authored
1183 call_some_test_code()
f11773c Fixed #7521 -- Added the ability to customize ROOT_URLCONF for the du…
russellm authored
1184
1185 This test case will use the contents of ``myapp.test_urls`` as the
1186 URLconf for the duration of the test case.
1187
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1188 .. _emptying-test-outbox:
1189
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
1190 Multi-database support
1191 ~~~~~~~~~~~~~~~~~~~~~~
1192
1193 .. attribute:: TestCase.multi_db
1194
1195 .. versionadded:: 1.2
1196
1197 Django sets up a test database corresponding to every database that is
e6e276e Fixed #13377 -- Corrected markup typo in testing docs. Thanks to DrMe…
russellm authored
1198 defined in the :setting:`DATABASES` definition in your settings
836d297 Fixed #1142 -- Added multiple database support.
russellm authored
1199 file. However, a big part of the time taken to run a Django TestCase
1200 is consumed by the call to ``flush`` that ensures that you have a
1201 clean database at the start of each test run. If you have multiple
1202 databases, multiple flushes are required (one for each database),
1203 which can be a time consuming activity -- especially if your tests
1204 don't need to test multi-database activity.
1205
1206 As an optimization, Django only flushes the ``default`` database at
1207 the start of each test run. If your setup contains multiple databases,
1208 and you have a test that requires every database to be clean, you can
1209 use the ``multi_db`` attribute on the test suite to request a full
1210 flush.
1211
1212 For example::
1213
1214 class TestMyViews(TestCase):
1215 multi_db = True
1216
1217 def testIndexPageView(self):
1218 call_some_test_code()
1219
1220 This test case will flush *all* the test databases before running
1221 ``testIndexPageView``.
1222
d2e301e Added redirection for email services during test conditions.
russellm authored
1223 Emptying the test outbox
1224 ~~~~~~~~~~~~~~~~~~~~~~~~
941725a *Finally* edited docs/testing.txt
adrian authored
1225
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
1226 .. versionadded:: 1.0
d2e301e Added redirection for email services during test conditions.
russellm authored
1227
941725a *Finally* edited docs/testing.txt
adrian authored
1228 If you use Django's custom ``TestCase`` class, the test runner will clear the
1229 contents of the test e-mail outbox at the start of each test case.
d2e301e Added redirection for email services during test conditions.
russellm authored
1230
b296567 Changed 'email' to 'e-mail' in docs/testing.txt, to fit our consisten…
adrian authored
1231 For more detail on e-mail services during tests, see `E-mail services`_.
d2e301e Added redirection for email services during test conditions.
russellm authored
1232
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1233 Assertions
1234 ~~~~~~~~~~
941725a *Finally* edited docs/testing.txt
adrian authored
1235
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
1236 .. versionadded:: 1.0
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1237
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1238 .. versionchanged:: 1.2
1239 Addded ``msg_prefix`` argument.
1240
8720ecb A few fixes for the testing documentation:
gwilson authored
1241 As Python's normal ``unittest.TestCase`` class implements assertion methods
1242 such as ``assertTrue`` and ``assertEquals``, Django's custom ``TestCase`` class
1243 provides a number of custom assertion methods that are useful for testing Web
1244 applications:
75bd5f0 Added a default test Client to TestCase, and added some assertions fo…
russellm authored
1245
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1246 The failure messages given by the assertion methods can be customized
1247 with the ``msg_prefix`` argument. This string will be prefixed to any
1248 failure message generated by the assertion. This allows you to provide
1249 additional details that may help you to identify the location and
1250 cause of an failure in your test suite.
1251
1252 .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1253
941725a *Finally* edited docs/testing.txt
adrian authored
1254 Asserts that a ``Response`` instance produced the given ``status_code`` and
1255 that ``text`` appears in the content of the response. If ``count`` is
1256 provided, ``text`` must occur exactly ``count`` times in the response.
676599c Finally began proofreading docs/testing.txt. Did the intro for now; m…
adrian authored
1257
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1258 .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1259
caadd85 Fixed #7165 -- Added an assertNotContains() method to the test client…
russellm authored
1260 Asserts that a ``Response`` instance produced the given ``status_code`` and
1261 that ``text`` does not appears in the content of the response.
1262
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1263 .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1264
941725a *Finally* edited docs/testing.txt
adrian authored
1265 Asserts that a field on a form raises the provided list of errors when
5ae694f Removed a bunch of trailing whitespace. Don't people realise whitespa…
mtredinnick authored
1266 rendered on the form.
1267
941725a *Finally* edited docs/testing.txt
adrian authored
1268 ``form`` is the name the ``Form`` instance was given in the template
0824cff Removed oldforms, validators, and related code:
gwilson authored
1269 context.
5ae694f Removed a bunch of trailing whitespace. Don't people realise whitespa…
mtredinnick authored
1270
1271 ``field`` is the name of the field on the form to check. If ``field``
941725a *Finally* edited docs/testing.txt
adrian authored
1272 has a value of ``None``, non-field errors (errors you can access via
1273 ``form.non_field_errors()``) will be checked.
5ae694f Removed a bunch of trailing whitespace. Don't people realise whitespa…
mtredinnick authored
1274
1275 ``errors`` is an error string, or a list of error strings, that are
1276 expected as a result of form validation.
1277
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1278 .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1279
caadd85 Fixed #7165 -- Added an assertNotContains() method to the test client…
russellm authored
1280 Asserts that the template with the given name was used in rendering the
1281 response.
1282
1283 The name is a string such as ``'admin/index.html'``.
1284
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1285 .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1286
941725a *Finally* edited docs/testing.txt
adrian authored
1287 Asserts that the template with the given name was *not* used in rendering
63f8bda Added assertFormError, assertTemplateUsed and assertTemplateNotUsed f…
russellm authored
1288 the response.
5ae694f Removed a bunch of trailing whitespace. Don't people realise whitespa…
mtredinnick authored
1289
ace8710 Fixed #10314 -- Added a message prefix argument to Django's test asse…
russellm authored
1290 .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
0534ca0 Corrected some formatting in the testing docs.
russellm authored
1291
8720ecb A few fixes for the testing documentation:
gwilson authored
1292 Asserts that the response return a ``status_code`` redirect status, it
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1293 redirected to ``expected_url`` (including any GET data), and the final
8492c68 Fixed #4968 -- Added assertRedirects handling for paths with GET data…
russellm authored
1294 page was received with ``target_status_code``.
63f8bda Added assertFormError, assertTemplateUsed and assertTemplateNotUsed f…
russellm authored
1295
fd84b2f Fixed #4476 -- Added a ``follow`` option to the test client request m…
russellm authored
1296 .. versionadded:: 1.1
1297
1298 If your request used the ``follow`` argument, the ``expected_url`` and
1299 ``target_status_code`` will be the url and status code for the final
1300 point of the redirect chain.
1301
72c4560 Fixed #14168 -- Removed stray argument from docs for assertQuerysetEq…
russellm authored
1302 .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr)
ae4b55b Fixed #13634 -- Migrated aggregation tests to use unittest. This remo…
russellm authored
1303
68a47d8 Fixed #14147 -- Added documentation metadata for new assertQuerysetEq…
russellm authored
1304 .. versionadded:: 1.3
1305
ae4b55b Fixed #13634 -- Migrated aggregation tests to use unittest. This remo…
russellm authored
1306 Asserts that a queryset ``qs`` returns a particular list of values ``values``.
1307
1308 The comparison of the contents of ``qs`` and ``values`` is performed using
1309 the function ``transform``; by default, this means that the ``repr()`` of
1310 each value is compared. Any other callable can be used if ``repr()`` doesn't
1311 provide a unique or helpful comparison.
1312
1313 The comparison is also ordering dependent. If ``qs`` doesn't provide an
1314 implicit ordering, you will need to apply a ``order_by()`` clause to your
1315 queryset to ensure that the test will pass reliably.
1316
535094d Fixed #10355 -- Added an API for pluggable e-mail backends.
russellm authored
1317 .. _topics-testing-email:
1318
b296567 Changed 'email' to 'e-mail' in docs/testing.txt, to fit our consisten…
adrian authored
1319 E-mail services
06f663c Fixed #4285 -- Fixed ReST error in docs/testing.txt. Thanks, Michał K…
adrian authored
1320 ---------------
b296567 Changed 'email' to 'e-mail' in docs/testing.txt, to fit our consisten…
adrian authored
1321
15e55da Fixed #8753: converted "new in ..." callouts to proper Sphinx "versio…
jacob authored
1322 .. versionadded:: 1.0
d2e301e Added redirection for email services during test conditions.
russellm authored
1323
38f5bcf Fixed #14141: docs now use the :doc: construct for links between docu…
jacob authored
1324 If any of your Django views send e-mail using :doc:`Django's e-mail
1325 functionality </topics/email>`, you probably don't want to send e-mail each time
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1326 you run a test using that view. For this reason, Django's test runner
1327 automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
1328 test every aspect of sending e-mail -- from the number of messages sent to the
1329 contents of each message -- without actually sending the messages.
941725a *Finally* edited docs/testing.txt
adrian authored
1330
1331 The test runner accomplishes this by transparently replacing the normal
535094d Fixed #10355 -- Added an API for pluggable e-mail backends.
russellm authored
1332 email backend with a testing backend.
8720ecb A few fixes for the testing documentation:
gwilson authored
1333 (Don't worry -- this has no effect on any other e-mail senders outside of
1334 Django, such as your machine's mail server, if you're running one.)
2c7ad41 Massive reorganization of the docs. See the new docs online at http:/…
jacob authored
1335
1336 .. currentmodule:: django.core.mail
1337
5f6f9a1 Fixed a typo and clarified how django.core.mail.outbox works in the t…
mtredinnick authored
1338 .. data:: django.core.mail.outbox
941725a *Finally* edited docs/testing.txt
adrian authored
1339
f38ee5a Fixed #5189 -- Added logout method to test Client. Thanks, Jakub Wisn…
russellm authored
1340 During test running, each outgoing e-mail is saved in
8720ecb A few fixes for the testing documentation:
gwilson authored
1341 ``django.core.mail.outbox``. This is a simple list of all
76fdb9b Fixed #11961: Corrected a few typos in docs/testing.txt. Thanks to ti…
ubernostrum authored
1342 :class:`~django.core.mail.EmailMessage` instances that have been sent.
5f6f9a1 Fixed a typo and clarified how django.core.mail.outbox works in the t…
mtredinnick authored
1343 The ``outbox`` attribute is a special attribute that is created *only* when
535094d Fixed #10355 -- Added an API for pluggable e-mail backends.
russellm authored
1344 the ``locmem`` e-mail backend is used. It doesn't normally exist as part of the
5f6f9a1 Fixed a typo and clarified how django.core.mail.outbox works in the t…
mtredinnick authored
1345 :mod:`django.core.mail` module and you can't import it directly. The code
1346 below shows how to access this attribute correctly.
1347
941725a *Finally* edited docs/testing.txt
adrian authored
1348 Here's an example test that examines ``django.core.mail.outbox`` for length
1349 and contents::
d2e301e Added redirection for email services during test conditions.
russellm authored
1350
1351 from django.core import mail
941725a *Finally* edited docs/testing.txt
adrian authored
1352 from django.test import TestCase
d2e301e Added redirection for email services during test conditions.
russellm authored
1353
941725a *Finally* edited docs/testing.txt
adrian authored
1354 class EmailTest(TestCase):
1355 def test_send_email(self):
1356 # Send message.
1357 mail.send_mail('Subject here', 'Here is the message.',
1358 'from@example.com', ['to@example.com'],
1359 fail_silently=False)
d2e301e Added redirection for email services during test conditions.
russellm authored
1360
941725a *Finally* edited docs/testing.txt
adrian authored
1361 # Test that one message has been sent.
83987fd