tutorial05.txt 28 KB

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