tutorial05.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. counter-intuitive, 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. Creating test database for alias 'default'...
  152. System check identified no issues (0 silenced).
  153. F
  154. ======================================================================
  155. FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
  156. ----------------------------------------------------------------------
  157. Traceback (most recent call last):
  158. File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
  159. self.assertIs(future_question.was_published_recently(), False)
  160. AssertionError: True is not False
  161. ----------------------------------------------------------------------
  162. Ran 1 test in 0.001s
  163. FAILED (failures=1)
  164. Destroying test database for alias 'default'...
  165. .. admonition:: Different error?
  166. If instead you're getting a ``NameError`` here, you may have missed a step
  167. in :ref:`Part 2 <tutorial02-import-timezone>` where we added imports of
  168. ``datetime`` and ``timezone`` to ``polls/models.py``. Copy the imports from
  169. that section, and try running your tests again.
  170. What happened is this:
  171. * ``manage.py test polls`` looked for tests in the ``polls`` application
  172. * it found a subclass of the :class:`django.test.TestCase` class
  173. * it created a special database for the purpose of testing
  174. * it looked for test methods - ones whose names begin with ``test``
  175. * in ``test_was_published_recently_with_future_question`` it created a ``Question``
  176. instance whose ``pub_date`` field is 30 days in the future
  177. * ... and using the ``assertIs()`` method, it discovered that its
  178. ``was_published_recently()`` returns ``True``, though we wanted it to return
  179. ``False``
  180. The test informs us which test failed and even the line on which the failure
  181. occurred.
  182. Fixing the bug
  183. --------------
  184. We already know what the problem is: ``Question.was_published_recently()`` should
  185. return ``False`` if its ``pub_date`` is in the future. Amend the method in
  186. ``models.py``, so that it will only return ``True`` if the date is also in the
  187. past:
  188. .. code-block:: python
  189. :caption: polls/models.py
  190. def was_published_recently(self):
  191. now = timezone.now()
  192. return now - datetime.timedelta(days=1) <= self.pub_date <= now
  193. and run the test again::
  194. Creating test database for alias 'default'...
  195. System check identified no issues (0 silenced).
  196. .
  197. ----------------------------------------------------------------------
  198. Ran 1 test in 0.001s
  199. OK
  200. Destroying test database for alias 'default'...
  201. After identifying a bug, we wrote a test that exposes it and corrected the bug
  202. in the code so our test passes.
  203. Many other things might go wrong with our application in the future, but we can
  204. be sure that we won't inadvertently reintroduce this bug, because running the
  205. test will warn us immediately. We can consider this little portion of the
  206. application pinned down safely forever.
  207. More comprehensive tests
  208. ------------------------
  209. While we're here, we can further pin down the ``was_published_recently()``
  210. method; in fact, it would be positively embarrassing if in fixing one bug we had
  211. introduced another.
  212. Add two more test methods to the same class, to test the behavior of the method
  213. more comprehensively:
  214. .. code-block:: python
  215. :caption: polls/tests.py
  216. def test_was_published_recently_with_old_question(self):
  217. """
  218. was_published_recently() returns False for questions whose pub_date
  219. is older than 1 day.
  220. """
  221. time = timezone.now() - datetime.timedelta(days=1, seconds=1)
  222. old_question = Question(pub_date=time)
  223. self.assertIs(old_question.was_published_recently(), False)
  224. def test_was_published_recently_with_recent_question(self):
  225. """
  226. was_published_recently() returns True for questions whose pub_date
  227. is within the last day.
  228. """
  229. time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
  230. recent_question = Question(pub_date=time)
  231. self.assertIs(recent_question.was_published_recently(), True)
  232. And now we have three tests that confirm that ``Question.was_published_recently()``
  233. returns sensible values for past, recent, and future questions.
  234. Again, ``polls`` is a minimal application, but however complex it grows in the
  235. future and whatever other code it interacts with, we now have some guarantee
  236. that the method we have written tests for will behave in expected ways.
  237. Test a view
  238. ===========
  239. The polls application is fairly undiscriminating: it will publish any question,
  240. including ones whose ``pub_date`` field lies in the future. We should improve
  241. this. Setting a ``pub_date`` in the future should mean that the Question is
  242. published at that moment, but invisible until then.
  243. A test for a view
  244. -----------------
  245. When we fixed the bug above, we wrote the test first and then the code to fix
  246. it. In fact that was an example of test-driven development, but it doesn't
  247. really matter in which order we do the work.
  248. In our first test, we focused closely on the internal behavior of the code. For
  249. this test, we want to check its behavior as it would be experienced by a user
  250. through a web browser.
  251. Before we try to fix anything, let's have a look at the tools at our disposal.
  252. The Django test client
  253. ----------------------
  254. Django provides a test :class:`~django.test.Client` to simulate a user
  255. interacting with the code at the view level. We can use it in ``tests.py``
  256. or even in the :djadmin:`shell`.
  257. We will start again with the :djadmin:`shell`, where we need to do a couple of
  258. things that won't be necessary in ``tests.py``. The first is to set up the test
  259. environment in the :djadmin:`shell`:
  260. .. console::
  261. $ python manage.py shell
  262. .. code-block:: pycon
  263. >>> from django.test.utils import setup_test_environment
  264. >>> setup_test_environment()
  265. :meth:`~django.test.utils.setup_test_environment` installs a template renderer
  266. which will allow us to examine some additional attributes on responses such as
  267. ``response.context`` that otherwise wouldn't be available. Note that this
  268. method *does not* setup a test database, so the following will be run against
  269. the existing database and the output may differ slightly depending on what
  270. questions you already created. You might get unexpected results if your
  271. ``TIME_ZONE`` in ``settings.py`` isn't correct. If you don't remember setting
  272. it earlier, check it before continuing.
  273. Next we need to import the test client class (later in ``tests.py`` we will use
  274. the :class:`django.test.TestCase` class, which comes with its own client, so
  275. this won't be required)::
  276. >>> from django.test import Client
  277. >>> # create an instance of the client for our use
  278. >>> client = Client()
  279. With that ready, we can ask the client to do some work for us::
  280. >>> # get a response from '/'
  281. >>> response = client.get('/')
  282. Not Found: /
  283. >>> # we should expect a 404 from that address; if you instead see an
  284. >>> # "Invalid HTTP_HOST header" error and a 400 response, you probably
  285. >>> # omitted the setup_test_environment() call described earlier.
  286. >>> response.status_code
  287. 404
  288. >>> # on the other hand we should expect to find something at '/polls/'
  289. >>> # we'll use 'reverse()' rather than a hardcoded URL
  290. >>> from django.urls import reverse
  291. >>> response = client.get(reverse('polls:index'))
  292. >>> response.status_code
  293. 200
  294. >>> response.content
  295. b'\n <ul>\n \n <li><a href="/polls/1/">What&#x27;s up?</a></li>\n \n </ul>\n\n'
  296. >>> response.context['latest_question_list']
  297. <QuerySet [<Question: What's up?>]>
  298. Improving our view
  299. ------------------
  300. The list of polls shows polls that aren't published yet (i.e. those that have a
  301. ``pub_date`` in the future). Let's fix that.
  302. In :doc:`Tutorial 4 </intro/tutorial04>` we introduced a class-based view,
  303. based on :class:`~django.views.generic.list.ListView`:
  304. .. code-block:: python
  305. :caption: polls/views.py
  306. class IndexView(generic.ListView):
  307. template_name = 'polls/index.html'
  308. context_object_name = 'latest_question_list'
  309. def get_queryset(self):
  310. """Return the last five published questions."""
  311. return Question.objects.order_by('-pub_date')[:5]
  312. We need to amend the ``get_queryset()`` method and change it so that it also
  313. checks the date by comparing it with ``timezone.now()``. First we need to add
  314. an import:
  315. .. code-block:: python
  316. :caption: polls/views.py
  317. from django.utils import timezone
  318. and then we must amend the ``get_queryset`` method like so:
  319. .. code-block:: python
  320. :caption: polls/views.py
  321. def get_queryset(self):
  322. """
  323. Return the last five published questions (not including those set to be
  324. published in the future).
  325. """
  326. return Question.objects.filter(
  327. pub_date__lte=timezone.now()
  328. ).order_by('-pub_date')[:5]
  329. ``Question.objects.filter(pub_date__lte=timezone.now())`` returns a queryset
  330. containing ``Question``\s whose ``pub_date`` is less than or equal to - that
  331. is, earlier than or equal to - ``timezone.now``.
  332. Testing our new view
  333. --------------------
  334. Now you can satisfy yourself that this behaves as expected by firing up
  335. ``runserver``, loading the site in your browser, creating ``Questions`` with
  336. dates in the past and future, and checking that only those that have been
  337. published are listed. You don't want to have to do that *every single time you
  338. make any change that might affect this* - so let's also create a test, based on
  339. our :djadmin:`shell` session above.
  340. Add the following to ``polls/tests.py``:
  341. .. code-block:: python
  342. :caption: polls/tests.py
  343. from django.urls import reverse
  344. and we'll create a shortcut function to create questions as well as a new test
  345. class:
  346. .. code-block:: python
  347. :caption: polls/tests.py
  348. def create_question(question_text, days):
  349. """
  350. Create a question with the given `question_text` and published the
  351. given number of `days` offset to now (negative for questions published
  352. in the past, positive for questions that have yet to be published).
  353. """
  354. time = timezone.now() + datetime.timedelta(days=days)
  355. return Question.objects.create(question_text=question_text, pub_date=time)
  356. class QuestionIndexViewTests(TestCase):
  357. def test_no_questions(self):
  358. """
  359. If no questions exist, an appropriate message is displayed.
  360. """
  361. response = self.client.get(reverse('polls:index'))
  362. self.assertEqual(response.status_code, 200)
  363. self.assertContains(response, "No polls are available.")
  364. self.assertQuerysetEqual(response.context['latest_question_list'], [])
  365. def test_past_question(self):
  366. """
  367. Questions with a pub_date in the past are displayed on the
  368. index page.
  369. """
  370. create_question(question_text="Past question.", days=-30)
  371. response = self.client.get(reverse('polls:index'))
  372. self.assertQuerysetEqual(
  373. response.context['latest_question_list'],
  374. ['<Question: Past question.>']
  375. )
  376. def test_future_question(self):
  377. """
  378. Questions with a pub_date in the future aren't displayed on
  379. the index page.
  380. """
  381. create_question(question_text="Future question.", days=30)
  382. response = self.client.get(reverse('polls:index'))
  383. self.assertContains(response, "No polls are available.")
  384. self.assertQuerysetEqual(response.context['latest_question_list'], [])
  385. def test_future_question_and_past_question(self):
  386. """
  387. Even if both past and future questions exist, only past questions
  388. are displayed.
  389. """
  390. create_question(question_text="Past question.", days=-30)
  391. create_question(question_text="Future question.", days=30)
  392. response = self.client.get(reverse('polls:index'))
  393. self.assertQuerysetEqual(
  394. response.context['latest_question_list'],
  395. ['<Question: Past question.>']
  396. )
  397. def test_two_past_questions(self):
  398. """
  399. The questions index page may display multiple questions.
  400. """
  401. create_question(question_text="Past question 1.", days=-30)
  402. create_question(question_text="Past question 2.", days=-5)
  403. response = self.client.get(reverse('polls:index'))
  404. self.assertQuerysetEqual(
  405. response.context['latest_question_list'],
  406. ['<Question: Past question 2.>', '<Question: Past question 1.>']
  407. )
  408. Let's look at some of these more closely.
  409. First is a question shortcut function, ``create_question``, to take some
  410. repetition out of the process of creating questions.
  411. ``test_no_questions`` doesn't create any questions, but checks the message:
  412. "No polls are available." and verifies the ``latest_question_list`` is empty.
  413. Note that the :class:`django.test.TestCase` class provides some additional
  414. assertion methods. In these examples, we use
  415. :meth:`~django.test.SimpleTestCase.assertContains()` and
  416. :meth:`~django.test.TransactionTestCase.assertQuerysetEqual()`.
  417. In ``test_past_question``, we create a question and verify that it appears in
  418. the list.
  419. In ``test_future_question``, we create a question with a ``pub_date`` in the
  420. future. The database is reset for each test method, so the first question is no
  421. longer there, and so again the index shouldn't have any questions in it.
  422. And so on. In effect, we are using the tests to tell a story of admin input
  423. and user experience on the site, and checking that at every state and for every
  424. new change in the state of the system, the expected results are published.
  425. Testing the ``DetailView``
  426. --------------------------
  427. What we have works well; however, even though future questions don't appear in
  428. the *index*, users can still reach them if they know or guess the right URL. So
  429. we need to add a similar constraint to ``DetailView``:
  430. .. code-block:: python
  431. :caption: polls/views.py
  432. class DetailView(generic.DetailView):
  433. ...
  434. def get_queryset(self):
  435. """
  436. Excludes any questions that aren't published yet.
  437. """
  438. return Question.objects.filter(pub_date__lte=timezone.now())
  439. And of course, we will add some tests, to check that a ``Question`` whose
  440. ``pub_date`` is in the past can be displayed, and that one with a ``pub_date``
  441. in the future is not:
  442. .. code-block:: python
  443. :caption: polls/tests.py
  444. class QuestionDetailViewTests(TestCase):
  445. def test_future_question(self):
  446. """
  447. The detail view of a question with a pub_date in the future
  448. returns a 404 not found.
  449. """
  450. future_question = create_question(question_text='Future question.', days=5)
  451. url = reverse('polls:detail', args=(future_question.id,))
  452. response = self.client.get(url)
  453. self.assertEqual(response.status_code, 404)
  454. def test_past_question(self):
  455. """
  456. The detail view of a question with a pub_date in the past
  457. displays the question's text.
  458. """
  459. past_question = create_question(question_text='Past Question.', days=-5)
  460. url = reverse('polls:detail', args=(past_question.id,))
  461. response = self.client.get(url)
  462. self.assertContains(response, past_question.question_text)
  463. Ideas for more tests
  464. --------------------
  465. We ought to add a similar ``get_queryset`` method to ``ResultsView`` and
  466. create a new test class for that view. It'll be very similar to what we have
  467. just created; in fact there will be a lot of repetition.
  468. We could also improve our application in other ways, adding tests along the
  469. way. For example, it's silly that ``Questions`` can be published on the site
  470. that have no ``Choices``. So, our views could check for this, and exclude such
  471. ``Questions``. Our tests would create a ``Question`` without ``Choices`` and
  472. then test that it's not published, as well as create a similar ``Question``
  473. *with* ``Choices``, and test that it *is* published.
  474. Perhaps logged-in admin users should be allowed to see unpublished
  475. ``Questions``, but not ordinary visitors. Again: whatever needs to be added to
  476. the software to accomplish this should be accompanied by a test, whether you
  477. write the test first and then make the code pass the test, or work out the
  478. logic in your code first and then write a test to prove it.
  479. At a certain point you are bound to look at your tests and wonder whether your
  480. code is suffering from test bloat, which brings us to:
  481. When testing, more is better
  482. ============================
  483. It might seem that our tests are growing out of control. At this rate there will
  484. soon be more code in our tests than in our application, and the repetition
  485. is unaesthetic, compared to the elegant conciseness of the rest of our code.
  486. **It doesn't matter**. Let them grow. For the most part, you can write a test
  487. once and then forget about it. It will continue performing its useful function
  488. as you continue to develop your program.
  489. Sometimes tests will need to be updated. Suppose that we amend our views so that
  490. only ``Questions`` with ``Choices`` are published. In that case, many of our
  491. existing tests will fail - *telling us exactly which tests need to be amended to
  492. bring them up to date*, so to that extent tests help look after themselves.
  493. At worst, as you continue developing, you might find that you have some tests
  494. that are now redundant. Even that's not a problem; in testing redundancy is
  495. a *good* thing.
  496. As long as your tests are sensibly arranged, they won't become unmanageable.
  497. Good rules-of-thumb include having:
  498. * a separate ``TestClass`` for each model or view
  499. * a separate test method for each set of conditions you want to test
  500. * test method names that describe their function
  501. Further testing
  502. ===============
  503. This tutorial only introduces some of the basics of testing. There's a great
  504. deal more you can do, and a number of very useful tools at your disposal to
  505. achieve some very clever things.
  506. For example, while our tests here have covered some of the internal logic of a
  507. model and the way our views publish information, you can use an "in-browser"
  508. framework such as Selenium_ to test the way your HTML actually renders in a
  509. browser. These tools allow you to check not just the behavior of your Django
  510. code, but also, for example, of your JavaScript. It's quite something to see
  511. the tests launch a browser, and start interacting with your site, as if a human
  512. being were driving it! Django includes :class:`~django.test.LiveServerTestCase`
  513. to facilitate integration with tools like Selenium.
  514. If you have a complex application, you may want to run tests automatically
  515. with every commit for the purposes of `continuous integration`_, so that
  516. quality control is itself - at least partially - automated.
  517. A good way to spot untested parts of your application is to check code
  518. coverage. This also helps identify fragile or even dead code. If you can't test
  519. a piece of code, it usually means that code should be refactored or removed.
  520. Coverage will help to identify dead code. See
  521. :ref:`topics-testing-code-coverage` for details.
  522. :doc:`Testing in Django </topics/testing/index>` has comprehensive
  523. information about testing.
  524. .. _Selenium: http://seleniumhq.org/
  525. .. _continuous integration: https://en.wikipedia.org/wiki/Continuous_integration
  526. What's next?
  527. ============
  528. For full details on testing, see :doc:`Testing in Django
  529. </topics/testing/index>`.
  530. When you're comfortable with testing Django views, read
  531. :doc:`part 6 of this tutorial</intro/tutorial06>` to learn about
  532. static files management.