Token导航 LogoToken导航

Agent Skill · 开发

pytest-test-data-factories(pytest 测试数据工厂)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

pytest-test-data-factories 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 21,271。

总安装 192周安装 8GitHub Stars 1下载 64核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:pytest-test-data-factories(pytest 测试数据工厂)
来源仓库:https://github.com/dawiddutoit/custom-claude
仓库路径:skills/pytest-test-data-factories
安装命令:
npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-test-data-factories
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-test-data-factories

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于自动生成和管理 pytest 测试中的模拟数据和工厂对象。适合创建结构化测试数据,提升测试可读性和复用性。支持与 SQLAlchemy 等 ORM 框架集成,简化数据库测试场景。生成数据时应基于实际业务模型,避免虚构字段或关系。

pytest-test-data-factories 属于开发类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/pytest-test-data-factories

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-test-…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

pytest-test-data-factories 怎么安装?

在终端执行 npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-test-data-facto…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

pytest-test-data-factories 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

pytest-test-data-factories 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

pytest-test-data-factories 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

pytest-test-data-factories 用的人多吗?

公开数据是累计安装 192 次,近一周安装 8 次,下载 64 次,GitHub 1 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

pytest-test-data-factories 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
pytest-test-data-factories

pytest 测试数据工厂 · 本页

1921需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Pytest Test Data Factories

Purpose

Test data factories eliminate duplication and make tests more maintainable. Instead of recreating Order objects with the same fields in every test, factories provide sensible defaults and allow customization only where needed.

Quick Start

Create simple factory functions in conftest.py:

# tests/unit/conftest.py
import pytest
from datetime import datetime
from app.extraction.domain.entities import Order
from app.extraction.domain.value_objects import OrderId, Money, ProductTitle

@pytest.fixture
def create_test_order():
    """Factory fixture for creating test orders with defaults."""
    def _create(
        order_id: str = "order_123",
        customer_name: str = "Test User",
        total: float = 99.99,
    ) -> Order:
        return Order(
            order_id=OrderId(order_id),
            created_at=datetime.now(),
            customer_name=customer_name,
            line_items=[create_test_line_item()],
            total_price=Money.from_float(total),
        )

    return _create

# Usage in tests
def test_order_validation(create_test_order):
    """Use factory with defaults."""
    order = create_test_order()
    assert order.customer_name == "Test User"

def test_order_custom_name(create_test_order):
    """Override specific fields."""
    order = create_test_order(customer_name="Jane Doe")
    assert order.customer_name == "Jane Doe"

Instructions

Step 1: Create Basic Factory Fixtures

# tests/unit/conftest.py
from __future__ import annotations

from datetime import datetime
from decimal import Decimal
from typing import Optional
import pytest

from app.extraction.domain.entities import Order, LineItem
from app.extraction.domain.value_objects import OrderId, ProductId, ProductTitle, Money

@pytest.fixture
def create_test_order():
    """Factory for Order aggregate with sensible defaults."""
    def _create(
        order_id: str = "order_123",
        customer_name: str = "Test User",
        line_items: Optional[list[LineItem]] = None,
        total: Optional[float] = None,
    ) -> Order:
        if line_items is None:
            line_items = [create_test_line_item()]

        # Calculate total from line items if not provided
        if total is None:
            total = sum(
                float(item.price.amount) * item.quantity
                for item in line_items
            )

        return Order(
            order_id=OrderId(order_id),
            created_at=datetime.now(),
            customer_name=customer_name,
            line_items=line_items,
            total_price=Money.from_float(total),
        )

    return _create

@pytest.fixture
def create_test_line_item():
    """Factory for LineItem entity with defaults."""
    def _create(
        product_id: str = "prod_1",
        product_title: str = "Test Product",
        quantity: int = 1,
        price: float = 99.99,
    ) -> LineItem:
        return LineItem(
            product_id=ProductId(product_id),
            product_title=ProductTitle(product_title),
            quantity=quantity,
            price=Money.from_float(price),
        )

    return _create

Step 2: Use Builder Pattern for Complex Objects

class OrderBuilder:
    """Builder for creating complex Order objects."""

    def __init__(self):
        self.order_id = "order_123"
        self.customer_name = "Test User"
        self.line_items: list[LineItem] = []
        self.total: Optional[float] = None

    def with_order_id(self, order_id: str) -> OrderBuilder:
        """Set order ID."""
        self.order_id = order_id
        return self

    def with_customer_name(self, name: str) -> OrderBuilder:
        """Set customer name."""
        self.customer_name = name
        return self

    def with_line_items(self, items: list[LineItem]) -> OrderBuilder:
        """Set line items."""
        self.line_items = items
        return self

    def add_line_item(self, item: LineItem) -> OrderBuilder:
        """Add a single line item."""
        self.line_items.append(item)
        return self

    def with_total(self, total: float) -> OrderBuilder:
        """Set total price."""
        self.total = total
        return self

    def build(self) -> Order:
        """Build the Order object."""
        if not self.line_items:
            self.line_items = [
                LineItem(
                    product_id=ProductId("prod_1"),
                    product_title=ProductTitle("Default Product"),
                    quantity=1,
                    price=Money.from_float(99.99),
                )
            ]

        # Auto-calculate total if not provided
        if self.total is None:
            self.total = sum(
                float(item.price.amount) * item.quantity
                for item in self.line_items
            )

        return Order(
            order_id=OrderId(self.order_id),
            created_at=datetime.now(),
            customer_name=self.customer_name,
            line_items=self.line_items,
            total_price=Money.from_float(self.total),
        )

