Xpersona
P

python-testing

CLAWHUB · Unverified

Python testing patterns with pytest, fixtures, TDD, mocking, async and integration tests Skill: python-testing Owner: athola Summary: Python testing patterns with pytest, fixtures, TDD, mocking, async and integration tests Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:18:08.946Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:38:27.328Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:08.561Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:03:35.570Z | user Release v1.9.14 v1.9.13 | 2026-06

62
Rank
84
Safety
1.7k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.7K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-parseltongue-python-testing
  1. Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-parseltongue-python-testing/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

146,123 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: python-testing
description: |
  Python testing patterns with pytest, fixtures, TDD, mocking, async and integration tests
version: 1.9.8
triggers:
  - python
  - testing
  - pytest
  - tdd
  - test-automation
  - quality-assurance
  - writing or auditing a Python test suite
metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/parseltongue", "emoji": "\ud83e\uddea"}}
source: claude-night-market
source_plugin: parseltongue
---

> **Night Market Skill** — ported from [claude-night-market/parseltongue](https://github.com/athola/claude-night-market/tree/master/plugins/parseltongue). For the full experience with agents, hooks, and commands, install the Claude Code plugin.


# Python Testing Hub

Testing standards for pytest configuration, fixture management, and TDD implementation.

## Table of Contents

1. [Quick Start](#quick-start)
2. [When to Use](#when-to-use)
3. [Modules](#modules)

## Quick Start

1.  **Dependencies**: `pip install pytest pytest-cov pytest-asyncio pytest-mock`
2.  **Configuration**: Add the following to `pyproject.toml`:
    ```toml
    [tool.pytest.ini_options]
    testpaths = ["tests"]
    addopts = "--cov=src"
    ```
3.  **Verification**: Run `pytest` to confirm discovery of files matching `test_*.py`.

## When To Use

- Constructing unit and integration tests for Python 3.9+ projects.
- Isolating external dependencies using `pytest-mock` or custom monkeypatching.
- Validating asynchronous logic with `pytest-asyncio` markers and event loop management.
- Configuring project-wide coverage thresholds and reporting.

## When NOT To Use

- Evaluating test
  quality - use pensive:test-review instead
- Infrastructure test
  config - use leyline:pytest-config

## Modules

This skill uses modular loading to manage the system prompt budget.

### Core Implementation
- See `modules/unit-testing.md` - AAA (Arrange-Act-Assert) pattern, basic test structure, and exception validation.
- See `modules/fixtures-and-mocking.md` - Request-scoped fixtures, parameterization, and boundary mocking.
- See `modules/async-testing.md` - Coroutine testing, async fixtures, and concurrency validation.

### Infrastructure & Workflow
- See `modules/test-infrastructure.md` - Directory standards, `conftest.py` management, and coverage tools.
- See `modules/testing-workflows.md` - Local execution patterns and GitHub Actions integration.

### Standards
- See `modules/test-quality.md` - Identification of common anti-patterns like broad exception catching or shared state between tests.

## Exit Criteria

- Tests implement the AAA pattern.
- Coverage reaches the 80% project minimum.
- Individual tests are independent and do not rely on execution order.
- Fixtures are scoped appropriately (function, class, or session) to prevent side effects.
- Mocking is restricted to external system boundaries.

## Troubleshooting

- **Test Discovery**: Verify filenames match the `test_*.py` pattern. Use `pytest --collect-

_meta.json

{
  "ownerId": "kn7d107jg9jv602h9ytsegydq184a42s",
  "slug": "nm-parseltongue-python-testing",
  "version": "1.9.19",
  "publishedAt": 1787750288946
}

modules/async-testing.md

---
name: async-testing
description: Testing asynchronous Python code with pytest-asyncio including async fixtures and concurrent operation testing
category: testing
tags: [python, pytest, async, asyncio, pytest-asyncio, concurrent]
dependencies: [unit-testing, fixtures-and-mocking]
estimated_tokens: 275
---

# Async Testing

Patterns for testing asynchronous Python code with pytest-asyncio.

## Table of Contents

- [Basic Async Tests](#basic-async-tests)
- [Async Fixtures](#async-fixtures)
- [Testing Concurrent Operations](#testing-concurrent-operations)
- [Mocking Async Functions](#mocking-async-functions)
- [Testing Timeouts](#testing-timeouts)
- [Testing Exception Handling](#testing-exception-handling)
- [Async Context Managers](#async-context-managers)
- [Async Generators](#async-generators)
- [Configuration](#configuration)
- [Best Practices](#best-practices)
- [Common Pitfalls](#common-pitfalls)

## Basic Async Tests

Test async functions using `pytest.mark.asyncio`:

```python
import pytest

@pytest.mark.asyncio
async def test_async_function():
    result = await async_operation()
    assert result == "success"
```

Verify: Run `pytest tests/test_async.py -v` to execute async tests.

## Async Fixtures

Create async fixtures for setup/teardown:

```python
import pytest
from typing import AsyncGenerator

@pytest.fixture
async def async_client() -> AsyncGenerator[AsyncClient, None]:
    """Async fixture with setup and teardown."""
    client = AsyncClient()
    await client.connect()
    yield client
    await client.disconnect()

@pytest.mark.asyncio
async def test_with_async_client(async_client):
    response = await async_client.get("/users")
    assert response.status == 200
```

Verify: Run `pytest tests/test_async_fixtures.py -v` to test async fixtures with proper setup/teardown.

## Testing Concurrent Operations

Test multiple async operations:

```python
import asyncio
import pytest

@pytest.mark.asyncio
async def test_concurrent_requests():
    async with AsyncAPIClient() as client:
        tasks = [
            client.get_user(1),
            client.get_user(2),
            client.get_user(3),
        ]
        results = await asyncio.gather(*tasks)
        assert len(results) == 3
        assert all(r is not None for r in results)
```

## Mocking Async Functions

Mock async dependencies:

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

@pytest.mark.asyncio
@patch("aiohttp.ClientSession.get")
async def test_async_api_call(mock_get):
    mock_response = AsyncMock()
    mock_response.json.return_value = {"id": 1, "name": "Test"}
    mock_get.return_value.__aenter__.return_value = mock_response

    client = AsyncAPIClient()
    user = await client.get_user(1)

    assert user["id"] == 1
```

## Testing Timeouts

Test timeout behavior:

```python
@pytest.mark.asyncio
async def test_operation_timeout():
    with pytest.raises(asyncio.TimeoutError):
        await asyncio.wait_for(slow_operation(), timeout=0.1)
```

## Testing Exce

modules/fixtures-and-mocking.md

---
name: fixtures-and-mocking
description: Advanced pytest fixtures, parameterized tests, and mocking patterns for external dependencies
category: testing
tags: [python, pytest, fixtures, mocking, parameterization, test-setup]
dependencies: [unit-testing]
estimated_tokens: 500
---

# Fixtures and Mocking

Advanced patterns for test setup, teardown, parameterization, and mocking external dependencies.

## Table of Contents

- [Fixtures for Setup/Teardown](#fixtures-for-setupteardown)
  - [Fixture Scopes](#fixture-scopes)
- [Parameterized Tests](#parameterized-tests)
  - [Multiple Parameters](#multiple-parameters)
- [Mocking External Dependencies](#mocking-external-dependencies)
  - [Mock Patterns](#mock-patterns)
  - [Mocking Best Practices](#mocking-best-practices)
- [Fixture Composition](#fixture-composition)

## Fixtures for Setup/Teardown

Fixtures provide reusable setup and teardown logic:

```python
import pytest
from typing import Generator

@pytest.fixture
def db_session() -> Generator[Session, None, None]:
    """Fixture that provides database session."""
    session = Session()
    session.begin()
    yield session
    session.rollback()
    session.close()

def test_user_creation(db_session):
    user = User(name="Test")
    db_session.add(user)
    db_session.flush()
    assert user.id is not None
```

Verify: Run `pytest tests/test_fixtures.py -v` to confirm fixtures handle setup/teardown correctly.

### Fixture Scopes

```python
@pytest.fixture(scope="function")  # Default: new instance per test
def user():
    return User(name="Test")

@pytest.fixture(scope="class")  # Shared across test class
def api_client():
    return APIClient()

@pytest.fixture(scope="module")  # Shared across module
def database():
    db = Database()
    db.connect()
    yield db
    db.disconnect()

@pytest.fixture(scope="session")  # Once per test session
def app_config():
    return load_config()
```

## Parameterized Tests

Test multiple inputs efficiently:

```python
@pytest.mark.parametrize("email,is_valid", [
    ("user@example.com", True),
    ("test.user@domain.co.uk", True),
    ("invalid.email", False),
    ("@example.com", False),
    ("", False),
])
def test_email_validation(email, is_valid):
    assert validate_email(email) == is_valid
```

### Multiple Parameters

```python
@pytest.mark.parametrize("input_value,expected", [
    (0, "zero"),
    (1, "one"),
    (5, "many"),
])
@pytest.mark.parametrize("locale", ["en", "es", "fr"])
def test_number_formatting(input_value, expected, locale):
    result = format_number(input_value, locale)
    assert result is not None  # Locale-specific checks
```

## Mocking External Dependencies

Mock external services and APIs:

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

@patch("requests.get")
def test_api_client(mock_get):
    mock_get.return_value.json.return_value = {"id": 1, "name": "Test"}
    mock_get.return_value.raise_for_status.return_value = None

    client = APIClient("https://api.example.com

modules/test-infrastructure.md

---
name: test-infrastructure
description: Project configuration for pytest including pyproject.toml setup, test directory structure, and coverage configuration
category: testing
tags: [python, pytest, configuration, project-setup, coverage]
dependencies: []
estimated_tokens: 300
---

# Test Infrastructure

Configuration and structure for Python test suites.

## Table of Contents

- [pyproject.toml Configuration](#pyprojecttoml-configuration)
- [Test Directory Structure](#test-directory-structure)
- [conftest.py](#conftestpy)
- [Dependencies](#dependencies)
- [Coverage Configuration](#coverage-configuration)

## pyproject.toml Configuration

Complete pytest configuration in `pyproject.toml`:

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

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

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

Verify: Run `pytest --collect-only` to confirm test discovery works with this configuration.

## Test Directory Structure

Organized test layout:

```
tests/
├── conftest.py           # Shared fixtures
├── unit/                 # Unit tests
│   ├── test_models.py
│   └── test_utils.py
├── integration/          # Integration tests
│   ├── test_api.py
│   └── test_database.py
└── fixtures/             # Test data
    └── sample_data.json
```

## conftest.py

Shared fixtures and configuration:

```python
import pytest
from pathlib import Path

@pytest.fixture
def fixtures_path() -> Path:
    """Path to test fixtures directory."""
    return Path(__file__).parent / "fixtures"

@pytest.fixture
def sample_data(fixtures_path):
    """Load sample test data."""
    import json
    with open(fixtures_path / "sample_data.json") as f:
        return json.load(f)

# Pytest configuration hooks
def pytest_configure(config):
    """Configure pytest."""
    config.addinivalue_line("markers", "smoke: Quick smoke tests")

def pytest_collection_modifyitems(items):
    """Modify test collection."""
    for item in items:
        if "integration" in item.nodeid:
            item.add_marker(pytest.mark.slow)
```

## Dependencies

Add testing dependencies to `pyproject.toml`:

```toml
[project.optional-dependencies]
dev = [
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "pytest-asyncio>=0.23.0",
    "pytest-xdist>=3.5.0",  # Parallel execution
    "pytest-mock>=3.12.0",
]
```

## Coverage Configuration

Fine-tune coverage reporting:

```toml
[tool.coverage.run]
source = ["src"]
branch = true  # Branch coverage
omit = [
    "*/tests/*",
    "*/migrations/*",
    "*/__init__.py",
]

[tool.coverage.report]
precision = 2
skip_empty = true
exclude_lines = [
    "pragma: no cover",
  

Sponsored

Ads related to python-testing and adjacent AI workflows.