Pytest Oop Patterns logo

Pytest Oop Patterns

Community
manikosto
pytest-oop-patterns

OOP-based pytest patterns for API test automation — base classes, service layers, fixtures hierarchy, parametrization, markers, parallel execution, and test isolation.

Overview

Publishermanikosto
Repositoryclaude-code-python-stack
Skill namepytest-oop-patterns
Stars
54
Forks
10
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by manikosto on GitHub. Read the source before you install it.

Installation

Install the Pytest Oop Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/manikosto/claude-code-python-stack/tree/main/skills/pytest-oop-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/manikosto/claude-code-python-stack.git /tmp/claude-code-python-stack
mkdir -p .claude/skills
cp -r /tmp/claude-code-python-stack/skills/pytest-oop-patterns .claude/skills/pytest-oop-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Pytest Oop Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Pytest Oop Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Pytest Oop Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

OOP Pytest Patterns for API Testing

Strict OOP patterns for building maintainable, scalable pytest test suites.

When to Activate

  • Designing test framework architecture
  • Writing new API test suites
  • Reviewing test code for OOP compliance
  • Setting up pytest infrastructure (conftest, fixtures, markers)

RULE: No Bare Functions

Every test MUST be inside a class. This is non-negotiable.

python
# WRONG -- procedural, no encapsulation
def test_create_user():
    response = httpx.post("/users", json={"email": "a@b.com"})
    assert response.status_code == 201

# CORRECT -- OOP, inherits BaseTest, uses service class
@allure.feature("User Management")
class TestCreateUser(BaseTest):
    def test_create_user_returns_201(self):
        data = self.gen.create_user_request()
        response = self.users_api.create_user(data)
        assert response.status_code == 201

Base Test Class

python
import pytest
import allure
from framework.clients.http_client import HTTPClient
from framework.config.settings import Settings


class BaseTest:
    """Base class for ALL test classes."""

    client: HTTPClient
    settings: Settings

    @pytest.fixture(autouse=True)
    def _setup_base(self, http_client: HTTPClient, settings: Settings):
        """Inject shared dependencies."""
        self.client = http_client
        self.settings = settings


class BaseAuthenticatedTest(BaseTest):
    """Base for tests requiring authentication."""

    @pytest.fixture(autouse=True)
    def _setup_auth(self, authenticated_client: HTTPClient):
        self.client = authenticated_client

API Service Layer

python
from framework.base.base_api_client import BaseAPIClient


class BaseAPIClient:
    """Base for all API service classes."""

    def __init__(self, client: HTTPClient):
        self.client = client


class UsersAPI(BaseAPIClient):
    ENDPOINT = "/api/v1/users"

    @allure.step("POST /users — Create user: {data.email}")
    def create_user(self, data: CreateUserRequest) -> httpx.Response:
        return self.client.post(self.ENDPOINT, json=data.model_dump())

    @allure.step("GET /users/{user_id}")
    def get_user(self, user_id: int) -> httpx.Response:
        return self.client.get(f"{self.ENDPOINT}/{user_id}")

    @allure.step("GET /users — List (page={page})")
    def list_users(self, page: int = 1, per_page: int = 20) -> httpx.Response:
        return self.client.get(self.ENDPOINT, params={"page": page, "per_page": per_page})

    @allure.step("PATCH /users/{user_id}")
    def update_user(self, user_id: int, data: dict) -> httpx.Response:
        return self.client.patch(f"{self.ENDPOINT}/{user_id}", json=data)

    @allure.step("DELETE /users/{user_id}")
    def delete_user(self, user_id: int) -> httpx.Response:
        return self.client.delete(f"{self.ENDPOINT}/{user_id}")

Fixtures Hierarchy

Root conftest.py (session-scoped)

python
# conftest.py
import pytest
from framework.clients.http_client import HTTPClient
from framework.config.settings import Settings


@pytest.fixture(scope="session")
def settings() -> Settings:
    return Settings()

@pytest.fixture(scope="session")
def http_client(settings: Settings) -> HTTPClient:
    client = HTTPClient(settings)
    yield client
    client.close()

@pytest.fixture(scope="session")
def auth_token(http_client, settings) -> str:
    from api.auth_api import AuthAPI
    auth = AuthAPI(http_client)
    resp = auth.login(settings.TEST_USER_EMAIL, settings.TEST_USER_PASSWORD)
    return resp.json()["access_token"]

@pytest.fixture
def authenticated_client(settings, auth_token) -> HTTPClient:
    client = HTTPClient(settings, token=auth_token)
    yield client
    client.close()

Module conftest.py (test-specific)

python
# tests/test_users/conftest.py
import pytest
from api.users_api import UsersAPI
from framework.helpers.data_generator import DataGenerator


@pytest.fixture
def users_api(http_client) -> UsersAPI:
    return UsersAPI(http_client)