# Usage
def test_with_builder():
    """Build complex order with fluent API."""
    order = (OrderBuilder()
        .with_customer_name("Jane Doe")
        .add_line_item(LineItem(...))
        .add_line_item(LineItem(...))
        .build())

    assert order.customer_name == "Jane Doe"
    assert len(order.line_items) == 2

Step 3: Create Fixture Factories (Fixture Factories)

@pytest.fixture
def order_factory(create_test_order):
    """Fixture factory that returns the create_test_order factory."""
    return create_test_order

def test_multiple_orders(order_factory):
    """Create multiple different orders easily."""
    order1 = order_factory(order_id="order_1", customer_name="Alice")
    order2 = order_factory(order_id="order_2", customer_name="Bob")
    order3 = order_factory(order_id="order_3", customer_name="Charlie")

    assert order1.order_id.value == "order_1"
    assert order2.order_id.value == "order_2"
    assert order3.order_id.value == "order_3"

Step 4: Parametrize Tests with Factory-Generated Data

import pytest
from decimal import Decimal

# Factory-generated test data
ORDER_TEST_CASES = [
    ("order_1", "Alice", 100.00, 1),
    ("order_2", "Bob", 250.50, 2),
    ("order_3", "Charlie", 999.99, 3),
]

@pytest.mark.parametrize(
    "order_id,customer_name,total,item_count",
    ORDER_TEST_CASES,
    ids=["alice_order", "bob_order", "charlie_order"]
)
def test_order_creation_parametrized(
    create_test_order,
    order_id: str,
    customer_name: str,
    total: float,
    item_count: int,
) -> None:
    """Test multiple orders with different data."""
    order = create_test_order(
        order_id=order_id,
        customer_name=customer_name,
        total=total,
    )

    assert order.order_id.value == order_id
    assert order.customer_name == customer_name
    assert float(order.total_price.amount) == total

Step 5: Create Mock Response Templates

# tests/unit/conftest.py or tests/unit/fixtures/responses.py

@pytest.fixture
def shopify_order_response() -> dict:
    """Mock Shopify API order response."""
    return {
        "id": "12345",
        "created_at": "2024-01-01T10:00:00Z",
        "customer": {"name": "John Doe"},
        "line_items": [
            {
                "product_id": "prod_1",
                "title": "Laptop",
                "quantity": 2,
                "price": "999.99",
            }
        ],
        "total_price": "1999.98",
    }

@pytest.fixture
def kafka_message_template() -> dict:
    """Mock Kafka message format."""
    return {
        "order_id": "12345",
        "created_at": "2024-01-01T10:00:00Z",
        "customer_name": "John Doe",
        "line_items": [
            {
                "product_id": "prod_1",
                "product_title": "Laptop",
                "quantity": 2,
                "price": 999.99,
            }
        ],
        "total_price": 1999.98,
    }

@pytest.fixture
def clickhouse_query_result() -> list[tuple]:
    """Mock ClickHouse query result."""
    return [
        ("Laptop", 100),
        ("Mouse", 50),
        ("Keyboard", 30),
    ]

# Usage in tests
async def test_shopify_gateway(shopify_order_response):
    """Use mock response template."""
    with aioresponses() as mock_http:
        mock_http.get(
            "https://test.myshopify.com/admin/api/2024-01/orders.json",
            payload=shopify_order_response,
        )
        # Test code...

Step 6: Create Realistic Data with Faker

from faker import Faker
import pytest

@pytest.fixture
def faker_instance():
    """Provide faker instance for generating realistic data."""
    return Faker()

@pytest.fixture
def create_realistic_order(faker_instance):
    """Factory creating realistic test orders."""
    def _create(count: int = 1) -> list[Order]:
        orders = []
        for _ in range(count):
            orders.append(Order(
                order_id=OrderId(faker_instance.uuid4()),
                created_at=faker_instance.date_time(),
                customer_name=faker_instance.name(),
                line_items=[
                    LineItem(
                        product_id=ProductId(faker_instance.uuid4()),
                        product_title=ProductTitle(faker_instance.word()),
                        quantity=faker_instance.random_int(1, 10),
                        price=Money.from_float(
                            float(faker_instance.pricetag())
                        ),
                    )
                ],
                total_price=Money.from_float(
                    float(faker_instance.pricetag())
                ),
            ))
        return orders

    return _create

def test_with_realistic_data(create_realistic_order):
    """Create realistic test data."""
    orders = create_realistic_order(count=5)
    assert len(orders) == 5
    assert all(isinstance(order, Order) for order in orders)

