Testing a Simple Home Page with Unit Tests
Our First Django App, and Our First Unit Test
ใช้คำสั่ง python3 manage.py startapp lists ใน terminalโดยคำสั่งนี้จะทำหน้าที่สร้าง folder at superlists/lists
ทำให้ได้โครงสร้างในไฟล์ดังนี้
superlists/
├── db.sqlite3
├── functional_tests.py
├── lists
│ ├── admin.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── superlists
├── __init__.py
├── __pycache__
├── settings.py
├── urls.py
└── wsgi.py
Unit Testing in Django
ให้ใส่code ที่ lists/tests.pyเมื่อเปิดไฟล์มาจะเจอดังรูป
ทดลองRun โดยใช้คำสั่ง python3 manage.py test

จากการรันโค๊ดจะได้ว่า 2 ไม่เท่ากับ 3 แสดงว่า code ทำงานได้ถูกต้อง พิ่มคำสั่ง
-git status
-git add lists
-git diff --stages
-git commit -m "Add app for lists, with deliberately failing unit test"
Functional tests จะช่วยสร้าง application ที่ถูกต้องต่อการทำงาน และจะไม่เกิดข้อผิดพลาด
Unit tests จะช่วยให้เขียน code ดูง่ายขึ้นและไม่มี bug
-เราสามารถแก้ไข Root URL in function view ได้หรือไม่
-เราสามารถทำให้ฟังก์ชัน view ส่งค่า HTML คืน ได้หรือไม่
การทดสอบเริ่มจาก
-แก้ไขไฟล์ lists/tests.py.
Django’s MVC, URLs, and View Functions
ในเรื่องนี้จะทดสอบ2อย่างนั้นคือ-เราสามารถแก้ไข Root URL in function view ได้หรือไม่
-เราสามารถทำให้ฟังก์ชัน view ส่งค่า HTML คืน ได้หรือไม่
การทดสอบเริ่มจาก
-แก้ไขไฟล์ lists/tests.py.
#1 import home_page มาจากไฟล์ views
#2 สร้าง
HttpRequest object, which is what Django will see when
a user’s browser asks for a page.-แก้ไขไฟล์ superlists/urls.py เพื่อทำการเรียกฟังก์ชั่น home_page ในไฟล์ views ใน directory lists
-แก้ไขไฟล์ lists/views.py
ทดลองรัน โดยใช้คำสั่ง python3 manage.py test
ทดลองรัน โดยใช้คำสั่ง python3 functional_tests.py (จำเป็นต้องรัน server ก่อน)
ในส่วนนี้ก็เป็นส่วนที่สิ้นสุดการทำงานของ functional_tests ของเรา
จากนั้นทำการ commit ไว้เพื่อเป็น back up เพื่อให้สามารถเรียกดูได้ในอนาคต
-git diff # should show our new test in tests.py, and the view in views.py
-git commit -am "Basic view now returns minimal HTML"
อ้างอิง http://chimera.labs.oreilly.com/books/1234000000754/ch03.html#_urls_py







ไม่มีความคิดเห็น:
แสดงความคิดเห็น