tests.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. class ListViewTest(TestCase):
  30. def test_uses_list_template(self):
  31. response = self.client.get('/lists/the-only-list/')
  32. self.assertTemplateUsed(response, 'list.html')
  33. def test_displays_all_items(self):
  34. Item.objects.create(text='itemey 1')
  35. Item.objects.create(text='itemey 2')
  36. response = self.client.get('/lists/the-only-list/')
  37. self.assertContains(response, 'itemey 1')
  38. self.assertContains(response, 'itemey 2')
  39. class ItemModelTest(TestCase):
  40. def test_save_and_retrieve_items(self):
  41. item1 = Item()
  42. item1.text = 'The first (ever) list item'
  43. item1.save()
  44. item2 = Item()
  45. item2.text = 'Item the 2nd'
  46. item2.save()
  47. saved = Item.objects.all()
  48. self.assertEqual(saved.count(), 2)
  49. first_item = saved[0]
  50. second_item = saved[1]
  51. self.assertEqual(first_item.text, item1.text)
  52. self.assertEqual(second_item.text, item2.text)
  53. class NewListTest(TestCase):
  54. def test_can_save_a_POST_request(self):
  55. self.client.post('/lists/new', data={'item_text': 'A new list item'})
  56. self.assertEqual(Item.objects.count(), 1)
  57. new_item = Item.objects.first()
  58. self.assertEqual(new_item.text, 'A new list item')
  59. def test_redirects_after_POST(self):
  60. response = self.client.post('/lists/new', data={'item_text': 'A new list item'})
  61. self.assertRedirects(response, '/lists/the-only-list/')