Python เบื้องต้นสำหรับการทดสอบโค้ด
Alexander Levin
Data Scientist
ปัญหาที่พบบ่อย:
ปัญหาเหล่านี้อาจนำไปสู่ค่าใช้จ่ายในการแก้ไขที่สูงขึ้นอย่างมีนัยสำคัญ
การทดสอบช่วยให้:
จำเป็นต้องทดสอบเพื่อให้แน่ใจว่าตรงตามข้อกำหนดที่กำหนดไว้
Test - กระบวนการตรวจสอบความถูกต้องของแอปพลิเคชันหรือระบบซอฟต์แวร์
assertลองนึกถึงเครื่องบิน:
ทั้งหมดข้างต้นคือการทดสอบ! และจำเป็นต้องมีเพื่อความปลอดภัย

assert condition - ใช้ทดสอบว่า condition เป็น True หรือไม่condition เป็น False Python จะ raise AssertionErrorpytest - เฟรมเวิร์กสำหรับการทดสอบที่ได้รับความนิยมใน Python ช่วยให้เขียนเทสต์ได้ง่ายขึ้น
ตัวอย่างการทดสอบด้วย "assert" โดยใช้ pytest ใน Python:
import pytest
# A function to test
def squared(number):
return number * number
# A test function always starts with "test"
def test_squared():
assert squared(-2) == squared(2)
with# Writing to file example
with open("hello_world.txt", 'w') as hello_file:
hello_file.write("Hello world \n")
pytest.raises - ใช้เมื่อต้องการทดสอบว่าโค้ด raise Exception ตามที่คาดไว้
import pytest
# A function to test
def division(a, b):
return a / b
# A test function
def test_raises():
with pytest.raises(ZeroDivisionError):
division(a=25, b=0)
Testing คือ:
การนำ Tests ไปใช้งาน:
pytest - เฟรมเวิร์ก Python ที่ทรงพลัง ช่วยให้กระบวนการทดสอบง่ายขึ้นassert - คีย์เวิร์ดของ Python ใช้ใน pytest เพื่อสร้างเทสต์พื้นฐานโดยตรวจสอบเงื่อนไขpytest.raises - context manager ใช้สร้างเทสต์ที่คาดว่าจะเกิด ExceptionPython เบื้องต้นสำหรับการทดสอบโค้ด