@pytest.fixture
def created_user(users_api: UsersAPI) -> dict:
    """Create a user and return response body. Cleanup after test."""
    data = DataGenerator.create_user_request()
    response = users_api.create_user(data)
    user = response.json()
    yield user
    users_api.delete_user(user["id"])  # Cleanup

Parametrization Patterns

Data-driven tests

python
@allure.feature("Input Validation")
class TestUserValidation(BaseTest):

    @pytest.mark.parametrize("field,value,error_field", [
        ("email", "not-email", "email"),
        ("email", "", "email"),
        ("password", "123", "password"),
        ("name", "", "name"),
        ("name", "x" * 256, "name"),
    ], ids=[
        "invalid-email-format",
        "empty-email",
        "short-password",
        "empty-name",
        "name-too-long",
    ])
    @allure.story("Field validation")
    def test_create_user_field_validation(self, field: str, value: str, error_field: str):
        data = self.gen.create_user_request(**{field: value})
        response = self.users_api.create_user(data)

        assert response.status_code == 422
        errors = response.json()
        assert any(error_field in str(e) for e in errors.get("detail", []))

Status code matrix

python
@allure.feature("Authorization")
class TestUserAuthorization(BaseTest):

    @pytest.mark.parametrize("method,endpoint,expected", [
        ("GET", "/api/v1/users", 401),
        ("POST", "/api/v1/users", 401),
        ("GET", "/api/v1/users/1", 401),
        ("DELETE", "/api/v1/users/1", 401),
    ], ids=["list", "create", "get", "delete"])
    @allure.story("Unauthorized access returns 401")
    def test_unauthenticated_returns_401(self, method: str, endpoint: str, expected: int):
        response = getattr(self.client, method.lower())(endpoint)
        assert response.status_code == expected

Markers

ini
# pyproject.toml
[tool.pytest.ini_options]
markers = [
    "smoke: Quick sanity checks (< 30 seconds total)",
    "regression: Full regression suite",
    "critical: Business-critical flows",
    "negative: Negative/error scenarios",
    "slow: Tests > 10 seconds",
    "flaky: Known flaky tests (quarantined)",
]
python
@pytest.mark.smoke
@pytest.mark.critical
class TestAuthSmoke(BaseAuthenticatedTest):
    def test_login_returns_token(self): ...

    def test_token_refresh_works(self): ...
bash
# Run smoke suite
pytest -m smoke --alluredir=allure-results

# Run everything except flaky
pytest -m "not flaky"

# Run critical regression
pytest -m "critical and regression"

Parallel Execution

bash
# Install
pip install pytest-xdist

# Run parallel (auto-detect CPU count)
pytest -n auto --alluredir=allure-results

# Fixed worker count
pytest -n 4

Rules for parallel-safe tests:

  • No shared mutable state (class variables, global dicts)
  • Each test creates its own entities
  • Fixtures with scope="session" must be thread-safe
  • Use unique identifiers (UUID) in test data, not sequential IDs

Custom Assertions

python
import allure
from framework.models.response_models import ErrorResponse


class Assertions:
    """Custom assertion helpers with Allure integration."""

    @staticmethod
    @allure.step("Assert status code is {expected}")
    def assert_status(response, expected: int):
        assert response.status_code == expected, (
            f"Expected {expected}, got {response.status_code}. "
            f"Body: {response.text[:200]}"
        )

    @staticmethod
    @allure.step("Assert response matches schema {model.__name__}")
    def assert_schema(response, model: type):
        """Validate response body against Pydantic model."""
        data = response.json()
        parsed = model.model_validate(data)
        return parsed

    @staticmethod
    @allure.step("Assert error response contains: {expected_detail}")
    def assert_error(response, expected_status: int, expected_detail: str | None = None):
        assert response.status_code == expected_status
        if expected_detail:
            error = ErrorResponse.model_validate(response.json())
            assert expected_detail in error.detail

Quick Reference

PatternDescription
BaseTestAll test classes inherit from this
BaseAPIClientAll API services inherit from this
@allure.stepEvery API method gets this decorator
DataGeneratorFactory for test data (faker-based)
AssertionsCustom assertion helpers
conftest.py hierarchyRoot (session) -> module -> suite
@pytest.mark.parametrizeData-driven testing
pytest -n autoParallel execution
Arrange-Act-AssertMandatory test structure

Frequently asked questions

What does the Pytest Oop Patterns AI skill do?

OOP-based pytest patterns for API test automation — base classes, service layers, fixtures hierarchy, parametrization, markers, parallel execution, and test isolation.

Why use Pytest Oop Patterns on TypingMind?

Because you install it once and use it with any model. Pytest Oop Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Pytest Oop Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/manikosto/claude-code-python-stack/tree/main/skills/pytest-oop-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Pytest Oop Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Pytest Oop Patterns?

As many as you like. As long as a model supports skills, you can use Pytest Oop Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Pytest Oop Patterns AI skill free?

It is published on GitHub by manikosto. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