tutorial05.txt 27 KB

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