schemathesis

通过从 OpenAPI 或 GraphQL 模式自动生成测试用例来自动测试 API。适用于对 API 进行模糊测试、发现 REST 或 GraphQL API 的边界情况、验证与模式的合规性、基于规范生成属性测试、查找导致崩溃或 500 错误的问题,或验证 API 契约。可从模式生成大量测试用例以发现手动测试可能遗漏的缺陷。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "schemathesis":https://skillpi.com/zh/skills/deepskill-62f01f11a2e2bcf2a9db5aadf6650597f39baef443cbad21d89c5172abbdce79。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

通过从 OpenAPI 或 GraphQL 模式自动生成测试用例来自动测试 API。适用于对 API 进行模糊测试、发现 REST 或 GraphQL API 的边界情况、验证与模式的合规性、基于规范生成属性测试、查找导致崩溃或 500 错误的问题,或验证 API 契约。可从模式生成大量测试用例以发现手动测试可能遗漏的缺陷。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: schemathesis
description: >-
  Automatically test APIs by generating test cases from OpenAPI/GraphQL schemas.
  Use when tasks involve API fuzzing, finding edge cases in REST or GraphQL APIs,
  testing schema compliance, generating property-based tests from API specs,
  finding crashes and 500 errors, or validating API contracts. Schemathesis
  generates thousands of test cases from your schema and finds bugs that manual
  testing misses.
license: Apache-2.0
compatibility: "Python 3.9+"
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: development
  tags:
    - api-testing
    - fuzzing
    - openapi
    - graphql
    - security

Schemathesis

Overview

Automatically generate and run API tests from OpenAPI and GraphQL schemas. Schemathesis finds bugs by generating thousands of test cases — boundary values, invalid types, malformed payloads, deep nesting — that developers never think to write manually.

Instructions

Installation

pip install schemathesis

# Or with all extras
pip install schemathesis[all]

Quick Start

# Test a live API using its OpenAPI schema
st run https://api.example.com/openapi.json

# Test from a local schema file
st run ./openapi.yaml --base-url http://localhost:8080

# Test a GraphQL API
st run https://api.example.com/graphql

How It Works

Schemathesis reads your API schema (OpenAPI 2.0/3.0/3.1 or GraphQL) and:

  1. Generates test cases — valid and invalid inputs based on parameter types, constraints, and formats
  2. Sends requests — fires thousands of combinations at your API
  3. Checks for failures — 500 errors, schema violations, response timeouts, crashes
  4. Shrinks failures — reduces failing test cases to the minimal reproducible example
  5. Reports results — shows exactly which input caused which failure
Schema → Generator → Request → Response → Checker → Report
         ├── Valid values        ├── Status code OK?
         ├── Boundary values     ├── Response matches schema?
         ├── Invalid types       ├── No 500 errors?
         ├── Null/empty          ├── Response time OK?
         ├── Overflow values     └── No crashes?
         └── Unicode/special chars

CLI Options

# Basic testing
st run https://api.example.com/openapi.json

# Authentication
st run URL --auth user:password                    # Basic auth
st run URL --header "Authorization: Bearer TOKEN"  # Bearer token
st run URL --header "X-API-Key: KEY"               # API key

# Target specific endpoints
st run URL --include-path "/api/users"             # Only test /api/users
st run URL --include-method POST                   # Only test POST endpoints
st run URL --exclude-path "/api/admin"             # Skip admin endpoints

# Control test volume
st run URL --hypothesis-max-examples=500    # Max test cases per endpoint
st run URL --hypothesis-deadline=5000       # Max ms per test case
st run URL --workers 4                      # Parallel workers

# Output
st run URL --report                     # Generate HTML report
st run URL --cassette-path=cassette.yaml  # Save all requests/responses
st run URL --junit-xml=results.xml      # JUnit format for CI

Test Strategies

Negative testing

Schemathesis automatically generates inputs that violate schema constraints:

If schema says: { "type": "integer", "minimum": 1, "maximum": 100 }
Schemathesis tries: 0, -1, -2147483648, 101, 999999999, null, "string", 1.5, []

If schema says: { "type": "string", "format": "email" }
Schemathesis tries: "", "not-an-email", "a@b", null, 12345, very-long-string...

If schema says: { "type": "array", "maxItems": 10 }
Schemathesis tries: [], [1000 items], null, "not-array", nested arrays...

Stateful testing (link-based)

Schemathesis can chain API calls using OpenAPI links:

# Enable stateful testing — creates resources, then tests operations on them
st run URL --stateful=links

# Example flow:
# 1. POST /users → creates user, gets ID
# 2. GET /users/{id} → uses the created ID
# 3. PUT /users/{id} → updates with fuzzed data
# 4. DELETE /users/{id} → cleanup

This catches bugs that only appear with real resource IDs, not random values.

Custom checks

# custom_checks.py
# Add custom validation logic to Schemathesis test runs

import schemathesis

@schemathesis.check
def no_sensitive_data_in_errors(response, case):
    """Ensure error responses don't leak sensitive information.

    Checks that 4xx/5xx responses don't contain stack traces,
    database queries, or internal paths.
    """
    if response.status_code >= 400:
        body = response.text.lower()
        sensitive_patterns = [
            "traceback",
            "stack trace",
            "sql",
            "select * from",
            "/usr/local/",
            "/home/",
            "password",
            "secret",
            "internal server",
        ]
        for pattern in sensitive_patterns:
            assert pattern not in body, (
                f"Sensitive data '{pattern}' found in error response"
            )

