tutorial05.txt 28 KB

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