CLI Interface

Python เบื้องต้นสำหรับการทดสอบโค้ด

Alexander Levin

Data Scientist

ตัวอย่าง: โค้ด

ทดสอบตัวดำเนินการยกกำลัง:

# test_sqneg.py
import unittest
# Declaring the TestCase class
class TestSquared(unittest.TestCase):
    # Defining the test
    def test_negative(self):
        self.assertEqual((-3) ** 2, 9)

คำสั่ง CLI:

python3 -m unittest test_sqneg.py

รันสคริปต์ Python test_sqneg.py โดยใช้โมดูล unittest

Python เบื้องต้นสำหรับการทดสอบโค้ด

ตัวอย่าง: ผลลัพธ์

คำสั่ง: python3 -m unittest test_sqneg.py

ผลลัพธ์ของการทดสอบ: ผลลัพธ์ของ unittest test_sqneg.py

Python เบื้องต้นสำหรับการทดสอบโค้ด

อาร์กิวเมนต์ keyword -k

unittest -k - รันเมธอดและคลาสทดสอบที่ตรงกับรูปแบบหรือ substring ที่ระบุ

คำสั่ง: python3 -m unittest -k "SomeStringOrPattern" test_script.py

ตัวอย่าง: python3 -m unittest -k "Squared" test_sqneg.py

ผลลัพธ์: ผลลัพธ์เมื่อใช้ keyword

1 https://docs.python.org/3/library/unittest.html
Python เบื้องต้นสำหรับการทดสอบโค้ด

แฟล็ก Fail Fast -f

unittest -f - หยุดการทดสอบทันทีเมื่อพบข้อผิดพลาดหรือความล้มเหลวครั้งแรก

คำสั่ง: python3 -m unittest -f test_script.py

ตัวอย่างการใช้งาน: เมื่อการทดสอบทุกรายการมีความสำคัญ เช่น การตรวจสอบระบบก่อนใช้งานจริง

ตัวอย่างการทดสอบที่ล้มเหลว

1 https://docs.python.org/3/library/unittest.html
Python เบื้องต้นสำหรับการทดสอบโค้ด

แฟล็ก Catch -c

แฟล็ก Catch unittest -c - ให้หยุดการทดสอบด้วยการกด "Ctrl - C"

  • หากกด "Ctrl - C"
    • ครั้งเดียว unittest จะรอให้การทดสอบปัจจุบันเสร็จสิ้นแล้วรายงานผลที่ผ่านมาทั้งหมด
    • สองครั้ง unittest จะ raise exception KeyboardInterrupt

คำสั่ง: python3 -m unittest -c test_script.py

ตัวอย่างการใช้งาน: เมื่อ debug ชุดทดสอบขนาดใหญ่

1 https://docs.python.org/3/library/unittest.html
Python เบื้องต้นสำหรับการทดสอบโค้ด

แฟล็ก Verbose -v

unittest -v - รันการทดสอบพร้อมแสดงรายละเอียดเพิ่มเติม

คำสั่ง: python3 -m unittest -v test_script.py

ตัวอย่างการใช้งาน: สำหรับการ debug

ตัวอย่างผลลัพธ์: ผลลัพธ์ unittest เมื่อใช้แฟล็ก verbose

1 https://docs.python.org/3/library/unittest.html
Python เบื้องต้นสำหรับการทดสอบโค้ด

สรุป

  • คำสั่งพื้นฐานไม่มีอาร์กิวเมนต์ python3 -m unittest test_script.py

  • ผลลัพธ์ใน unittest

  • อาร์กิวเมนต์ keyword: python3 -m unittest -k "SomeStringOrPattern" test_script.py

  • แฟล็ก fail fast: python3 -m unittest -f test_script.py

  • แฟล็ก catch: python3 -m unittest -c test_script.py

  • แฟล็ก verbose: python3 -m unittest -v test_script.py

Python เบื้องต้นสำหรับการทดสอบโค้ด

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับการทดสอบโค้ด

Preparing Video For Download...