Chuyển đến nội dung
Skillpedia
Kiểm thử48k · #5544

pytest-skill

Skill này làm gì

Công cụ này giúp tạo các test tự động cho code Python bằng thư viện pytest. Nó tạo ra các test kiểm tra code hoạt động đúng như mong đợi, kể cả trong các tình huống phức tạp.

Khi nào nên dùng

  • ✓Khi bạn cần viết test cho code Python.
  • ✓Khi dùng thư viện pytest và muốn tận dụng các tính năng nâng cao của nó.
  • ✓Để đảm bảo code Python hoạt động đúng trong nhiều tình huống khác nhau.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pytest-skill/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pytest-skill/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Tạo các test pytest cho hàm cộng hai số của tôi, dùng fixture và parametrize.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Công cụ dùng các mẫu pytest phổ biến như fixture để chuẩn bị môi trường test, parametrize để kiểm thử nhiều giá trị và marker để sắp xếp test. Nó cũng có thể mô phỏng một phần code (mocking) để cô lập phần đang được kiểm thử.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Pytest Testing Skill

When to Use

Use this skill when you need generates production-grade pytest tests in Python with fixtures, parametrize, markers, mocking, and conftest patterns. Use when user mentions "pytest", "conftest", "@pytest.fixture", "@pytest.mark", "Python test". Triggers on: "pytest", "conftest", "Python test", "parametrize", "Python...

Core Patterns

Basic Test

import pytest

def test_addition():
    assert 2 + 3 == 5

def test_exception():
    with pytest.raises(ValueError, match="invalid"):
        int("not_a_number")

class TestCalculator:
    def test_add(self):
        calc = Calculator()
        assert calc.add(2, 3) == 5

    def test_divide_by_zero(self):
        with pytest.raises(ZeroDivisionError):
            Calculator().divide(10, 0)

Fixtures

@pytest.fixture
def calculator():
    return Calculator()

@pytest.fixture
def db_connection():
    conn = Database.connect("test_db")
    yield conn  # teardown after yield
    conn.rollback()
    conn.close()

@pytest.fixture(scope="module")
def api_client():
    client = APIClient(base_url="http://localhost:8000")
    yield client
    client.logout()

# conftest.py - shared fixtures
@pytest.fixture(autouse=True)
def reset_state():
    State.reset()
    yield
    State.cleanup()

# Usage
def test_add(calculator):
    assert calculator.add(2, 3) == 5

Parametrize

@pytest.mark.parametrize("input,expected", [
    ("hello", 5), ("", 0), ("pytest", 6),
])
def test_string_length(input, expected):
    assert len(input) == expected

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5), (-1, 1, 0), (0, 0, 0),
])
def test_add(calculator, a, b, expected):
    assert calculator.add(a, b) == expected

Markers

@pytest.mark.slow
def test_large_dataset(): ...

@pytest.mark.skip(reason="Not implemented")
def test_future_feature(): ...

@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_permissions(): ...

@pytest.mark.xfail(reason="Known bug #123")
def test_known_bug(): ...

Mocking

from unittest.mock import patch, MagicMock

def test_send_email(mocker):
    mock_smtp = mocker.patch("myapp.email.smtplib.SMTP")
    send_welcome_email("user@test.com")
    mock_smtp.return_value.sendmail.assert_called_once()

def test_api_call(mocker):
    mock_response = mocker.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"users": [{"name": "Alice"}]}
    mocker.patch("myapp.service.requests.get", return_value=mock_response)
    users = get_users()
    assert len(users) == 1

@patch("myapp.service.database")
def test_save_user(mock_db):
    mock_db.save.return_value = True
    assert save_user({"name": "Alice"}) is True
    mock_db.save.assert_called_once()

Assertions

assert x == y
assert x != y
assert x in collection
assert isinstance(obj, MyClass)
assert 0.1 + 0.2 == pytest.approx(0.3)

with pytest.raises(ValueError) as exc_info:
    raise ValueError("bad")
assert "bad" in str(exc_info.value)

Anti-Patterns

Bad Good Why
self.assertEqual() assert x == y pytest rewrites give better output
Setup in __init__ @pytest.fixture Lifecycle management
Global state Fixture with yield Proper cleanup
Huge test functions Small focused tests Easier debugging

Quick Reference

Task Command
Run all pytest
Run file pytest tests/test_login.py
Run specific pytest tests/test_login.py::test_login_success
By marker pytest -m slow
By keyword pytest -k "login and not invalid"
Verbose pytest -v
Stop first fail pytest -x
Last failed pytest --lf
Coverage pytest --cov=myapp --cov-report=html
Parallel pytest -n auto (pytest-xdist)

pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: slow tests", "integration: integration tests"]
addopts = "-v --tb=short"

Deep Patterns

For production-grade patterns, see reference/playbook.md:

Section What's Inside
§1 Config pytest.ini + pyproject.toml with markers, coverage
§2 Fixtures Scoping, factories, teardown, autouse, tmp_path
§3 Parametrize Basic, with IDs, cartesian, indirect
§4 Mocking pytest-mock, monkeypatch, spies, env vars
§5 Async pytest-asyncio, async fixtures, async client

…

Câu hỏi thường gặp

“Fixtures” là gì?

Fixtures giống như các bước chuẩn bị cho test. Chúng thiết lập môi trường hoặc dữ liệu cần thiết trước khi test chạy và có thể dọn dẹp sau đó.

“Parametrize” là gì?

Parametrize cho phép chạy cùng một test nhiều lần với các dữ liệu khác nhau, mà không phải viết lại test nhiều lần.

“Mocking” là gì?

Mocking là tạo các phiên bản giả của một phần code (như các lệnh gọi mạng hoặc tương tác cơ sở dữ liệu) để bạn kiểm thử code chính một cách độc lập.

Chi tiết

Mô tả gốc của tác giả

Generates production-grade pytest tests in Python with fixtures, parametrize, markers, mocking, and conftest patterns. Use when user mentions \"pytest\", \"conftest\", \"@pytest.fixture\", \"@pytest.mark\", \"Python test\".

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5544
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự