tests.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from django.urls import resolve
  2. from django.test import TestCase
  3. from django.http import HttpRequest
  4. from django.template.loader import render_to_string
  5. from lists.views import home_page
  6. from lists.models import Item
  7. class HomePageTest(TestCase):
  8. def test_root_url_resolves_to_home_page_view(self):
  9. found = resolve('/')
  10. self.assertEqual(found.func, home_page)
  11. def test_uses_home_template(self):
  12. response = self.client.get('/')
  13. # The Manual Way of doing it:
  14. html = response.content.decode('utf8')
  15. self.assertTrue(html.startswith('<html>'))
  16. self.assertIn('<title>To-Do lists</title>', html)
  17. self.assertTrue(html.strip().endswith('</html>'))
  18. # Using Django's Builtin Testing Client:
  19. self.assertTemplateUsed(response, 'home.html')
  20. def test_can_save_POST_request(self):
  21. response = self.client.post('/', data={'item_text': 'A new list item'})
  22. self.assertEqual(Item.objects.count(), 1)
  23. new_item = Item.objects.first()
  24. self.assertEqual(new_item.text, 'A new list item')
  25. def test_redirects_after_POST(self):
  26. response = self.client.post('/', data={'item_text': 'A new list item'})
  27. self.assertEqual(response.status_code, 302)
  28. self.assertEqual(response['location'], '/lists/the-only-list/')
  29. def test_only_saves_items_when_needed(self):
  30. self.client.get('/')
  31. self.assertEqual(Item.objects.count(), 0)
  32. class ListViewTest(TestCase):
  33. def test_uses_list_template(self):
  34. response = self.client.get('/lists/the-only-list/')
  35. self.assertTemplateUsed(response, 'list.html')
  36. def test_displays_all_items(self):
  37. Item.objects.create(text='itemey 1')
  38. Item.objects.create(text='itemey 2')
  39. response = self.client.get('/lists/the-only-list/')
  40. self.assertContains(response, 'itemey 1')
  41. self.assertContains(response, 'itemey 2')
  42. class ItemModelTest(TestCase):
  43. def test_save_and_retrieve_items(self):
  44. item1 = Item()
  45. item1.text = 'The first (ever) list item'
  46. item1.save()
  47. item2 = Item()
  48. item2.text = 'Item the 2nd'
  49. item2.save()
  50. saved = Item.objects.all()
  51. self.assertEqual(saved.count(), 2)
  52. first_item = saved[0]
  53. second_item = saved[1]
  54. self.assertEqual(first_item.text, item1.text)
  55. self.assertEqual(second_item.text, item2.text)