From 9fa1028ce1568ebf728525d403fa9608896e9b53 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Sat, 7 Nov 2020 15:27:12 +1100 Subject: [PATCH] Finished chap3 --- textbook/chap3.md | 78 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/textbook/chap3.md b/textbook/chap3.md index 52701ef..1204748 100644 --- a/textbook/chap3.md +++ b/textbook/chap3.md @@ -125,8 +125,84 @@ Overall, the traceback can be interpreted as: "when trying to resolve `/`, Djang ## 3.6 urls.py +Django use `urls.py` in each app to map URLs to view functions. +```python +urlpatterns = [ + url(r'^admin/', admin.site.urls), +] +``` + +Note: +* This book use Django v1.11. So `path` function is not utilized, it's used in v3.x + +Explain: +* `url` start with a regex, which defines which URLs it looks for, and where (function) should these request to send +* `^$` means empty string + +Modifying `superlists.urls` to + +```python +from django.conf.urls import url +from lists import views + +urlpatterns = [ + url(r'^$', views.home_page, name='home'), +] +``` + +Generate error as shown + +``` +... +File "/home/jason/HomeWorkstation/SynologyGiteaSpace/python-tdd-book-src/src/superlists/urls.py", line 20, in + url(r'^$', views.home_page, name='home'), + File "/home/jason/miniconda3/envs/python-tdd-book/lib/python3.6/site-packages/django/conf/urls/__init__.py", line 85, in url + raise TypeError('view must be a callable or a list/tuple in the case of include().') +TypeError: view must be a callable or a list/tuple in the case of include(). +``` + +Analyzing error message "TypeError: view must be a callable or a list/tuple in the case of include().": unit tests have actually made the link btw the URL "/" and `home_page = None` in `lists/views.py`, and are now complaining that `home_page` view is not callable. + +Fix this problem via modifying `lists/views.py` + +```python +def home_page(): + pass +``` ## 3.7 Unit Testing a View -### 3.7.1 The Unit-Test/Code Cycle \ No newline at end of file +After creating simple `home_page` empty function. We can create test function in `lists/tests.py` + +```python + def test_home_page_returns_correct_html(self): + request = HttpRequest() + response = home_page(request) + html = response.content.decode('utf8') + self.assertTrue(html.startswith('')) + self.assertIn('To-Do list', html) + self.assertTrue(html.endswith('')) +``` + +Result of `python manager.py test` is: + +``` +line 15, in test_home_page_returns_correct_html + response = home_page(request) +TypeError: home_page() takes 0 positional arguments but 1 was given +``` + +### 3.7.1 The Unit-Test/Code Cycle + +TDD *unit-test/code cycle*: +1. In the terminal, run unit tests and see how they fail +2. In the editor, create minimal code change to fix test failure. +3. Repeat + +Fix the `views.py` to + +```python +def home_page(request): + return HttpResponse('To-Do list') +``` \ No newline at end of file