Token导航 LogoToken导航

Agent Skill · 研究检索

testing-anti-patterns(测试反模式)

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

testing-anti-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,暂无第三方扫描结果,按安装量在研究检索类的 73,675 个 Skill 里排第 5,342。

总安装 26,414周安装 769GitHub Stars 公开资料未说明下载 8,687核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

请帮我安装这个 Agent Skill:testing-anti-patterns(测试反模式)
来源仓库:https://github.com/chunkytortoise/enterprisehub
仓库路径:skills/testing-anti-patterns
安装命令:
npx skills add chunkytortoise/enterprisehub --skill "testing-anti-patterns"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

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

AgentSkills.tonpx skills
npx skills add chunkytortoise/enterprisehub --skill "testing-anti-patterns"

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于辅助测试设计、自动化测试、用例整理和回归验证。适合编写单元测试、端到端测试或根据失败日志定位问题。使用时需确认项目测试框架、运行命令和夹具数据,避免误改真实逻辑。涉及浏览器或外部服务时,应区分本地模拟、测试环境与生产环境。安装前建议核实权限范围和维护状态,确认是否触发联网或文件操作。

来源仓库内路径:skills/testing-anti-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add chunkytortoise/enterprisehub --skill "testing-anti-patterns";命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

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

常见问题

6 条

testing-anti-patterns 怎么安装?

在终端执行 npx skills add chunkytortoise/enterprisehub --skill "testing-anti-patterns"。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

testing-anti-patterns 支持哪些 AI 工具?

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

testing-anti-patterns 需要什么权限?

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

testing-anti-patterns 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

testing-anti-patterns 用的人多吗?

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

testing-anti-patterns 安全吗?

没有查到第三方扫描结果,安全性无法从公开资料判断,安装前请自行审查源码、依赖和命令行为。

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 没有第三方扫描结果,安全性只能靠自己读源码判断。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

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

不太适合

  • 要求有安全扫描结论才肯安装的团队。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

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

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
testing-anti-patterns

测试反模式 · 本页

26,414—需要联网MIT未收录

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

SKILL.md 原文

name
Testing Anti-Patterns
description
This skill should be used when encountering "flaky tests", "test maintenance issues", "slow test suites", "brittle tests", "test code smells", "test debugging problems", or when tests are hard to understand, maintain, or debug.
version
1.0.0

Testing Anti-Patterns: Prevention and Detection

Overview

This skill identifies and prevents common testing anti-patterns that make test suites unreliable, slow, and difficult to maintain. It provides detection strategies and refactoring solutions for healthier test codebases.

When to Use This Skill

Use this skill when encountering:

  • Flaky tests that pass/fail inconsistently
  • Slow test suites that take too long to run
  • Brittle tests that break on minor code changes
  • Hard-to-debug test failures
  • Test maintenance nightmares
  • Test code duplication and complexity
  • Poor test organization and naming

Common Anti-Patterns and Solutions

1. The Mystery Guest Anti-Pattern

Problem: Tests depend on external data that's not visible in the test.

# ❌ BAD: Mystery Guest
def test_user_login():
    """What user data exists? What are the credentials?"""
    user = User.objects.get(email=" [email protected] ")  # Where did this come from?
    response = client.post('/login', {
        'email': user.email,
        'password': 'secret123'  # How do we know this password?
    })
    assert response.status_code == 200

# ✅ GOOD: Explicit setup
def test_user_login():
    """Clear test with explicit data creation."""
    # Arrange: Create test data explicitly
    user = User.objects.create_user(
        email=" [email protected] ",
        password="secret123",
        first_name="Test",
        last_name="User"
    )

    # Act: Perform the action
    response = client.post('/login', {
        'email': user.email,
        'password': 'secret123'
    })

    # Assert: Verify the result
    assert response.status_code == 200
    assert response.json()['user_id'] == user.id

2. The Slow Poke Anti-Pattern

Problem: Tests take unnecessarily long to run.

# ❌ BAD: Slow Poke
import time

def test_api_response():
    """This test is unnecessarily slow."""
    time.sleep(5)  # Why?
    response = api_client.get('/slow-endpoint')
    time.sleep(2)  # More unnecessary waiting
    assert response.status_code == 200