@schemathesis.check
def response_time_acceptable(response, case):
    """Ensure no endpoint takes longer than 5 seconds.

    Slow responses might indicate injection vulnerabilities
    (time-based SQL injection) or denial-of-service potential.
    """
    assert response.elapsed.total_seconds() < 5.0, (
        f"Response took {response.elapsed.total_seconds():.1f}s "
        f"(limit: 5s) — possible DoS vector"
    )
# Run with custom checks
st run URL --checks all --hypothesis-max-examples=200

Python API

# test_api.py
# Use Schemathesis in pytest for CI integration

import schemathesis

# Load schema
schema = schemathesis.from_url("https://api.example.com/openapi.json")

# Or from file
schema = schemathesis.from_path("./openapi.yaml", base_url="http://localhost:8080")

# Generate test cases for all endpoints
@schema.parametrize()
def test_api(case):
    """Property-based test generated from OpenAPI schema.

    Schemathesis generates hundreds of test cases per endpoint,
    testing boundary values, invalid types, and edge cases.
    """
    response = case.call()
    case.validate_response(response)  # Check response matches schema

# Target specific endpoint
@schema.parametrize(endpoint="/api/users", method="POST")
def test_create_user(case):
    """Test user creation with generated inputs."""
    response = case.call()
    case.validate_response(response)
    assert response.status_code != 500, f"Server error with input: {case.body}"

CI Integration

# .github/workflows/api-test.yml
name: API Schema Testing
on: [push, pull_request]

jobs:
  schemathesis:
    runs-on: ubuntu-latest
    services:
      api:
        image: your-api:latest
        ports:
          - 8080:8080
    steps:
      - uses: actions/checkout@v4

      - name: Run Schemathesis
        uses: schemathesis/action@v1
        with:
          schema: http://localhost:8080/openapi.json
          args: >-
            --checks all
            --stateful=links
            --hypothesis-max-examples=200
            --junit-xml=results.xml

      - name: Upload results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: api-test-results
          path: results.xml

Security-Focused Testing

For penetration testing, configure Schemathesis to look for security issues:

# Test for injection vulnerabilities
# Schemathesis will try SQL injection, XSS, and command injection payloads
# in string parameters
st run URL \
  --checks all \
  --hypothesis-max-examples=1000 \
  --header "Authorization: Bearer TOKEN" \
  --stateful=links \
  --report

# Common findings:
# - 500 errors on special characters → potential injection
# - Slow responses on certain inputs → time-based injection
# - Different error messages → information disclosure
# - Bypassed validation → missing server-side checks
# - Schema violations in responses → data leakage

Examples

Fuzz a REST API to find crashes

Our REST API has an OpenAPI 3.0 spec at /api/docs/openapi.json. Run Schemathesis against all endpoints with 500 test cases per endpoint. Focus on finding 500 errors, schema violations, and slow responses (>3 seconds). Use stateful testing to chain CRUD operations. Generate an HTML report showing all findings with reproducible curl commands.

Add API fuzzing to CI pipeline

Set up Schemathesis in our GitHub Actions CI to run on every PR. The API starts in Docker (docker-compose up), schema is at localhost:8080/openapi.json. Run with 200 test cases per endpoint, fail the build on any 500 error or schema violation. Output JUnit XML for GitHub's test reporter. Include authentication via Bearer token from GitHub Secrets.

Security-focused API testing

We're doing a security assessment of our payment API. Use Schemathesis to test all endpoints with maximum fuzzing intensity. Check for: SQL injection indicators (500 errors with special chars), information disclosure in error responses, slow queries suggesting time-based injection, and missing input validation. Produce a security findings report with severity ratings.

Guidelines

  • Always test against staging or development environments first — never fuzz a production API without explicit authorization
  • Start with a low --hypothesis-max-examples value (50-100) to validate setup before running full intensity
  • Use --workers carefully — too many parallel workers can overwhelm the target and cause false failures
  • Ensure your OpenAPI/GraphQL schema is up to date — stale schemas produce misleading results
  • Schemathesis finds crashes and violations but does not confirm exploitability — triage 500 errors manually
  • Use --cassette-path to record all requests for reproducibility and audit trails

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • Schemathesis能自动生成大量测试用例,显著提升API测试效率,发现手动测试遗漏的缺陷。
  • 适用于多种API类型(OpenAPI、GraphQL)和场景(模糊测试、边界情况发现、模式合规性测试等)。
触发精准90/100

亮点

  • 触发词精准完整,覆盖多种变体,边界清晰。
  • 提供了具体的CLI和Python API使用示例,便于用户理解和操作。
结构规范90/100

亮点

  • 文档结构清晰,包含多个详细部分,每个部分都有具体的步骤和示例。
  • frontmatter完整,单文件内容详尽但不过长。
执行可靠90/100

亮点

  • 工具来源明确,参数正确,覆盖主要异常。
  • 提供了多种认证方式、测试策略和自定义检查,强调了测试环境的选择和安全性。
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 安装或获取外部依赖

    使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。

    主文档提及 · 第 35, 38 行
  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 83 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • api.example.com
  • localhost

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。