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
คำสั่ง:
python3 -m unittest test_sqneg.py
ผลลัพธ์ของการทดสอบ:

unittest -k - รันเมธอดและคลาสทดสอบที่ตรงกับรูปแบบหรือ substring ที่ระบุ
คำสั่ง:
python3 -m unittest -k "SomeStringOrPattern" test_script.py
ตัวอย่าง:
python3 -m unittest -k "Squared" test_sqneg.py
ผลลัพธ์:

unittest -f - หยุดการทดสอบทันทีเมื่อพบข้อผิดพลาดหรือความล้มเหลวครั้งแรก
คำสั่ง: python3 -m unittest -f test_script.py
ตัวอย่างการใช้งาน: เมื่อการทดสอบทุกรายการมีความสำคัญ เช่น การตรวจสอบระบบก่อนใช้งานจริง

แฟล็ก Catch unittest -c - ให้หยุดการทดสอบด้วยการกด "Ctrl - C"
unittest จะรอให้การทดสอบปัจจุบันเสร็จสิ้นแล้วรายงานผลที่ผ่านมาทั้งหมดunittest จะ raise exception KeyboardInterruptคำสั่ง: python3 -m unittest -c test_script.py
ตัวอย่างการใช้งาน: เมื่อ debug ชุดทดสอบขนาดใหญ่
unittest -v - รันการทดสอบพร้อมแสดงรายละเอียดเพิ่มเติม
คำสั่ง: python3 -m unittest -v test_script.py
ตัวอย่างการใช้งาน: สำหรับการ debug
ตัวอย่างผลลัพธ์: 
คำสั่งพื้นฐานไม่มีอาร์กิวเมนต์ 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 เบื้องต้นสำหรับการทดสอบโค้ด