# ✅ GOOD: Fast and focused
def test_api_response_fast():
    """Fast test with mocked delays."""
    with patch('slow_service.time_consuming_operation') as mock_op:
        mock_op.return_value = "mocked_result"

        response = api_client.get('/fast-endpoint')
        assert response.status_code == 200

        # Verify the operation was called correctly
        mock_op.assert_called_once()

3. The Eager Test Anti-Pattern

Problem: One test tries to verify too many things.

# ❌ BAD: Eager Test
def test_user_management_everything():
    """This test does too much."""
    # Create user
    user = create_user(" [email protected] ")
    assert user.id is not None

    # Update user
    user.update(first_name="Updated")
    assert user.first_name == "Updated"

    # User permissions
    assign_permission(user, "read")
    assert user.has_permission("read")

    # User posts
    post = create_post(user, "Test post")
    assert post.author == user

    # Delete user
    user.delete()
    assert User.objects.filter(id=user.id).count() == 0

    # This test is hard to debug when it fails!

# ✅ GOOD: Focused tests
def test_user_creation():
    """Test only user creation."""
    user = create_user(" [email protected] ")
    assert user.id is not None
    assert user.email == " [email protected] "

def test_user_update():
    """Test only user updates."""
    user = create_user(" [email protected] ")
    user.update(first_name="Updated")
    assert user.first_name == "Updated"

def test_user_permissions():
    """Test only permission assignment."""
    user = create_user(" [email protected] ")
    assign_permission(user, "read")
    assert user.has_permission("read")

4. The Fragile Fixture Anti-Pattern

Problem: Fixtures that break easily and affect multiple tests.

# ❌ BAD: Fragile Fixture
@pytest.fixture(scope="session")  # Dangerous: shared state
def database_with_data():
    """This fixture is fragile and affects all tests."""
    db.create_all()

    # Create a bunch of interconnected data
    user1 = User.objects.create(email=" [email protected] ")
    user2 = User.objects.create(email=" [email protected] ")

    post1 = Post.objects.create(author=user1, title="Post 1")
    post2 = Post.objects.create(author=user2, title="Post 2")

    # Any test that modifies this data breaks other tests!
    yield

    db.drop_all()

# ✅ GOOD: Isolated fixtures
@pytest.fixture
def clean_database():
    """Clean database for each test."""
    db.create_all()
    yield
    db.drop_all()

@pytest.fixture
def sample_user(clean_database):
    """Create a fresh user for each test."""
    return User.objects.create(
        email=" [email protected] ",
        first_name="Test",
        last_name="User"
    )

@pytest.fixture
def sample_post(sample_user):
    """Create a fresh post for each test."""
    return Post.objects.create(
        author=sample_user,
        title="Test Post",
        content="Test content"
    )

5. The Assertion Roulette Anti-Pattern

Problem: Multiple assertions without clear failure messages.

# ❌ BAD: Assertion Roulette
def test_user_api_response():
    """Which assertion failed? Who knows!"""
    response = api_client.get('/users/1')
    data = response.json()

    assert response.status_code == 200
    assert data['id'] == 1
    assert data['email'] == ' [email protected] '
    assert data['first_name'] == 'Test'
    assert data['last_name'] == 'User'
    assert data['is_active'] is True
    assert data['created_at'] is not None
    # If any of these fail, we don't know which or why

# ✅ GOOD: Clear assertions with messages
def test_user_api_response_clear():
    """Each assertion has a clear purpose and message."""
    response = api_client.get('/users/1')

    assert response.status_code == 200, f"API request failed: {response.text}"

    data = response.json()
    assert data['id'] == 1, f"Wrong user ID: expected 1, got {data.get('id')}"
    assert data['email'] == ' [email protected] ', f"Wrong email: {data.get('email')}"
    assert data['first_name'] == 'Test', f"Wrong first name: {data.get('first_name')}"
    assert data['last_name'] == 'User', f"Wrong last name: {data.get('last_name')}"
    assert data['is_active'] is True, f"User should be active: {data.get('is_active')}"

    # Or use a helper for complex object validation
    assert_user_data_valid(data, expected_id=1, expected_email=' [email protected] ')

