Przejdź do treści
Biblioteka skilli
Programowanie · Testowanie

pytest

/pytest

Wspiera testowanie w Python z pytest: fixtures, parametrize, mockowanie, conftest.py i pokrycie kodu.

Licencja
MIT
Ostatnia zmiana repozytorium
21.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
10
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
2
Przestarzałość

Brak sygnałów. Repozytorium zmienione 21.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Wspiera testowanie w Python z pytest: fixtures, parametrize, mockowanie, conftest.py i pokrycie kodu.

Wyzwalacze z opisu

pytestpython testfixture@pytest.fixture@pytest.mark.parametrizeconftest.pypytest coveragepython unit test
Oryginalny opis (EN)

pytest Python testing framework. Covers fixtures, parametrize, and mocking. Use for Python testing. USE WHEN: user mentions "pytest", "python test", "fixture", asks about "@pytest.fixture", "@pytest.mark.parametrize", "conftest.py", "pytest coverage", "python unit test" DO NOT USE FOR: JavaScript/TypeScript - use `vitest` or `jest`; Java - use `junit`; E2E web tests - use `playwright`; Load testing - use locust

Jak działa

  1. When NOT to Use This Skill
  2. Basic Tests
  3. Fixtures
  4. Parametrize
  5. Mocking
  6. Async Tests
  7. Property-Based Testing (Hypothesis)
  8. Configuration
  9. Production Readiness
  10. Anti-Patterns
Sekcje z nagłówków SKILL.md, w oryginale · 328 linii, 923 słów
Podgląd SKILL.md
---
name: pytest
description: |
  pytest Python testing framework. Covers fixtures, parametrize,
  and mocking. Use for Python testing.

  USE WHEN: user mentions "pytest", "python test", "fixture", asks about "@pytest.fixture", "@pytest.mark.parametrize", "conftest.py", "pytest coverage", "python unit test"

  DO NOT USE FOR: JavaScript/TypeScript - use `vitest` or `jest`; Java - use `junit`; E2E web tests - use `playwright`; Load testing - use locust
allowed-tools: Read, Grep, Glob, Write, Edit
---
# pytest Core Knowledge

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `pytest` for comprehensive documentation.

## When NOT to Use This Skill

- **JavaScript/TypeScript Testing** - Use `vitest` or `jest` for JS/TS projects
- **Java Testing** - Use `junit` for Java/Spring projects
- **E2E Web Testing** - Use `playwright` for browser automation
- **Load Testing** - Use locust or pytest-benchmark for performance
- **API Contract Testing** - Use dedicated tools like Pact

## Basic Tests

```python
def test_addition():
    assert 1 + 1 == 2

def test_list_contains():
    items = [1, 2, 3]
    assert 2 in items

def test_raises_exception():
    with pytest.raises(ValueError):
        int("not a number")

class TestUserService:
    def test_create_user(self):
        user = create_user(name="John")
        assert user.name == "John"
```

## Fixtures

```python
import pytest

@pytest.fixture
def user():
    return User(name="John", email="john@example.com")

@pytest.fixture
def db():
    connection = create_db_connection()
    yield connection
    connection.close()

def test_user_name(user):
    assert user.name == "John"

def test_user_in_db(db, user):
    db.save(user)
    assert db.find(user.id) is not None
```

## Parametrize

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

@pytest.mark.parametrize("email,valid", [
    ("test@example.com", True),
    ("invalid", False),
    ("", False),
])
def test_validate_email(email, valid):
    assert validate_email(email) == valid
```

## Mocking

```python
from unittest.mock import Mock, patch

def test_with_mock():
    mock_api = Mock()
    mock_api.get_users.return_value = [{"name": "John"}]

    result = process_users(mock_api)

    mock_api.get_users.assert_called_once()

@patch('myapp.api.requests.get')
def test_api_call(mock_get):
    mock_get.return_value.json.return_value = {"data": []}

    result = fetch_data()

    assert result == {"data": []}
```

## Async Tests

```python
import pytest

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

# With pytest-asyncio 0.23+
@pytest.mark.asyncio(loop_scope="module")
async def test_shared_loop():
    pass
```

## Property-Based Testing (Hypothesis)

```python
from hypothesis import given, strategies as st

@given(st.integers(), st.integers())
def test_addition_commutative(a: int, b: int):
    assert a + b == b + a

@given(st.lists(st.integers()))
def test_sort_idempotent(items: list[int]):
    assert sorted(sorted(items)) == sorted(items)

@given(st.text(min_size=1))
def test_string_nonempty(s: str):
    assert len(s) >= 1

# Custom strategies
@given(st.builds(User, name=st.text(min_size=1), age=st.integers(0, 150)))
def test_user_creation(user: User):
    assert user.name
    assert 0 <= user.age <= 150

# Stateful testing
from hypothesis.stateful import RuleBasedStateMachine, rule

class SetMachine(RuleBasedStateMachine):
    def __init__(self):
        self.model = set()
        self.impl = MySet()

    @rule(value=st.integers())
    def add(self, value):
        self.model.add(value)
        self.impl.add(value)
        assert self.impl.contains(value)
```

## Configuration

```ini
# pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
python_functions = test_*
addopts = -v --cov=src --cov-report=html
```

## Production Readiness

### Test Organization

```python
# tests/conftest.py - Shared fixtures
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

@pytest.fixture(scope="session")
def engine():
    """Database engine for all tests."""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    yield engine
    engine.dispose()

@pytest.fixture(scope="function")
def db_session(engine):
    """Fresh database session for each test."""
    Session = sessionmaker(bind=engine)
    session = Session()
    yield session
    session.rollback()
    session.close()

@pytest.fixture
def client(db_session):
    """Test client with database session."""
    app.dependency_overrides[get_db] = lambda: db_session
    with TestClient(app) as client:
        yield client
    app.dependency_overrides.clear()
```

### Coverage Configuration

```ini
# pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = "-v --cov=src --cov-report=term-missing --cov-report=xml --cov-fail-under=80"
markers = [
    "slow: marks tests as slow",
    "integration: integration tests",
]

[tool.coverage.run]
source = ["src"]
omit = ["*/tests/*", "*/__init__.py"]

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
    "raise NotImplementedError",
]
```

### CI Configuration

```yaml
# GitHub Actions
- name: Run tests
  run: |
    pytest --junitxml=test-results.xml --cov-report=xml

- name: Upload coverage
  uses: codecov/codecov-action@v3
  with:
    files: ./coverage.xml
```

### Factory Pattern

```python
# tests/factories.py
import factory
from faker import Faker

fake = Faker()

class UserFactory(factory.Factory):
    class Meta:
        model = User

    name = factory.LazyAttribute(lambda _: fake.name())
    email = factory.LazyAttribute(lambda _: fake.email())
    is_active = True

# Usage
def test_user_creation(db_session):
    user = UserFactory()
    db_session.add(user)
    db_session.commit()
    assert user.id is not None
```

### Monitoring Metrics

| Metric | Target |
|--------|--------|
| Line coverage | > 80% |
| Branch coverage | > 75% |
| Test execution time | < 60s |
| Flaky test rate | 0% |

### Checklist

- [ ] Fixtures in conftest.py
- [ ] Database isolation per test
- [ ] Coverage thresholds enforced
- [ ] CI/CD integration
- [ ] Factory pattern for test data
- [ ] Proper test markers
- [ ] Async tests with pytest-asyncio
- [ ] Mocking external services
- [ ] Parametrized edge cases
- [ ] Error paths tested

## Anti-Patterns

| Anti-Pattern | Why It's Bad | Solution |
|--------------|--------------|----------|
| Sharing mutable fixtures | Tests affect each other | Use function-scoped fixtures |
| Not using parametrize | Duplicate test code | Use @pytest.mark.parametrize |
| Testing implementation details | Brittle tests | Test public API behavior |
| Fixtures with side effects | Hard to debug | Keep fixtures pure, use yield for cleanup |
| No conftest.py organization | Scattered fixtures | Centralize in conftest.py |
| Ignoring warnings | Hidden issues | Treat warnings as errors in CI |
| Not mocking external services | Slow, flaky tests | Mock HTTP, database, file system |

## Quick Troubleshooting

| Problem | Likely Cause | Solution |
|---------|--------------|----------|
| "fixture not found" | Fixture not in scope | Move to conftest.py or same file |
| Test hangs | Missing await or infinite loop | Check async operations, add timeout |
| "Database is locked" | Shared DB connection | Use function-scoped DB fixtures |
| Flaky test | Shared state or timing | Isolate setup, check for race conditions |
| Import error | PYTHONPATH not set | Add src to path or use pytest.ini |
| Coverage not accurate | Missing source paths | Configure [tool.coverage.run] in pyproject.toml |

## Hypothesis Configuration

```toml
# pyproject.toml
[tool.hypothesis]
deadline = 500  # ms
max_examples = 100
database = ".hypothesis"

[tool.pytest.ini_options]
addopts = "--hypothesis-show-statistics"
```

## Reference Documentation
- [Fixtures](quick-ref/fixtures.md)
- [Mocking](quick-ref/mocking.md)

**Official docs:**
- pytest: https://docs.pytest.org/
- hypothesis: https://hypothesis.readthedocs.io/
Pliki w paczce (10)
  • SKILL.md 8 KB
  • quick-ref/alembic-testing.md 7 KB
  • quick-ref/basics.md 5 KB
  • quick-ref/fixtures.md 6 KB
  • quick-ref/grpc-testing.md 9 KB
  • quick-ref/integration-patterns.md 9 KB
  • quick-ref/pact-python.md 9 KB
  • quick-ref/redis-kafka-testing.md 9 KB
  • quick-ref/sqlalchemy-fixtures.md 8 KB
  • quick-ref/testcontainers-python.md 52 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · claude-dev-suite/claude-dev-suite100MIT
TerminalSkills/skills100Apache-2.0
xobotyi/cc-foundry100MIT
G1Joshi/Agent-Skills100MIT
aks-builds/quality-skills100MIT

Migawka bazy z 28.10.2026 · wersja paczki e89c1f2cb7e8 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100pytest-skill
    Generuje gotowe do produkcji testy pytest w Python z fixtures, parametrize, markerami, mockowaniem i wzorcami conftest.
  • 100pytest-skill
    Generuje gotowe do produkcji testy pytest w Python z fixtures, parametrize, markerami, mockowaniem i wzorcami conftest.
  • 100python-pytest-ops
    Stosuje wzorce testowania pytest w Python: fixtures, markery, parametrize, mocki, conftest, pokrycie kodu oraz testy jednostkowe i integracyjne.
  • 100python-testing
    Wspiera testowanie w Python z pytest: pokrycie kodu, fixtures i mockowanie.
  • 100pytest-fixtures
    Opisuje fixtures pytest, pliki conftest, dekoratory parametrize i zakresy fixtures przy przygotowaniu środowiska testów.
  • 100python-testing
    Pomaga pisać testy w Pythonie z pytest: jednostkowe i integracyjne, fixtury, mockowanie oraz pokrycie kodu.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.