วันเสาร์ที่ 17 มีนาคม พ.ศ. 2561

Test-Driven Development with Python(Chapter 4)

เนื่องจากเดิมอันเดิมยาวและติดกันเกินไปทำให้ยากต่อการอ่าน
จึงแยก (Week 3-2) - (Week 5-1) Test-Driven Development with Python ออกเป็น 7 part

Chapter 4

ทำการ import keys เพื่ออนุญาตให้เราสามารถ special keys เช่น Enter และ time เวลา

และทำการ update functional test ของเราให้เช็คเนื้อหาต่างๆมากขึ้นดังนี้
#1 - เช็ค h1
#2 - เช็ค To-Do header
#3 - เช็ค element ชื่อ 'id_new_item'
#4 - เช็ค placeholder ใน html form 'Enter a to-do item'
#5 - ทดสอบใส่คำว่า 'Buy peacock feathers'
#6 - กด enter
#7 - รอ 1 วินาที
#8 - เช็คตารางว่ามีตารางหรือไม่ และมีคำว่า '1: Buy peacock feathers'
#9 - แล้วจงใจ error พร้อม message 'Finish the test!'
เมื่อลอง run functional test จะติด error จากข้อ #1 ในข้างต้น (หา h1 ไม่เจอ)


ทำการ commit


ต่อมาหนังสือเค้าบอกว่าอย่า unit test constants และ template html text เพราะมันไม่จำเป็น unit test ใช้ในการ test logic, flow control และ configulation
ทำการสร้าง template หน้า home.html ดังภาพข้างล่าง


และทำการแก้ function home_page ใน views.py ให้ render template home.html


เมื่อทำการ unit test จะติด error หา template ไม่เจอ

จึงทำการ install app polls ลงไปใน setting.py ของโปรเจค superlists

เมื่อ test จะติด error ที่ไม่หน้าติดคือ ไม่ลงท้ายด้วย </html>

ทั้งๆที่ใน template home.html ก็ลงท้ายด้วย </html>

ซึ่งเป็นเพราะว่า ตอนจบมีการ auto "(\n)" ขึ้นบรรทัดใหม่ทำให้ test error จึงแก้ test ใช้ html.strip() แทนเพื่อกันปัญหาที่เกิด

เมื่อ run unit test จึงผ่าน

ต่อมาใน unit test (tests.py) เพิ่ม import render_to_string เพื่อให้ง่ายต่อการเช็คโดย ให้ render หน้า home เป็น string

ซึ่งก็สามารถใช้แบบแรกได้เช่นกัน แล้วเพิ่ม assert template เข้ามาเช็คหน้า home.html ตอนท้าย

เมื่อ unit test จะผ่าน

ต่อมาลองจงใจ error โดย assert กับ wrong.html แทน home.html

เมื่อ unit test จะ error ตามคาด

ซึ่งในขั้นนี้แก้ test_root_​url_resolves() เป็น test_uses_home_template()

เมื่อแก้แล้วจึง unit test ผ่าน

แล้วจึง commit

ทำการเพิ่ม body ให้ home.html ของเรามี <h1>Your To-Do list</h1>

เมื่อ functional test จะผ่าน #1 และ #2 จากข้างต้น แล้ว แต่ติด #3 ต่อ(ไม่เจอ element 'id_new_item')

จึงเพิ่ม <input id="id_new_item" />

เมื่อ functional test จะติด #4 (ไม่เจอ placeholder)

จึงเพิ่ม placeholder="Enter a to-do item"

เมื่อ functional test จะติดไม่เจอตาราง(#5)ต่อ

จึงเพิ่มตาราง

เมื่อ functional test จะติด #8 (ไม่มี '1: Buy peacock feathers' แสดงในตาราง)

ลองแก้ functional test ให้ message อ่านง่ายมากขึ้น ถ้าติด assert นี้จะแสดง 'New to-do item did not appear in table'

เมื่อ functional test error จะเปลี่ยนไป

ภาพกระบวนการ tdd

ภาพกระบวนการ tdd django

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

แสดงความคิดเห็น