FastAPI Backend Development Bootcamp · บทเรียน

การทดสอบหน่วยด้วย Pytest

เขียนการทดสอบหน่วยที่มีประสิทธิภาพสำหรับฟังก์ชันและมอดูล FastAPI ด้วยเฟรมเวิร์ก Pytest

บทเรียน 1 จาก 411 ขั้นตอน

การทดสอบหน่วยด้วย Pytest เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What is Unit Testing?

Welcome to unit testing! This is a fundamental practice in software development that helps ensure your code works correctly.

  • Unit testing focuses on testing the smallest testable parts of an application, called 'units'.
  • A 'unit' can be a function, a method, or a class. The goal is to isolate it and verify it behaves as expected.
  • This helps catch bugs early, makes code easier to refactor, and builds confidence in your application's reliability.

Introducing Pytest

For Python, one of the most popular and powerful testing frameworks is Pytest. It's known for its simplicity and flexibility.

  • Pytest makes it easy to write simple, yet scalable tests.
  • It automatically discovers tests, provides detailed failure reports, and supports advanced features like fixtures.
  • You'll find Pytest widely used in the Python community, including for FastAPI projects.

Installing Pytest

Before we write our first test, we need to install Pytest. It's a standard Python package.

Open your terminal or command prompt and run the following command:

pip install pytest

Your First Function to Test

Let's create a simple Python function that we want to test. We'll put this in a file named utils.py.

This function simply multiplies two numbers. We'll write tests to ensure it always returns the correct product.

def multiply(x, y):
    return x * y

if __name__ == "__main__":
    # This part shows how to use the function directly
    print(f"5 * 3 = {multiply(5, 3)}")
    print(f"10 * 0 = {multiply(10, 0)}")

Crafting Your First Test

Now, let's write tests for our multiply function. Pytest automatically discovers test files that start with test_ (e.g., test_utils.py) and test functions within them that also start with test_.

Create a new file named test_utils.py in the same directory as utils.py:

from utils import multiply # Import the function to test

def test_multiply_positive_numbers():
    # Check if 2 * 3 equals 6
    assert multiply(2, 3) == 6

def test_multiply_by_zero():
    # Check if any number multiplied by zero is zero
    assert multiply(5, 0) == 0

def test_multiply_negative_numbers():
    # Check multiplication with a negative number
    assert multiply(-2, 4) == -8

Executing Your Tests

With both utils.py and test_utils.py saved in the same folder, you can now run your tests!

Open your terminal in that directory and simply type pytest. Pytest will find and execute all tests.

# In your terminal or command prompt:
pytest

Understanding Assertions

The core of any test is the assert statement. It's how you verify that a condition is true. If an assert statement fails, Pytest marks the test as failed.

Here are some common ways to use assert:

  • assert actual == expected: Checks if two values are equal.
  • assert actual != unexpected: Checks if two values are not equal.
  • assert item in collection: Checks if an item exists in a list, set, or string.
  • assert not condition: Checks if a condition is false.
  • assert value > 0: Checks for numerical comparisons.

Reusable Test Setup with Fixtures

Sometimes, multiple tests need the same setup (e.g., a temporary file, a configured object). Pytest fixtures provide a way to define reusable setup and teardown logic.

A fixture is a function decorated with @pytest.fixture. Tests can then request the fixture by naming it as an argument.

import pytest

@pytest.fixture
def sample_data():
    # This fixture provides a list of numbers for tests
    print("\nSetting up sample_data") # Runs before tests
    yield [10, 20, 30]
    print("\nTeardown sample_data") # Runs after tests

def test_data_length(sample_data):
    assert len(sample_data) == 3

def test_data_contains_value(sample_data):
    assert 20 in sample_data

Handling Expected Errors

What if your function is supposed to raise an error under certain conditions? Pytest can test for that too, using pytest.raises.

This ensures your error handling logic works correctly by asserting that a specific exception is raised.

# my_processor.py
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

# test_my_processor.py
import pytest
from my_processor import divide

def test_divide_by_zero_raises_error():
    with pytest.raises(ValueError, match="Cannot divide by zero!"):
        divide(10, 0)

def test_divide_positive_numbers():
    assert divide(10, 2) == 5.0

Pytest Fundamentals Check

Consider the Python function and the Pytest test below:

# calculator.py
def add(a, b):
    return a + b

# test_calculator.py
from calculator import add

def test_add_positive():
    assert add(5, 3) == 8

def test_add_negative_numbers():
    assert add(-2, -4) == -6

def test_add_mixed_numbers():
    assert add(10, -5) == 5

If you run pytest in the terminal, what will be the outcome?

Unit Testing Recap

Great job! You've learned the basics of unit testing with Pytest. This is a crucial skill for building robust applications.

  • Unit tests verify small, isolated parts of your code.
  • Pytest is a powerful and easy-to-use framework for writing and running these tests.
  • You use assert statements to check for expected outcomes.
  • Fixtures help set up reusable data or resources for your tests.
  • pytest.raises is used to test that your code correctly raises specific exceptions.

Next, we'll explore how to perform integration testing specifically for your FastAPI endpoints!

เริ่มต้นได้ฟรี

เรียนรู้ FastAPI Backend Development Bootcamp ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
21
บทเรียน
84

คำถามที่พบบ่อย

บทเรียน “การทดสอบหน่วยด้วย Pytest” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การทดสอบหน่วยด้วย Pytest” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบหน่วยด้วย Pytest”

เขียนการทดสอบหน่วยที่มีประสิทธิภาพสำหรับฟังก์ชันและมอดูล FastAPI ด้วยเฟรมเวิร์ก Pytest คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การทดสอบหน่วยด้วย Pytest” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การทดสอบหน่วยด้วย Pytest
  2. การทดสอบการผสานรวมจุดปลายทาง FastAPI
  3. การแก้ไขข้อบกพร่องของแอปพลิเคชัน FastAPI
  4. การจำลองการพึ่งพาในการทดสอบ FastAPI
← กลับไปที่ FastAPI Backend Development Bootcamp