| 1 |
===================================== |
| 2 |
Writing your first Django app, part 5 |
| 3 |
===================================== |
| 4 |
|
| 5 |
This tutorial begins where :doc:`Tutorial 4 </intro/tutorial04>` left off. |
| 6 |
We've built a web-poll application, and we'll now create some automated tests |
| 7 |
for it. |
| 8 |
|
| 9 |
.. admonition:: Where to get help: |
| 10 |
|
| 11 |
If you're having trouble going through this tutorial, please head over to |
| 12 |
the :doc:`Getting Help</faq/help>` section of the FAQ. |
| 13 |
|
| 14 |
Introducing automated testing |
| 15 |
============================= |
| 16 |
|
| 17 |
What are automated tests? |
| 18 |
------------------------- |
| 19 |
|
| 20 |
Tests are routines that check the operation of your code. |
| 21 |
|
| 22 |
Testing operates at different levels. Some tests might apply to a tiny detail |
| 23 |
(*does a particular model method return values as expected?*) while others |
| 24 |
examine the overall operation of the software (*does a sequence of user inputs |
| 25 |
on the site produce the desired result?*). That's no different from the kind of |
| 26 |
testing you did earlier in :doc:`Tutorial 2 </intro/tutorial02>`, using the |
| 27 |
:djadmin:`shell` to examine the behavior of a method, or running the |
| 28 |
application and entering data to check how it behaves. |
| 29 |
|
| 30 |
What's different in *automated* tests is that the testing work is done for |
| 31 |
you by the system. You create a set of tests once, and then as you make changes |
| 32 |
to your app, you can check that your code still works as you originally |
| 33 |
intended, without having to perform time consuming manual testing. |
| 34 |
|
| 35 |
Why you need to create tests |
| 36 |
---------------------------- |
| 37 |
|
| 38 |
So why create tests, and why now? |
| 39 |
|
| 40 |
You may feel that you have quite enough on your plate just learning |
| 41 |
Python/Django, and having yet another thing to learn and do may seem |
| 42 |
overwhelming and perhaps unnecessary. After all, our polls application is |
| 43 |
working quite happily now; going through the trouble of creating automated |
| 44 |
tests is not going to make it work any better. If creating the polls |
| 45 |
application is the last bit of Django programming you will ever do, then true, |
| 46 |
you don't need to know how to create automated tests. But, if that's not the |
| 47 |
case, now is an excellent time to learn. |
| 48 |
|
| 49 |
Tests will save you time |
| 50 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 51 |
|
| 52 |
Up to a certain point, 'checking that it seems to work' will be a satisfactory |
| 53 |
test. In a more sophisticated application, you might have dozens of complex |
| 54 |
interactions between components. |
| 55 |
|
| 56 |
A change in any of those components could have unexpected consequences on the |
| 57 |
application's behavior. Checking that it still 'seems to work' could mean |
| 58 |
running through your code's functionality with twenty different variations of |
| 59 |
your test data to make sure you haven't broken something - not a good use |
| 60 |
of your time. |
| 61 |
|
| 62 |
That's especially true when automated tests could do this for you in seconds. |
| 63 |
If something's gone wrong, tests will also assist in identifying the code |
| 64 |
that's causing the unexpected behavior. |
| 65 |
|
| 66 |
Sometimes it may seem a chore to tear yourself away from your productive, |
| 67 |
creative programming work to face the unglamorous and unexciting business |
| 68 |
of writing tests, particularly when you know your code is working properly. |
| 69 |
|
| 70 |
However, the task of writing tests is a lot more fulfilling than spending hours |
| 71 |
testing your application manually or trying to identify the cause of a |
| 72 |
newly-introduced problem. |
| 73 |
|
| 74 |
Tests don't just identify problems, they prevent them |
| 75 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 76 |
|
| 77 |
It's a mistake to think of tests merely as a negative aspect of development. |
| 78 |
|
| 79 |
Without tests, the purpose or intended behavior of an application might be |
| 80 |
rather opaque. Even when it's your own code, you will sometimes find yourself |
| 81 |
poking around in it trying to find out what exactly it's doing. |
| 82 |
|
| 83 |
Tests change that; they light up your code from the inside, and when something |
| 84 |
goes wrong, they focus light on the part that has gone wrong - *even if you |
| 85 |
hadn't even realized it had gone wrong*. |
| 86 |
|
| 87 |
Tests make your code more attractive |
| 88 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 89 |
|
| 90 |
You might have created a brilliant piece of software, but you will find that |
| 91 |
many other developers will refuse to look at it because it lacks tests; without |
| 92 |
tests, they won't trust it. Jacob Kaplan-Moss, one of Django's original |
| 93 |
developers, says "Code without tests is broken by design." |
| 94 |
|
| 95 |
That other developers want to see tests in your software before they take it |
| 96 |
seriously is yet another reason for you to start writing tests. |
| 97 |
|
| 98 |
Tests help teams work together |
| 99 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 100 |
|
| 101 |
The previous points are written from the point of view of a single developer |
| 102 |
maintaining an application. Complex applications will be maintained by teams. |
| 103 |
Tests guarantee that colleagues don't inadvertently break your code (and that |
| 104 |
you don't break theirs without knowing). If you want to make a living as a |
| 105 |
Django programmer, you must be good at writing tests! |
| 106 |
|
| 107 |
Basic testing strategies |
| 108 |
======================== |
| 109 |
|
| 110 |
There are many ways to approach writing tests. |
| 111 |
|
| 112 |
Some programmers follow a discipline called "`test-driven development`_"; they |
| 113 |
actually write their tests before they write their code. This might seem |
| 114 |
counterintuitive, but in fact it's similar to what most people will often do |
| 115 |
anyway: they describe a problem, then create some code to solve it. Test-driven |
| 116 |
development formalizes the problem in a Python test case. |
| 117 |
|
| 118 |
More often, a newcomer to testing will create some code and later decide that |
| 119 |
it should have some tests. Perhaps it would have been better to write some |
| 120 |
tests earlier, but it's never too late to get started. |
| 121 |
|
| 122 |
Sometimes it's difficult to figure out where to get started with writing tests. |
| 123 |
If you have written several thousand lines of Python, choosing something to |
| 124 |
test might not be easy. In such a case, it's fruitful to write your first test |
| 125 |
the next time you make a change, either when you add a new feature or fix a bug. |
| 126 |
|
| 127 |
So let's do that right away. |
| 128 |
|
| 129 |
.. _test-driven development: https://en.wikipedia.org/wiki/Test-driven_development |
| 130 |
|
| 131 |
Writing our first test |
| 132 |
====================== |
| 133 |
|
| 134 |
We identify a bug |
| 135 |
----------------- |
| 136 |
|
| 137 |
Fortunately, there's a little bug in the ``polls`` application for us to fix |
| 138 |
right away: the ``Question.was_published_recently()`` method returns ``True`` if |
| 139 |
the ``Question`` was published within the last day (which is correct) but also if |
| 140 |
the ``Question``’s ``pub_date`` field is in the future (which certainly isn't). |
| 141 |
|
| 142 |
Confirm the bug by using the :djadmin:`shell` to check the method on a question |
| 143 |
whose date lies in the future: |
| 144 |
|
| 145 |
.. console:: |
| 146 |
|
| 147 |
$ python manage.py shell |
| 148 |
|
| 149 |
.. code-block:: pycon |
| 150 |
|
| 151 |
>>> import datetime |
| 152 |
>>> from django.utils import timezone |
| 153 |
>>> # create a Question instance with pub_date 30 days in the future |
| 154 |
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) |
| 155 |
>>> # was it published recently? |
| 156 |
>>> future_question.was_published_recently() |
| 157 |
True |
| 158 |
|
| 159 |
Since things in the future are not 'recent', this is clearly wrong. |
| 160 |
|
| 161 |
Create a test to expose the bug |
| 162 |
------------------------------- |
| 163 |
|
| 164 |
What we've just done in the :djadmin:`shell` to test for the problem is exactly |
| 165 |
what we can do in an automated test, so let's turn that into an automated test. |
| 166 |
|
| 167 |
A conventional place for an application's tests is in the application's |
| 168 |
``tests.py`` file; the testing system will automatically find tests in any file |
| 169 |
whose name begins with ``test``. |
| 170 |
|
| 171 |
Put the following in the ``tests.py`` file in the ``polls`` application: |
| 172 |
|
| 173 |
.. code-block:: python |
| 174 |
:caption: ``polls/tests.py`` |
| 175 |
|
| 176 |
import datetime |
| 177 |
|
| 178 |
from django.test import TestCase |
| 179 |
from django.utils import timezone |
| 180 |
|
| 181 |
from .models import Question |
| 182 |
|
| 183 |
|
| 184 |
class QuestionModelTests(TestCase): |
| 185 |
def test_was_published_recently_with_future_question(self): |
| 186 |
""" |
| 187 |
was_published_recently() returns False for questions whose pub_date |
| 188 |
is in the future. |
| 189 |
""" |
| 190 |
time = timezone.now() + datetime.timedelta(days=30) |
| 191 |
future_question = Question(pub_date=time) |
| 192 |
self.assertIs(future_question.was_published_recently(), False) |
| 193 |
|
| 194 |
Here we have created a :class:`django.test.TestCase` subclass with a method that |
| 195 |
creates a ``Question`` instance with a ``pub_date`` in the future. We then check |
| 196 |
the output of ``was_published_recently()`` - which *ought* to be False. |
| 197 |
|
| 198 |
Running tests |
| 199 |
------------- |
| 200 |
|
| 201 |
In the terminal, we can run our test: |
| 202 |
|
| 203 |
.. console:: |
| 204 |
|
| 205 |
$ python manage.py test polls |
| 206 |
|
| 207 |
and you'll see something like: |
| 208 |
|
| 209 |
.. code-block:: shell |
| 210 |
|
| 211 |
Creating test database for alias 'default'... |
| 212 |
System check identified no issues (0 silenced). |
| 213 |
F |
| 214 |
====================================================================== |
| 215 |
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests) |
| 216 |
---------------------------------------------------------------------- |
| 217 |
Traceback (most recent call last): |
| 218 |
File "/path/to/djangotutorial/polls/tests.py", line 16, in test_was_published_recently_with_future_question |
| 219 |
self.assertIs(future_question.was_published_recently(), False) |
| 220 |
AssertionError: True is not False |
| 221 |
|
| 222 |
---------------------------------------------------------------------- |
| 223 |
Ran 1 test in 0.001s |
| 224 |
|
| 225 |
FAILED (failures=1) |
| 226 |
Destroying test database for alias 'default'... |
| 227 |
|
| 228 |
.. admonition:: Different error? |
| 229 |
|
| 230 |
If instead you're getting a ``NameError`` here, you may have missed a step |
| 231 |
in :ref:`Part 2 <tutorial02-import-timezone>` where we added imports of |
| 232 |
``datetime`` and ``timezone`` to ``polls/models.py``. Copy the imports from |
| 233 |
that section, and try running your tests again. |
| 234 |
|
| 235 |
What happened is this: |
| 236 |
|
| 237 |
* ``manage.py test polls`` looked for tests in the ``polls`` application |
| 238 |
|
| 239 |
* it found a subclass of the :class:`django.test.TestCase` class |
| 240 |
|
| 241 |
* it created a special database for the purpose of testing |
| 242 |
|
| 243 |
* it looked for test methods - ones whose names begin with ``test`` |
| 244 |
|
| 245 |
* in ``test_was_published_recently_with_future_question`` it created a ``Question`` |
| 246 |
instance whose ``pub_date`` field is 30 days in the future |
| 247 |
|
| 248 |
* ... and using the ``assertIs()`` method, it discovered that its |
| 249 |
``was_published_recently()`` returns ``True``, though we wanted it to return |
| 250 |
``False`` |
| 251 |
|
| 252 |
The test informs us which test failed and even the line on which the failure |
| 253 |
occurred. |
| 254 |
|
| 255 |
Fixing the bug |
| 256 |
-------------- |
| 257 |
|
| 258 |
We already know what the problem is: ``Question.was_published_recently()`` should |
| 259 |
return ``False`` if its ``pub_date`` is in the future. Amend the method in |
| 260 |
``models.py``, so that it will only return ``True`` if the date is also in the |
| 261 |
past: |
| 262 |
|
| 263 |
.. code-block:: python |
| 264 |
:caption: ``polls/models.py`` |
| 265 |
|
| 266 |
def was_published_recently(self): |
| 267 |
now = timezone.now() |
| 268 |
return now - datetime.timedelta(days=1) <= self.pub_date <= now |
| 269 |
|
| 270 |
and run the test again: |
| 271 |
|
| 272 |
.. code-block:: pytb |
| 273 |
|
| 274 |
Creating test database for alias 'default'... |
| 275 |
System check identified no issues (0 silenced). |
| 276 |
. |
| 277 |
---------------------------------------------------------------------- |
| 278 |
Ran 1 test in 0.001s |
| 279 |
|
| 280 |
OK |
| 281 |
Destroying test database for alias 'default'... |
| 282 |
|
| 283 |
After identifying a bug, we wrote a test that exposes it and corrected the bug |
| 284 |
in the code so our test passes. |
| 285 |
|
| 286 |
Many other things might go wrong with our application in the future, but we can |
| 287 |
be sure that we won't inadvertently reintroduce this bug, because running the |
| 288 |
test will warn us immediately. We can consider this little portion of the |
| 289 |
application pinned down safely forever. |
| 290 |
|
| 291 |
More comprehensive tests |
| 292 |
------------------------ |
| 293 |
|
| 294 |
While we're here, we can further pin down the ``was_published_recently()`` |
| 295 |
method; in fact, it would be positively embarrassing if in fixing one bug we had |
| 296 |
introduced another. |
| 297 |
|
| 298 |
Add two more test methods to the same class, to test the behavior of the method |
| 299 |
more comprehensively: |
| 300 |
|
| 301 |
.. code-block:: python |
| 302 |
:caption: ``polls/tests.py`` |
| 303 |
|
| 304 |
def test_was_published_recently_with_old_question(self): |
| 305 |
""" |
| 306 |
was_published_recently() returns False for questions whose pub_date |
| 307 |
is older than 1 day. |
| 308 |
""" |
| 309 |
time = timezone.now() - datetime.timedelta(days=1, seconds=1) |
| 310 |
old_question = Question(pub_date=time) |
| 311 |
self.assertIs(old_question.was_published_recently(), False) |
| 312 |
|
| 313 |
|
| 314 |
def test_was_published_recently_with_recent_question(self): |
| 315 |
""" |
| 316 |
was_published_recently() returns True for questions whose pub_date |
| 317 |
is within the last day. |
| 318 |
""" |
| 319 |
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) |
| 320 |
recent_question = Question(pub_date=time) |
| 321 |
self.assertIs(recent_question.was_published_recently(), True) |
| 322 |
|
| 323 |
And now we have three tests that confirm that ``Question.was_published_recently()`` |
| 324 |
returns sensible values for past, recent, and future questions. |
| 325 |
|
| 326 |
Again, ``polls`` is a minimal application, but however complex it grows in the |
| 327 |
future and whatever other code it interacts with, we now have some guarantee |
| 328 |
that the method we have written tests for will behave in expected ways. |
| 329 |
|
| 330 |
Test a view |
| 331 |
=========== |
| 332 |
|
| 333 |
The polls application is fairly undiscriminating: it will publish any question, |
| 334 |
including ones whose ``pub_date`` field lies in the future. We should improve |
| 335 |
this. Setting a ``pub_date`` in the future should mean that the Question is |
| 336 |
published at that moment, but invisible until then. |
| 337 |
|
| 338 |
A test for a view |
| 339 |
----------------- |
| 340 |
|
| 341 |
When we fixed the bug above, we wrote the test first and then the code to fix |
| 342 |
it. In fact that was an example of test-driven development, but it doesn't |
| 343 |
really matter in which order we do the work. |
| 344 |
|
| 345 |
In our first test, we focused closely on the internal behavior of the code. For |
| 346 |
this test, we want to check its behavior as it would be experienced by a user |
| 347 |
through a web browser. |
| 348 |
|
| 349 |
Before we try to fix anything, let's have a look at the tools at our disposal. |
| 350 |
|
| 351 |
The Django test client |
| 352 |
---------------------- |
| 353 |
|
| 354 |
Django provides a test :class:`~django.test.Client` to simulate a user |
| 355 |
interacting with the code at the view level. We can use it in ``tests.py`` |
| 356 |
or even in the :djadmin:`shell`. |
| 357 |
|
| 358 |
We will start again with the :djadmin:`shell`, where we need to do a couple of |
| 359 |
things that won't be necessary in ``tests.py``. The first is to set up the test |
| 360 |
environment in the :djadmin:`shell`: |
| 361 |
|
| 362 |
.. console:: |
| 363 |
|
| 364 |
$ python manage.py shell |
| 365 |
|
| 366 |
.. code-block:: pycon |
| 367 |
|
| 368 |
>>> from django.test.utils import setup_test_environment |
| 369 |
>>> setup_test_environment() |
| 370 |
|
| 371 |
:meth:`~django.test.utils.setup_test_environment` installs a template renderer |
| 372 |
which will allow us to examine some additional attributes on responses such as |
| 373 |
``response.context`` that otherwise wouldn't be available. Note that this |
| 374 |
method *does not* set up a test database, so the following will be run against |
| 375 |
the existing database and the output may differ slightly depending on what |
| 376 |
questions you already created. You might get unexpected results if your |
| 377 |
``TIME_ZONE`` in ``settings.py`` isn't correct. If you don't remember setting |
| 378 |
it earlier, check it before continuing. |
| 379 |
|
| 380 |
Next we need to import the test client class (later in ``tests.py`` we will use |
| 381 |
the :class:`django.test.TestCase` class, which comes with its own client, so |
| 382 |
this won't be required): |
| 383 |
|
| 384 |
.. code-block:: pycon |
| 385 |
|
| 386 |
>>> from django.test import Client |
| 387 |
>>> # create an instance of the client for our use |
| 388 |
>>> client = Client() |
| 389 |
|
| 390 |
With that ready, we can ask the client to do some work for us: |
| 391 |
|
| 392 |
.. code-block:: pycon |
| 393 |
|
| 394 |
>>> # get a response from '/' |
| 395 |
>>> response = client.get("/") |
| 396 |
Not Found: / |
| 397 |
>>> # we should expect a 404 from that address; if you instead see an |
| 398 |
>>> # "Invalid HTTP_HOST header" error and a 400 response, you probably |
| 399 |
>>> # omitted the setup_test_environment() call described earlier. |
| 400 |
>>> response.status_code |
| 401 |
404 |
| 402 |
>>> # on the other hand we should expect to find something at '/polls/' |
| 403 |
>>> # we'll use 'reverse()' rather than a hardcoded URL |
| 404 |
>>> from django.urls import reverse |
| 405 |
>>> response = client.get(reverse("polls:index")) |
| 406 |
>>> response.status_code |
| 407 |
200 |
| 408 |
>>> response.content |
| 409 |
b'\n <ul>\n \n <li><a href="/polls/1/">What's up?</a></li>\n \n </ul>\n\n' |
| 410 |
>>> response.context["latest_question_list"] |
| 411 |
<QuerySet [<Question: What's up?>]> |
| 412 |
|
| 413 |
Improving our view |
| 414 |
------------------ |
| 415 |
|
| 416 |
The list of polls shows polls that aren't published yet (i.e. those that have a |
| 417 |
``pub_date`` in the future). Let's fix that. |
| 418 |
|
| 419 |
In :doc:`Tutorial 4 </intro/tutorial04>` we introduced a class-based view, |
| 420 |
based on :class:`~django.views.generic.list.ListView`: |
| 421 |
|
| 422 |
.. code-block:: python |
| 423 |
:caption: ``polls/views.py`` |
| 424 |
|
| 425 |
class IndexView(generic.ListView): |
| 426 |
template_name = "polls/index.html" |
| 427 |
context_object_name = "latest_question_list" |
| 428 |
|
| 429 |
def get_queryset(self): |
| 430 |
"""Return the last five published questions.""" |
| 431 |
return Question.objects.order_by("-pub_date")[:5] |
| 432 |
|
| 433 |
We need to amend the ``get_queryset()`` method and change it so that it also |
| 434 |
checks the date by comparing it with ``timezone.now()``. First we need to add |
| 435 |
an import: |
| 436 |
|
| 437 |
.. code-block:: python |
| 438 |
:caption: ``polls/views.py`` |
| 439 |
|
| 440 |
from django.utils import timezone |
| 441 |
|
| 442 |
and then we must amend the ``get_queryset`` method like so: |
| 443 |
|
| 444 |
.. code-block:: python |
| 445 |
:caption: ``polls/views.py`` |
| 446 |
|
| 447 |
def get_queryset(self): |
| 448 |
""" |
| 449 |
Return the last five published questions (not including those set to be |
| 450 |
published in the future). |
| 451 |
""" |
| 452 |
return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[ |
| 453 |
:5 |
| 454 |
] |
| 455 |
|
| 456 |
``Question.objects.filter(pub_date__lte=timezone.now())`` returns a queryset |
| 457 |
containing ``Question``\s whose ``pub_date`` is less than or equal to - that |
| 458 |
is, earlier than or equal to - ``timezone.now()``. |
| 459 |
|
| 460 |
Testing our new view |
| 461 |
-------------------- |
| 462 |
|
| 463 |
Now you can satisfy yourself that this behaves as expected by firing up |
| 464 |
``runserver``, loading the site in your browser, creating a few ``Question`` |
| 465 |
entries with dates in the past and future, and checking that only those that |
| 466 |
have been published are listed. You don't want to have to do that *every single |
| 467 |
time you make any change that might affect this* - so let's also create a test, |
| 468 |
based on our :djadmin:`shell` session above. |
| 469 |
|
| 470 |
Add the following to ``polls/tests.py``: |
| 471 |
|
| 472 |
.. code-block:: python |
| 473 |
:caption: ``polls/tests.py`` |
| 474 |
|
| 475 |
from django.urls import reverse |
| 476 |
|
| 477 |
and we'll create a shortcut function to create questions as well as a new test |
| 478 |
class: |
| 479 |
|
| 480 |
.. code-block:: python |
| 481 |
:caption: ``polls/tests.py`` |
| 482 |
|
| 483 |
def create_question(question_text, days): |
| 484 |
""" |
| 485 |
Create a question with the given `question_text` and published the |
| 486 |
given number of `days` offset to now (negative for questions published |
| 487 |
in the past, positive for questions that have yet to be published). |
| 488 |
""" |
| 489 |
time = timezone.now() + datetime.timedelta(days=days) |
| 490 |
return Question.objects.create(question_text=question_text, pub_date=time) |
| 491 |
|
| 492 |
|
| 493 |
class QuestionIndexViewTests(TestCase): |
| 494 |
def test_no_questions(self): |
| 495 |
""" |
| 496 |
If no questions exist, an appropriate message is displayed. |
| 497 |
""" |
| 498 |
response = self.client.get(reverse("polls:index")) |
| 499 |
self.assertEqual(response.status_code, 200) |
| 500 |
self.assertContains(response, "No polls are available.") |
| 501 |
self.assertQuerySetEqual(response.context["latest_question_list"], []) |
| 502 |
|
| 503 |
def test_past_question(self): |
| 504 |
""" |
| 505 |
Questions with a pub_date in the past are displayed on the |
| 506 |
index page. |
| 507 |
""" |
| 508 |
question = create_question(question_text="Past question.", days=-30) |
| 509 |
response = self.client.get(reverse("polls:index")) |
| 510 |
self.assertQuerySetEqual( |
| 511 |
response.context["latest_question_list"], |
| 512 |
[question], |
| 513 |
) |
| 514 |
|
| 515 |
def test_future_question(self): |
| 516 |
""" |
| 517 |
Questions with a pub_date in the future aren't displayed on |
| 518 |
the index page. |
| 519 |
""" |
| 520 |
create_question(question_text="Future question.", days=30) |
| 521 |
response = self.client.get(reverse("polls:index")) |
| 522 |
self.assertContains(response, "No polls are available.") |
| 523 |
self.assertQuerySetEqual(response.context["latest_question_list"], []) |
| 524 |
|
| 525 |
def test_future_question_and_past_question(self): |
| 526 |
""" |
| 527 |
Even if both past and future questions exist, only past questions |
| 528 |
are displayed. |
| 529 |
""" |
| 530 |
question = create_question(question_text="Past question.", days=-30) |
| 531 |
create_question(question_text="Future question.", days=30) |
| 532 |
response = self.client.get(reverse("polls:index")) |
| 533 |
self.assertQuerySetEqual( |
| 534 |
response.context["latest_question_list"], |
| 535 |
[question], |
| 536 |
) |
| 537 |
|
| 538 |
def test_two_past_questions(self): |
| 539 |
""" |
| 540 |
The questions index page may display multiple questions. |
| 541 |
""" |
| 542 |
question1 = create_question(question_text="Past question 1.", days=-30) |
| 543 |
question2 = create_question(question_text="Past question 2.", days=-5) |
| 544 |
response = self.client.get(reverse("polls:index")) |
| 545 |
self.assertQuerySetEqual( |
| 546 |
response.context["latest_question_list"], |
| 547 |
[question2, question1], |
| 548 |
) |
| 549 |
|
| 550 |
|
| 551 |
Let's look at some of these more closely. |
| 552 |
|
| 553 |
First is a question shortcut function, ``create_question``, to take some |
| 554 |
repetition out of the process of creating questions. |
| 555 |
|
| 556 |
``test_no_questions`` doesn't create any questions, but checks the message: |
| 557 |
"No polls are available." and verifies the ``latest_question_list`` is empty. |
| 558 |
Note that the :class:`django.test.TestCase` class provides some additional |
| 559 |
assertion methods. In these examples, we use |
| 560 |
:meth:`~django.test.SimpleTestCase.assertContains()` and |
| 561 |
:meth:`~django.test.TransactionTestCase.assertQuerySetEqual()`. |
| 562 |
|
| 563 |
In ``test_past_question``, we create a question and verify that it appears in |
| 564 |
the list. |
| 565 |
|
| 566 |
In ``test_future_question``, we create a question with a ``pub_date`` in the |
| 567 |
future. The database is reset for each test method, so the first question is no |
| 568 |
longer there, and so again the index shouldn't have any questions in it. |
| 569 |
|
| 570 |
And so on. In effect, we are using the tests to tell a story of admin input |
| 571 |
and user experience on the site, and checking that at every state and for every |
| 572 |
new change in the state of the system, the expected results are published. |
| 573 |
|
| 574 |
Testing the ``DetailView`` |
| 575 |
-------------------------- |
| 576 |
|
| 577 |
What we have works well; however, even though future questions don't appear in |
| 578 |
the *index*, users can still reach them if they know or guess the right URL. So |
| 579 |
we need to add a similar constraint to ``DetailView``: |
| 580 |
|
| 581 |
.. code-block:: python |
| 582 |
:caption: ``polls/views.py`` |
| 583 |
|
| 584 |
class DetailView(generic.DetailView): |
| 585 |
... |
| 586 |
|
| 587 |
def get_queryset(self): |
| 588 |
""" |
| 589 |
Excludes any questions that aren't published yet. |
| 590 |
""" |
| 591 |
return Question.objects.filter(pub_date__lte=timezone.now()) |
| 592 |
|
| 593 |
We should then add some tests, to check that a ``Question`` whose ``pub_date`` |
| 594 |
is in the past can be displayed, and that one with a ``pub_date`` in the future |
| 595 |
is not: |
| 596 |
|
| 597 |
.. code-block:: python |
| 598 |
:caption: ``polls/tests.py`` |
| 599 |
|
| 600 |
class QuestionDetailViewTests(TestCase): |
| 601 |
def test_future_question(self): |
| 602 |
""" |
| 603 |
The detail view of a question with a pub_date in the future |
| 604 |
returns a 404 not found. |
| 605 |
""" |
| 606 |
future_question = create_question(question_text="Future question.", days=5) |
| 607 |
url = reverse("polls:detail", args=(future_question.id,)) |
| 608 |
response = self.client.get(url) |
| 609 |
self.assertEqual(response.status_code, 404) |
| 610 |
|
| 611 |
def test_past_question(self): |
| 612 |
""" |
| 613 |
The detail view of a question with a pub_date in the past |
| 614 |
displays the question's text. |
| 615 |
""" |
| 616 |
past_question = create_question(question_text="Past Question.", days=-5) |
| 617 |
url = reverse("polls:detail", args=(past_question.id,)) |
| 618 |
response = self.client.get(url) |
| 619 |
self.assertContains(response, past_question.question_text) |
| 620 |
|
| 621 |
Ideas for more tests |
| 622 |
-------------------- |
| 623 |
|
| 624 |
We ought to add a similar ``get_queryset`` method to ``ResultsView`` and |
| 625 |
create a new test class for that view. It'll be very similar to what we have |
| 626 |
just created; in fact there will be a lot of repetition. |
| 627 |
|
| 628 |
We could also improve our application in other ways, adding tests along the |
| 629 |
way. For example, it's pointless that a ``Question`` with no related ``Choice`` |
| 630 |
can be published on the site. So, our views could check for this, and exclude |
| 631 |
such ``Question`` objects. Our tests would create a ``Question`` without a |
| 632 |
``Choice``, and then test that it's not published, as well as create a similar |
| 633 |
``Question`` *with* at least one ``Choice``, and test that it *is* published. |
| 634 |
|
| 635 |
Perhaps logged-in admin users should be allowed to see unpublished ``Question`` |
| 636 |
entries, but not ordinary visitors. Again: whatever needs to be added to |
| 637 |
the software to accomplish this should be accompanied by a test, whether you |
| 638 |
write the test first and then make the code pass the test, or work out the |
| 639 |
logic in your code first and then write a test to prove it. |
| 640 |
|
| 641 |
At a certain point you are bound to look at your tests and wonder whether your |
| 642 |
code is suffering from test bloat, which brings us to: |
| 643 |
|
| 644 |
When testing, more is better |
| 645 |
============================ |
| 646 |
|
| 647 |
It might seem that our tests are growing out of control. At this rate there will |
| 648 |
soon be more code in our tests than in our application, and the repetition |
| 649 |
is unaesthetic, compared to the elegant conciseness of the rest of our code. |
| 650 |
|
| 651 |
**It doesn't matter**. Let them grow. For the most part, you can write a test |
| 652 |
once and then forget about it. It will continue performing its useful function |
| 653 |
as you continue to develop your program. |
| 654 |
|
| 655 |
Sometimes tests will need to be updated. Suppose that we amend our views so that |
| 656 |
only ``Question`` entries with associated ``Choice`` instances are published. |
| 657 |
In that case, many of our existing tests will fail - *telling us exactly which |
| 658 |
tests need to be amended to bring them up to date*, so to that extent tests |
| 659 |
help look after themselves. |
| 660 |
|
| 661 |
At worst, as you continue developing, you might find that you have some tests |
| 662 |
that are now redundant. Even that's not a problem; in testing redundancy is |
| 663 |
a *good* thing. |
| 664 |
|
| 665 |
As long as your tests are sensibly arranged, they won't become unmanageable. |
| 666 |
Good rules-of-thumb include having: |
| 667 |
|
| 668 |
* a separate ``TestClass`` for each model or view |
| 669 |
* a separate test method for each set of conditions you want to test |
| 670 |
* test method names that describe their function |
| 671 |
|
| 672 |
Further testing |
| 673 |
=============== |
| 674 |
|
| 675 |
This tutorial only introduces some of the basics of testing. There's a great |
| 676 |
deal more you can do, and a number of very useful tools at your disposal to |
| 677 |
achieve some very clever things. |
| 678 |
|
| 679 |
For example, while our tests here have covered some of the internal logic of a |
| 680 |
model and the way our views publish information, you can use an "in-browser" |
| 681 |
framework such as Selenium_ to test the way your HTML actually renders in a |
| 682 |
browser. These tools allow you to check not just the behavior of your Django |
| 683 |
code, but also, for example, of your JavaScript. It's quite something to see |
| 684 |
the tests launch a browser, and start interacting with your site, as if a human |
| 685 |
being were driving it! Django includes :class:`~django.test.LiveServerTestCase` |
| 686 |
to facilitate integration with tools like Selenium. |
| 687 |
|
| 688 |
If you have a complex application, you may want to run tests automatically |
| 689 |
with every commit for the purposes of `continuous integration`_, so that |
| 690 |
quality control is itself - at least partially - automated. |
| 691 |
|
| 692 |
A good way to spot untested parts of your application is to check code |
| 693 |
coverage. This also helps identify fragile or even dead code. If you can't test |
| 694 |
a piece of code, it usually means that code should be refactored or removed. |
| 695 |
Coverage will help to identify dead code. See |
| 696 |
:ref:`topics-testing-code-coverage` for details. |
| 697 |
|
| 698 |
:doc:`Testing in Django </topics/testing/index>` has comprehensive |
| 699 |
information about testing. |
| 700 |
|
| 701 |
.. _Selenium: https://www.selenium.dev/ |
| 702 |
.. _continuous integration: https://en.wikipedia.org/wiki/Continuous_integration |
| 703 |
|
| 704 |
What's next? |
| 705 |
============ |
| 706 |
|
| 707 |
For full details on testing, see :doc:`Testing in Django |
| 708 |
</topics/testing/index>`. |
| 709 |
|
| 710 |
When you're comfortable with testing Django views, read |
| 711 |
:doc:`part 6 of this tutorial</intro/tutorial06>` to learn about |
| 712 |
static files management. |