Step 7: Create Test Data Inheritance

class BaseOrderFactory:
    """Base factory with common defaults."""

    def __init__(self):
        self.order_id = "order_123"
        self.customer_name = "Test User"

class VIPOrderFactory(BaseOrderFactory):
    """Factory for high-value VIP orders."""

    def __init__(self):
        super().__init__()
        self.customer_name = "VIP Customer"
        self.total = 50000.00

class DiscountedOrderFactory(BaseOrderFactory):
    """Factory for discounted orders."""

    def __init__(self):
        super().__init__()
        self.customer_name = "Discount Customer"
        self.total = 10.00

# Usage
def test_vip_order():
    """Test VIP order type."""
    factory = VIPOrderFactory()
    assert factory.total == 50000.00

def test_discounted_order():
    """Test discounted order type."""
    factory = DiscountedOrderFactory()
    assert factory.total == 10.00

Step 8: Create Domain-Specific Test Data Builders

class ProductRankingFactory:
    """Factory for creating ProductRanking test data."""

    @staticmethod
    def create_default() -> ProductRanking:
        """Create with default values."""
        return ProductRanking(
            title="Test Product",
            rank=Rank(1),
            cnt_bought=100,
        )

    @staticmethod
    def create_list(count: int, start_rank: int = 1) -> list[ProductRanking]:
        """Create multiple rankings."""
        return [
            ProductRanking(
                title=f"Product {i}",
                rank=Rank(i + start_rank),
                cnt_bought=100 - (i * 10),
            )
            for i in range(count)
        ]

# Usage
def test_product_rankings(mock_query_gateway):
    """Use factory to create multiple rankings."""
    rankings = ProductRankingFactory.create_list(count=5)
    mock_query_gateway.query_top_products.return_value = rankings

    assert len(rankings) == 5
    assert rankings[0].rank.value == 1

Examples

Example 1: Complete Factory Setup

# tests/unit/conftest.py

from __future__ import annotations

from datetime import datetime
from typing import Optional
import pytest

from app.extraction.domain.entities import Order, LineItem
from app.extraction.domain.value_objects import OrderId, ProductId, ProductTitle, Money

@pytest.fixture
def create_test_line_item():
    """Factory for test line items."""
    def _create(
        product_id: str = "prod_1",
        title: str = "Test Product",
        quantity: int = 1,
        price: float = 99.99,
    ) -> LineItem:
        return LineItem(
            product_id=ProductId(product_id),
            product_title=ProductTitle(title),
            quantity=quantity,
            price=Money.from_float(price),
        )

    return _create

@pytest.fixture
def create_test_order(create_test_line_item):
    """Factory for test orders."""
    def _create(
        order_id: str = "order_123",
        customer_name: str = "Test User",
        items: Optional[list[LineItem]] = None,
    ) -> Order:
        if items is None:
            items = [create_test_line_item()]

        total = sum(
            float(item.price.amount) * item.quantity for item in items
        )

        return Order(
            order_id=OrderId(order_id),
            created_at=datetime.now(),
            customer_name=customer_name,
            line_items=items,
            total_price=Money.from_float(total),
        )

    return _create

# Usage
def test_order_with_defaults(create_test_order):
    """Create order with all defaults."""
    order = create_test_order()
    assert order.customer_name == "Test User"
    assert len(order.line_items) == 1

def test_order_with_multiple_items(create_test_order, create_test_line_item):
    """Create order with custom line items."""
    items = [
        create_test_line_item(title="Laptop"),
        create_test_line_item(title="Mouse"),
        create_test_line_item(title="Keyboard"),
    ]
    order = create_test_order(items=items)
    assert len(order.line_items) == 3

Example 2: Builder Pattern for Complex DTOs

class CreateOrderRequestBuilder:
    """Builder for CreateOrderRequest DTO."""

    def __init__(self):
        self.data = {
            "customer_name": "Test User",
            "items": [],
            "total": 0.0,
        }

    def with_customer(self, name: str) -> CreateOrderRequestBuilder:
        self.data["customer_name"] = name
        return self

    def with_item(self, title: str, price: float, qty: int = 1) -> CreateOrderRequestBuilder:
        self.data["items"].append({"title": title, "price": price, "qty": qty})
        self.data["total"] += price * qty
        return self

    def build(self) -> dict:
        return self.data

# Usage
def test_create_order_request():
    request = (CreateOrderRequestBuilder()
        .with_customer("Alice")
        .with_item("Laptop", 999.99)
        .with_item("Mouse", 29.99, qty=2)
        .build())

    assert request["customer_name"] == "Alice"
    assert len(request["items"]) == 2
    assert request["total"] == 1059.97

Requirements

  • Python 3.11+
  • pytest >= 7.0
  • Optional: faker >= 15.0 (for realistic data)
  • Domain models in your application

See Also

平台分布

Codex

35.56%
按下载量换算23

Claude

29.73%
按下载量换算19

Cursor

20.24%
按下载量换算13

Gemini CLI

11.12%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills