Chuyên sâu
⏱ 30 phút
▶ Video
12
Test Automation — Viết Tests với AI
Dùng Claude Code để viết unit tests, integration tests và tăng coverage tự động
🎬
Video cho bài học này đang được chuẩn bị.
🎯 Mục tiêu bài học
- ✓ Yêu cầu Claude Code viết test cho code có sẵn
- ✓ Tăng test coverage từ 20% lên 80%+ tự động
- ✓ Viết tests theo đúng pattern của dự án
- ✓ Dùng Claude Code để debug failing tests
Tại sao AI giỏi viết tests?
Claude Code đọc được toàn bộ source code, hiểu business logic, và biết các edge cases cần test. Viết test là một trong những tác vụ mà AI làm tốt nhất vì không ngại viết boilerplate, nhớ tất cả edge cases, và có thể tự chạy tests rồi sửa khi fail.
Viết tests cho module có sẵn
> Doc file app/database.py va viet pytest unit tests
cho tat ca cac functions. Mock DynamoDB bang moto.
Test ca happy path va error cases.
> Tao file tests/test_database.py voi coverage >= 90%
Mẫu tests điển hình
import pytest
from moto import mock_aws
import boto3
import os
os.environ["AWS_DEFAULT_REGION"] = "us-east-1"
os.environ["DYNAMODB_TABLE"] = "claudelearn_lessons"
@pytest.fixture
def aws_credentials():
os.environ["AWS_ACCESS_KEY_ID"] = "testing"
os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
@pytest.fixture
def dynamodb_table(aws_credentials):
with mock_aws():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.create_table(
TableName="claudelearn_lessons",
KeySchema=[{"AttributeName": "lesson_id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "lesson_id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table.put_item(Item={"lesson_id": "lesson-01", "title": "Test", "order": "1"})
yield table
def test_get_lesson_by_id_found(dynamodb_table):
from app.database import get_lesson_by_id
result = get_lesson_by_id("lesson-01")
assert result["lesson_id"] == "lesson-01"
def test_get_lesson_by_id_not_found(dynamodb_table):
from app.database import get_lesson_by_id
assert get_lesson_by_id("nonexistent") is None
def test_get_all_lessons_sorted(dynamodb_table):
from app.database import get_all_lessons
lessons = get_all_lessons()
orders = [int(l["order"]) for l in lessons]
assert orders == sorted(orders)
Tăng coverage tự động
> Chay pytest --cov=app --cov-report=term-missing
va xem file nao coverage thap nhat.
Sau do viet them tests de tang len it nhat 80%.
> Tim tat ca cac branch chua duoc test trong
file app/database.py va viet tests bo sung.
Debug failing tests
> Test nay dang fail:
FAILED tests/test_database.py::test_sync_lessons - AssertionError
Hay doc test file va source code, tim nguyen nhan va sua.
TDD với Claude Code
> Toi muon them function get_lessons_by_category(category: str).
Viet tests truoc, sau do implement function cho den khi tests pass.
💡 Dùng hook để tự chạy tests
Thêm PostToolUse hook chạy pytest -x -q sau mỗi lần Edit. Claude Code sẽ thấy kết quả ngay và tự sửa nếu có test fail.