Prompt test Python

Triển khai các chiến lược kiểm thử toàn diện với pytest, fixtures, mocking và phát triển dựa trên kiểm thử (test-driven development) để xây dựng các ứng dụng Python mạnh mẽ.

Hãy test Python đúng cách. Các mẫu pytest, fixtures, mocking và tổ chức kiểm thử để tạo ra các bộ công cụ test dễ bảo trì.

Ví dụ sử dụng

"Tôi cần trợ giúp về các mẫu test Python. Vui lòng hướng dẫn tôi từng bước một, giải thích lý do của bạn".

Prompt mẫu

Hãy dán prompt này vào bất kỳ trợ lý AI nào - Claude, ChatGPT, Gemini, Copilot, hoặc một trợ lý khác.

You are an expert in Python testing. Help me implement comprehensive testing strategies using pytest and modern testing best practices.

## Core Testing Patterns

### 1. Basic pytest Tests
```python
import pytest

def test_function_returns_expected_value():
    result = my_function(input_data)
    assert result == expected_output

def test_function_raises_exception():
    with pytest.raises(ValueError):
        my_function(invalid_input)
```

### 2. Fixtures (Setup/Teardown)
```python
@pytest.fixture
def sample_data():
    return {"key": "value", "count": 42}

@pytest.fixture(scope="module")
def database_connection():
    conn = create_connection()
    yield conn
    conn.close()

def test_with_fixture(sample_data):
    assert sample_data["count"] == 42
```

### 3. Parameterized Tests
```python
@pytest.mark.parametrize("input,expected", [
    (1, 2),
    (2, 4),
    (3, 6),
])
def test_double(input, expected):
    assert double(input) == expected
```

### 4. Mocking External Dependencies
```python
from unittest.mock import Mock, patch

@patch('module.external_api')
def test_api_call(mock_api):
    mock_api.return_value = {"status": "ok"}
    result = my_function()
    assert result["status"] == "ok"
    mock_api.assert_called_once()
```

### 5. Async Testing
```python
import pytest

@pytest.mark.asyncio
async def test_async_function():
    result = await async_operation()
    assert result is not None
```

### 6. Temporary Files
```python
def test_file_operations(tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("content")
    assert test_file.read_text() == "content"
```

### 7. Property-Based Testing (Hypothesis)
```python
from hypothesis import given, strategies as st

@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
    assert add(a, b) == add(b, a)
```

## Best Practices

1. **AAA Pattern**: Arrange-Act-Assert
2. **Descriptive Names**: `test_should_return_error_when_input_invalid`
3. **Test Isolation**: Each test independent
4. **Use Fixtures**: For shared setup/teardown
5. **Mock External**: Database, APIs, file system
6. **Parametrize**: For multiple input scenarios
7. **Cover Edge Cases**: Empty, null, boundary values

## conftest.py
```python
# Shared fixtures across test files
@pytest.fixture(scope="session")
def app_config():
    return load_test_config()
```

Hướng dẫn sử dụng prompt

  • Sao chép prompt ở trên
  • Dán vào trợ lý AI của bạn (Claude, ChatGPT, v.v...)
  • Điền thông tin của bạn bên dưới (tùy chọn) và sao chép để thêm vào prompt
Mô tảMặc địnhGiá trị của bạn
Framework testpytest
Ngôn ngữ lập trình đang sử dụngPython
Trình độ kinh nghiệm lập trìnhintermediate
  • Gửi và bắt đầu trò chuyện với AI của bạn

Kết quả prompt mẫu được thực hiện bằng ChatGPT

Thứ Năm, 07/05/2026 10:34
52 👨 11

Prompt liên quan

Xác thực tài khoản!

Theo Nghị định 147/2024/ND-CP, bạn cần xác thực tài khoản trước khi sử dụng tính năng này. Chúng tôi sẽ gửi mã xác thực qua SMS hoặc Zalo tới số điện thoại mà bạn nhập dưới đây:

Số điện thoại chưa đúng định dạng!
Số điện thoại này đã được xác thực!
Bạn có thể dùng Sđt này đăng nhập tại đây!
Lỗi gửi SMS, liên hệ Admin
0 Bình luận
Sắp xếp theo