def assert_user_data_valid(data, expected_id, expected_email):
    """Helper for user data validation with detailed error messages."""
    errors = []

    if data.get('id') != expected_id:
        errors.append(f"ID mismatch: expected {expected_id}, got {data.get('id')}")

    if data.get('email') != expected_email:
        errors.append(f"Email mismatch: expected {expected_email}, got {data.get('email')}")

    if not data.get('created_at'):
        errors.append("Missing created_at field")

    if errors:
        pytest.fail(f"User data validation failed:\n" + "\n".join(errors))

6. The Test Code Duplication Anti-Pattern

Problem: Copy-paste test code that's hard to maintain.

# ❌ BAD: Test Code Duplication
def test_admin_can_create_post():
    admin = User.objects.create(email=" [email protected] ", role="admin")
    auth_token = generate_token(admin)
    headers = {"Authorization": f"Bearer {auth_token}"}

    response = client.post('/posts', {
        'title': 'Admin Post',
        'content': 'Admin content'
    }, headers=headers)

    assert response.status_code == 201

def test_admin_can_update_post():
    admin = User.objects.create(email=" [email protected] ", role="admin")
    auth_token = generate_token(admin)
    headers = {"Authorization": f"Bearer {auth_token}"}

    post = Post.objects.create(title="Test", content="Test", author=admin)

    response = client.put(f'/posts/{post.id}', {
        'title': 'Updated Post',
        'content': 'Updated content'
    }, headers=headers)

    assert response.status_code == 200

def test_admin_can_delete_post():
    admin = User.objects.create(email=" [email protected] ", role="admin")
    auth_token = generate_token(admin)
    headers = {"Authorization": f"Bearer {auth_token}"}

    post = Post.objects.create(title="Test", content="Test", author=admin)

    response = client.delete(f'/posts/{post.id}', headers=headers)

    assert response.status_code == 204

# ✅ GOOD: DRY test code with helpers
class TestPostAPI:
    @pytest.fixture
    def admin_user(self):
        """Create admin user for tests."""
        return User.objects.create(email=" [email protected] ", role="admin")

    @pytest.fixture
    def auth_headers(self, admin_user):
        """Create authenticated headers."""
        token = generate_token(admin_user)
        return {"Authorization": f"Bearer {token}"}

    @pytest.fixture
    def sample_post(self, admin_user):
        """Create a sample post for tests."""
        return Post.objects.create(
            title="Test Post",
            content="Test content",
            author=admin_user
        )

    def test_admin_can_create_post(self, auth_headers):
        """Test admin post creation."""
        response = client.post('/posts', {
            'title': 'Admin Post',
            'content': 'Admin content'
        }, headers=auth_headers)

        assert response.status_code == 201

    def test_admin_can_update_post(self, auth_headers, sample_post):
        """Test admin post update."""
        response = client.put(f'/posts/{sample_post.id}', {
            'title': 'Updated Post',
            'content': 'Updated content'
        }, headers=auth_headers)

        assert response.status_code == 200

    def test_admin_can_delete_post(self, auth_headers, sample_post):
        """Test admin post deletion."""
        response = client.delete(f'/posts/{sample_post.id}', headers=auth_headers)
        assert response.status_code == 204

7. The Secret Dependency Anti-Pattern

Problem: Tests that depend on execution order or hidden state.

# ❌ BAD: Secret Dependencies
class TestUserWorkflow:
    # These tests secretly depend on execution order!
    def test_01_create_user(self):
        """Must run first!"""
        self.user = User.objects.create(email=" [email protected] ")
        assert self.user.id is not None

    def test_02_update_user(self):
        """Depends on test_01_create_user!"""
        self.user.update(first_name="Updated")
        assert self.user.first_name == "Updated"

    def test_03_delete_user(self):
        """Depends on previous tests!"""
        self.user.delete()
        assert User.objects.filter(id=self.user.id).count() == 0

# ✅ GOOD: Independent tests
class TestUserWorkflow:
    def test_user_creation(self):
        """Independent test for user creation."""
        user = User.objects.create(email=" [email protected] ")
        assert user.id is not None
        assert user.email == " [email protected] "

    def test_user_update(self):
        """Independent test for user update."""
        # Arrange: Create necessary data
        user = User.objects.create(email=" [email protected] ")

        # Act: Perform update
        user.update(first_name="Updated")

        # Assert: Verify result
        assert user.first_name == "Updated"

    def test_user_deletion(self):
        """Independent test for user deletion."""
        # Arrange: Create user to delete
        user = User.objects.create(email=" [email protected] ")
        user_id = user.id

        # Act: Delete user
        user.delete()

        # Assert: Verify deletion
        assert User.objects.filter(id=user_id).count() == 0

Anti-Pattern Detection Tools

1. Test Smell Detector

"""
Tool to detect common test anti-patterns in the codebase.
"""

import ast
import os
from pathlib import Path
from typing import List, Dict, Any
from dataclasses import dataclass


@dataclass
class TestSmell:
    """Represents a detected test anti-pattern."""
    file_path: str
    line_number: int
    smell_type: str
    description: str
    severity: str  # 'low', 'medium', 'high'
    suggestion: str


class TestSmellDetector:
    """Detects common anti-patterns in test files."""

    def __init__(self):
        self.smells: List[TestSmell] = []

    def analyze_test_file(self, file_path: Path) -> List[TestSmell]:
        """Analyze a test file for anti-patterns."""
        self.smells = []

        with open(file_path, 'r') as f:
            content = f.read()

        tree = ast.parse(content)
        self._analyze_ast(tree, str(file_path))

        return self.smells

    def _analyze_ast(self, tree: ast.AST, file_path: str):
        """Analyze AST for test smells."""
        for node in ast.walk(tree):
            self._check_long_test_methods(node, file_path)
            self._check_mystery_guest(node, file_path)
            self._check_assertion_roulette(node, file_path)
            self._check_slow_poke(node, file_path)
            self._check_fragile_fixture(node, file_path)

    def _check_long_test_methods(self, node: ast.AST, file_path: str):
        """Detect overly long test methods (Eager Test)."""
        if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
            # Count lines of code (excluding comments and docstrings)
            loc = len([n for n in ast.walk(node) if isinstance(n, ast.stmt)])

            if loc > 15:  # Threshold for "too long"
                self.smells.append(TestSmell(
                    file_path=file_path,
                    line_number=node.lineno,
                    smell_type="Eager Test",
                    description=f"Test method '{node.name}' is too long ({loc} statements)",
                    severity="medium",
                    suggestion="Break this test into smaller, focused tests"
                ))

    def _check_mystery_guest(self, node: ast.AST, file_path: str):
        """Detect Mystery Guest pattern."""
        if isinstance(node, ast.Call):
            # Look for database queries without clear setup
            if (hasattr(node.func, 'attr') and
                node.func.attr in ['get', 'filter', 'first'] and
                hasattr(node.func.value, 'attr') and
                node.func.value.attr == 'objects'):

                # Check if this is in a test method
                parent = node
                while parent and not (isinstance(parent, ast.FunctionDef) and
                                    parent.name.startswith('test_')):
                    parent = getattr(parent, 'parent', None)

                if parent:
                    self.smells.append(TestSmell(
                        file_path=file_path,
                        line_number=node.lineno,
                        smell_type="Mystery Guest",
                        description="Database query in test without explicit setup",
                        severity="medium",
                        suggestion="Create test data explicitly in the test or use fixtures"
                    ))

    def _check_assertion_roulette(self, node: ast.AST, file_path: str):
        """Detect Assertion Roulette pattern."""
        if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
            # Count assert statements
            assert_count = len([n for n in ast.walk(node)
                              if isinstance(n, ast.Assert)])

            if assert_count > 5:
                self.smells.append(TestSmell(
                    file_path=file_path,
                    line_number=node.lineno,
                    smell_type="Assertion Roulette",
                    description=f"Test has {assert_count} assertions without clear messages",
                    severity="medium",
                    suggestion="Add descriptive messages to assertions or split into multiple tests"
                ))

    def _check_slow_poke(self, node: ast.AST, file_path: str):
        """Detect Slow Poke pattern."""
        if isinstance(node, ast.Call):
            # Look for sleep calls in tests
            if (hasattr(node.func, 'attr') and node.func.attr == 'sleep' or
                isinstance(node.func, ast.Name) and node.func.id == 'sleep'):

                self.smells.append(TestSmell(
                    file_path=file_path,
                    line_number=node.lineno,
                    smell_type="Slow Poke",
                    description="Test uses sleep() - potential timing issue",
                    severity="high",
                    suggestion="Replace sleep with condition waiting or use mocks"
                ))

    def _check_fragile_fixture(self, node: ast.AST, file_path: str):
        """Detect Fragile Fixture pattern."""
        if (isinstance(node, ast.FunctionDef) and
            any(d.id == 'pytest.fixture' for d in node.decorator_list
                if hasattr(d, 'id'))):

            # Look for session-scoped fixtures
            for decorator in node.decorator_list:
                if (isinstance(decorator, ast.Call) and
                    hasattr(decorator.func, 'attr') and
                    decorator.func.attr == 'fixture'):

                    for keyword in decorator.keywords:
                        if (keyword.arg == 'scope' and
                            isinstance(keyword.value, ast.Str) and
                            keyword.value.s == 'session'):

                            self.smells.append(TestSmell(
                                file_path=file_path,
                                line_number=node.lineno,
                                smell_type="Fragile Fixture",
                                description="Session-scoped fixture can cause test interdependencies",
                                severity="medium",
                                suggestion="Consider using function-scoped fixtures for better isolation"
                            ))

    def generate_report(self, test_directory: Path) -> str:
        """Generate a comprehensive report of test smells."""
        all_smells = []

        # Analyze all test files
        for test_file in test_directory.rglob("test_*.py"):
            smells = self.analyze_test_file(test_file)
            all_smells.extend(smells)

        # Group by smell type
        smell_groups = {}
        for smell in all_smells:
            smell_type = smell.smell_type
            if smell_type not in smell_groups:
                smell_groups[smell_type] = []
            smell_groups[smell_type].append(smell)

        # Generate report
        report = "# Test Anti-Pattern Detection Report\n\n"
        report += f"Total smells detected: {len(all_smells)}\n\n"

        for smell_type, smells in smell_groups.items():
            report += f"## {smell_type} ({len(smells)} occurrences)\n\n"

            for smell in smells:
                report += f"- **{smell.file_path}:{smell.line_number}** - {smell.description}\n"
                report += f"  *Suggestion: {smell.suggestion}*\n\n"

        return report


