Finished up to chap 3.7: Basic view now returns minimal HTML

chap3
Jason Zhu 2020-11-07 15:23:42 +11:00
parent 1827d492d6
commit bfaffaa997
2 changed files with 24 additions and 3 deletions

View File

@ -1,5 +1,7 @@
from django.test import TestCase from django.test import TestCase
from django.urls import resolve from django.urls import resolve
from django.http import HttpRequest
from lists.views import home_page from lists.views import home_page
class HomePageTest(TestCase): class HomePageTest(TestCase):
@ -7,3 +9,19 @@ class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self): def test_root_url_resolves_to_home_page_view(self):
found = resolve('/') found = resolve('/')
self.assertEqual(found.func, home_page) self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
"""
1. Create an HttpRequest object, which is what Django will see when a user's browser asks for a page
2. Pass it to `home_page` view, which gives us a response.
3. Extract `.content` of the response, which are byte value, and should be decoded into string (HTML format)
4. Check HTML starts and end with <html> tag
5. Want to find <title> tag in the middle
"""
request = HttpRequest() #1
response = home_page(request) #2
html = response.content.decode('utf8') #3
self.assertTrue(html.startswith('<html>')) #4
self.assertIn('<title>To-Do list</title>', html) #5
self.assertTrue(html.endswith('</html>')) #4

View File

@ -1,5 +1,8 @@
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.shortcuts import render from django.shortcuts import render
# Create your views here # Create your views here
def home_page(): def home_page(request):
pass # return HttpResponse('<html><title>To-Do lists</title></html>')
return HttpResponse('<html><title>To-Do list</title></html>')