# Usage example:
def check_project_test_smells():
    """Check the entire project for test anti-patterns."""
    detector = TestSmellDetector()
    test_dir = Path("tests")

    report = detector.generate_report(test_dir)

    with open("test_smell_report.md", "w") as f:
        f.write(report)

    print("Test smell analysis complete. See test_smell_report.md")

2. Test Performance Analyzer

"""
Tool to analyze test suite performance and identify slow tests.
"""

import pytest
import time
import json
from pathlib import Path
from typing import Dict, List
from dataclasses import dataclass, asdict


@dataclass
class TestMetrics:
    """Metrics for a single test."""
    name: str
    duration: float
    status: str  # 'PASSED', 'FAILED', 'SKIPPED'
    file_path: str
    line_number: int


class TestPerformanceAnalyzer:
    """Analyzes test suite performance."""

    def __init__(self):
        self.test_metrics: List[TestMetrics] = []

    def pytest_runtest_protocol(self, item, nextitem):
        """Pytest hook to collect test metrics."""
        start_time = time.time()

        # Run the test
        result = yield

        end_time = time.time()
        duration = end_time - start_time

        # Collect metrics
        metrics = TestMetrics(
            name=item.name,
            duration=duration,
            status=result.outcome if hasattr(result, 'outcome') else 'UNKNOWN',
            file_path=str(item.fspath),
            line_number=item.function.__code__.co_firstlineno
        )

        self.test_metrics.append(metrics)

    def generate_performance_report(self) -> Dict:
        """Generate detailed performance analysis."""
        if not self.test_metrics:
            return {"error": "No test metrics collected"}

        total_duration = sum(m.duration for m in self.test_metrics)
        avg_duration = total_duration / len(self.test_metrics)

        # Find slow tests (>2x average duration)
        slow_threshold = avg_duration * 2
        slow_tests = [m for m in self.test_metrics if m.duration > slow_threshold]

        # Group by file
        by_file = {}
        for metric in self.test_metrics:
            file_path = metric.file_path
            if file_path not in by_file:
                by_file[file_path] = []
            by_file[file_path].append(metric)

        # Find slowest files
        file_durations = {
            path: sum(m.duration for m in metrics)
            for path, metrics in by_file.items()
        }

        slowest_files = sorted(file_durations.items(), key=lambda x: x[1], reverse=True)[:10]

        return {
            "summary": {
                "total_tests": len(self.test_metrics),
                "total_duration": round(total_duration, 2),
                "average_duration": round(avg_duration, 2),
                "slow_test_count": len(slow_tests),
                "slow_test_threshold": round(slow_threshold, 2)
            },
            "slow_tests": [
                {
                    "name": m.name,
                    "duration": round(m.duration, 2),
                    "file": m.file_path,
                    "line": m.line_number
                }
                for m in sorted(slow_tests, key=lambda x: x.duration, reverse=True)[:20]
            ],
            "slowest_files": [
                {
                    "file": path,
                    "duration": round(duration, 2),
                    "test_count": len(by_file[path])
                }
                for path, duration in slowest_files
            ]
        }

    def save_metrics(self, output_path: Path):
        """Save collected metrics to JSON file."""
        data = {
            "metrics": [asdict(m) for m in self.test_metrics],
            "report": self.generate_performance_report()
        }

        with open(output_path, 'w') as f:
            json.dump(data, f, indent=2)

# pytest plugin configuration
def pytest_configure(config):
    """Configure the performance analyzer plugin."""
    config.analyzer = TestPerformanceAnalyzer()
    config.pluginmanager.register(config.analyzer, "performance_analyzer")

def pytest_unconfigure(config):
    """Save metrics when tests complete."""
    if hasattr(config, 'analyzer'):
        config.analyzer.save_metrics(Path("test_performance_metrics.json"))
        print("Test performance metrics saved to test_performance_metrics.json")

Project-Specific Patterns for EnterpriseHub

For GHL Real Estate AI Components

# ✅ Good patterns for Streamlit component testing
class TestStreamlitComponents:
    """Test patterns for Streamlit components."""

    @pytest.fixture
    def mock_streamlit_session(self):
        """Mock Streamlit session state."""
        with patch('streamlit.session_state') as mock_session:
            mock_session._state = {}
            yield mock_session

    def test_property_matcher_component(self, mock_streamlit_session):
        """Test property matcher with proper mocking."""
        from components.property_matcher_ai import PropertyMatcherComponent

        # Arrange: Set up component with test data
        component = PropertyMatcherComponent()
        test_preferences = {
            "budget_max": 500000,
            "bedrooms": 3,
            "location": "Rancho Cucamonga, CA"
        }

        # Act: Render component with test data
        with patch('streamlit.selectbox') as mock_selectbox:
            mock_selectbox.return_value = "Rancho Cucamonga, CA"

            result = component.render_preferences_form()

        # Assert: Verify component behavior
        assert result is not None
        mock_selectbox.assert_called_once()

    def test_ai_training_sandbox_isolation(self):
        """Test AI training with proper isolation."""
        from components.ai_training_sandbox import AITrainingSandbox

        # Arrange: Create isolated training environment
        with patch('services.ai_service.AIService') as mock_ai_service:
            mock_ai_service.return_value.train_model.return_value = {
                "accuracy": 0.95,
                "loss": 0.05
            }

            sandbox = AITrainingSandbox()

            # Act: Train model with test data
            result = sandbox.train_with_sample_data()

            # Assert: Verify training results
            assert result["accuracy"] > 0.9
            mock_ai_service.return_value.train_model.assert_called_once()

Best Practices Summary

  1. Explicit Test Data: Create all test data explicitly within tests
  2. Independent Tests: Each test should run independently
  3. Clear Assertions: Use descriptive assertion messages
  4. Fast Tests: Mock external dependencies and avoid unnecessary delays
  5. Focused Tests: Test one concept per test method
  6. Clean Fixtures: Use function-scoped fixtures when possible
  7. DRY Principles: Extract common test code into reusable helpers

Integration with Other Skills

This skill enhances:

  • test-driven-development: By preventing common TDD pitfalls
  • verification-before-completion: By ensuring test quality before completion
  • systematic-debugging: By making test failures easier to debug

Use the detection tools regularly to maintain test suite health and prevent anti-pattern accumulation.

平台分布

windsurf

25.61%
按下载量换算2,225

OpenCode

24.19%
按下载量换算2,101

Codex

18.23%
按下载量换算1,584

Claude Code

12.41%
按下载量换算1,078

Antigravity

8.13%
按下载量换算706

Gemini CLI

3.04%
按下载量换算264

安全审计

暂无安全审计结果可展示。

权限和风险

需要联网

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

安装前确认

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

继续浏览同类 Skills