frappe-testing-unit

用于编写与运行 Frappe 的单元测试和集成测试。面向创建测试夹具、选择正确的测试基类(UnitTestCase、IntegrationTestCase)、使用 frappe.tests.utils、遵循 test_*.py 命名规范、运行 bench run-tests 及其参数,并防止因夹具缺失、测试隔离不当或基类错误导致的测试不稳定,提供写测与运行测试的要点与关键词参考。

仓库最近推送
GitHub Stars
211
Forks
61
Issues / PRs
4

安装方式

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

用 AI 助手安装

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

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

来源与配置

github.com

配置方式待核实

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

安装实测待补充

用于编写与运行 Frappe 的单元测试和集成测试。面向创建测试夹具、选择正确的测试基类(UnitTestCase、IntegrationTestCase)、使用 frappe.tests.utils、遵循 test_*.py 命名规范、运行 bench run-tests 及其参数,并防止因夹具缺失、测试隔离不当或基类错误导致的测试不稳定,提供写测与运行测试的要点与关键词参考。

0 下载

介绍来源: third_party · Impertio-Studio · 2.0 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: frappe-testing-unit
description: >
  Use when writing unit tests, integration tests, creating test fixtures, or running tests with bench run-tests.
  Prevents flaky tests from missing fixtures, incorrect test isolation, and wrong test base classes.
  Covers frappe.tests.utils, IntegrationTestCase, UnitTestCase, test fixtures, bench run-tests flags, test naming conventions.
  Keywords: unit test, integration test, IntegrationTestCase, fixtures, bench run-tests, frappe.tests, test_*.py, how to write test, test fixtures, run tests, test fails, bench run-tests example..
license: MIT
compatibility: "Claude Code, Claude.ai Projects, Claude API. Frappe v14-v16."
metadata:
  author: OpenAEC-Foundation
  version: "2.0"

Unit & Integration Testing

Quick Reference

Task Command / Class
Run all tests bench --site test_site run-tests
Run tests for app bench --site test_site run-tests --app myapp
Run tests for doctype bench --site test_site run-tests --doctype "Sales Order"
Run single test method bench --site test_site run-tests --doctype "Sales Order" --test test_submit
Run tests for module bench --site test_site run-tests --module "myapp.mymodule.doctype.mydt.test_mydt"
Run with profiler bench --site test_site run-tests --doctype "Task" --profile
Run with failfast bench --site test_site run-tests --failfast
Generate JUnit XML bench --site test_site run-tests --junit-xml-output /path/report.xml
Skip fixture loading bench --site test_site run-tests --skip-test-records --skip-before-tests
Base class (v14) from frappe.tests.utils import FrappeTestCase
Unit test class (v15+) from frappe.tests.classes import UnitTestCase
Integration test class (v15+) from frappe.tests.classes import IntegrationTestCase

Decision Tree: Which Test Base Class?

Need to test a function or method in isolation?
├─ YES → Does it require database access?
│   ├─ NO → UnitTestCase (v15+) or FrappeTestCase (v14)
│   └─ YES → IntegrationTestCase (v15+) or FrappeTestCase (v14)
└─ NO → Need to test document lifecycle (create/submit/cancel)?
    ├─ YES → IntegrationTestCase (v15+) or FrappeTestCase (v14)
    └─ NO → Need to test permissions or user context?
        ├─ YES → IntegrationTestCase (v15+) or FrappeTestCase (v14)
        └─ NO → UnitTestCase (v15+) or FrappeTestCase (v14)

Version note: In v14, FrappeTestCase is the ONLY base class. In v15+, it still works (deprecated wrapper) but ALWAYS prefer UnitTestCase or IntegrationTestCase for new code.

Test Base Classes

FrappeTestCase (v14: still works in v15+ as compatibility wrapper)

from frappe.tests.utils import FrappeTestCase

class TestMyDoctype(FrappeTestCase):
    def test_something(self):
        doc = frappe.get_doc({"doctype": "My Doctype", "field": "value"})
        doc.insert()
        self.assertEqual(doc.field, "value")

Behavior: Resets frappe.local.flags after each test. Database transactions start before each test and rollback afterward. ALWAYS call super().setUpClass() if you override setUpClass.

UnitTestCase (v15+): No Database Access

from frappe.tests.classes import UnitTestCase

class TestMyUtils(UnitTestCase):
    def test_calculation(self):
        result = my_calculation(10, 20)
        self.assertEqual(result, 30)

    def test_html_output(self):
        html = generate_html()
        self.assertEqual(self.normalize_html(html), self.normalize_html(expected))

Behavior: Sets frappe.set_user("Administrator") in setUpClass. Auto-detects doctype from module path. Provides normalize_html(), normalize_sql(), assertDocumentEqual(), assertQueryEqual(), assertSequenceSubset().

IntegrationTestCase (v15+): Full Database Access

from frappe.tests.classes import IntegrationTestCase

class TestSalesOrder(IntegrationTestCase):
    def test_submit_order(self):
        so = frappe.get_doc({
            "doctype": "Sales Order",
            "customer": "_Test Customer",
            "items": [{"item_code": "_Test Item", "qty": 1, "rate": 100}]
        }).insert()
        so.submit()
        self.assertEqual(so.docstatus, 1)

Behavior: Extends UnitTestCase. Calls frappe.init() and sets up site connection. Loads test record dependencies via make_test_records(). Provides primary_connection() and secondary_connection() context managers. maxDiff = 10_000.

Test File Structure

ALWAYS place test files in the doctype directory following this naming convention:

myapp/
└── mymodule/
    └── doctype/
        └── my_doctype/
            ├── my_doctype.py          # DocType controller
            ├── my_doctype.json        # DocType definition
            ├── test_my_doctype.py     # Test file (MUST start with test_)
            └── test_records.json      # Optional: test fixtures

Rules:

  • ALWAYS prefix test files with test_ — the test runner ignores files without this prefix
  • ALWAYS use test_{doctype_in_snake_case}.py for doctype tests
  • NEVER place test files outside the doctype directory for doctype-specific tests
  • Non-doctype tests can live in any module, but MUST follow the test_*.py naming

Test Fixtures

Method 1: test_records.json (Static Fixtures)

Create a test_records.json file in the doctype directory:

[
    {
        "doctype": "My Doctype",
        "field1": "_Test Value 1",
        "field2": 100
    },
    {
        "doctype": "My Doctype",
        "field1": "_Test Value 2",
        "field2": 200
    }
]

Rules:

  • ALWAYS prefix test data values with _Test to distinguish from production data
  • The test runner auto-loads these before running tests for the doctype
  • Link field dependencies are resolved automatically — the runner builds records for linked DocTypes first

Method 2: _test_records List (In-Module Fixtures)

_test_records = [
    {"doctype": "My Doctype", "field1": "_Test Value 1"},
    {"doctype": "My Doctype", "field1": "_Test Value 2"},
]

Method 3: Programmatic Fixtures (Recommended for Complex Data)

def create_test_data():
    if frappe.flags.test_data_created:
        return
    frappe.set_user("Administrator")
    frappe.get_doc({
        "doctype": "My Doctype",
        "field1": "_Test Value",
    }).insert()
    frappe.flags.test_data_created = True

class TestMyDoctype(IntegrationTestCase):
    def setUp(self):
        create_test_data()

ALWAYS use frappe.flags to prevent duplicate fixture creation across test methods.

Testing Patterns

Testing Document Lifecycle

class TestInvoice(IntegrationTestCase):
    def test_full_lifecycle(self):
        # Create
        doc = frappe.get_doc({"doctype": "Sales Invoice", ...}).insert()
        self.assertEqual(doc.docstatus, 0)  # Draft

        # Submit
        doc.submit()
        self.assertEqual(doc.docstatus, 1)  # Submitted

        # Cancel
        doc.cancel()
        self.assertEqual(doc.docstatus, 2)  # Cancelled

Testing Permissions

class TestPermissions(IntegrationTestCase):
    def test_user_cannot_read_private(self):
        frappe.set_user("test1@example.com")
        doc = frappe.get_doc("Event", {"subject": "_Test Private Event"})
        self.assertFalse(frappe.has_permission("Event", doc=doc))

    def tearDown(self):
        # ALWAYS reset user in tearDown
        frappe.set_user("Administrator")

Testing with User Context (v15+ Context Manager)

class TestAccess(IntegrationTestCase):
    def test_restricted_access(self):
        with self.set_user("test1@example.com"):
            self.assertRaises(
                frappe.PermissionError,
                frappe.get_doc, "Salary Slip", "SAL-001"
            )
        # User automatically restored after context manager exits

Testing Whitelisted Methods

class TestAPI(IntegrationTestCase):
    def test_whitelisted_method(self):
        frappe.set_user("test1@example.com")
        result = frappe.call("myapp.api.get_dashboard_data", filters={})
        self.assertIsInstance(result, dict)
        self.assertIn("total", result)

Mocking External Services

from unittest.mock import patch, MagicMock

class TestIntegration(IntegrationTestCase):
    @patch("myapp.integrations.stripe.requests.post")
    def test_payment_gateway(self, mock_post):
        mock_post.return_value = MagicMock(
            status_code=200,
            json=lambda: {"status": "success", "id": "ch_123"}
        )
        result = process_payment(amount=1000, currency="USD")
        self.assertEqual(result["status"], "success")
        mock_post.assert_called_once()

Testing with Settings Changes

class TestFeature(IntegrationTestCase):
    def test_with_modified_settings(self):
        with self.change_settings("Selling Settings", {"so_required": 1}):
            # Settings temporarily changed
            self.assertRaises(frappe.ValidationError, create_delivery_note)
        # Settings automatically reverted

Testing with Hook Overrides

class TestHooks(IntegrationTestCase):
    def test_custom_hook(self):
        with self.patch_hooks({"on_submit": ["myapp.hooks.custom_on_submit"]}):
            doc = create_and_submit_doc()
            # Verify hook was executed

Context Managers Reference

Context Manager Available On Purpose
set_user(user) UnitTestCase, IntegrationTestCase Temporarily switch user context
change_settings(dt, **kw) UnitTestCase, IntegrationTestCase Temporarily modify settings
patch_hooks(overrides) UnitTestCase, IntegrationTestCase Temporarily override hooks
freeze_time(time) UnitTestCase, IntegrationTestCase Freeze time for deterministic tests
debug_on(*exceptions) UnitTestCase, IntegrationTestCase Drop into debugger on exception
timeout(seconds) Decorator Fail test if it exceeds time limit
enable_safe_exec() IntegrationTestCase Enable server scripts temporarily
switch_site(site) IntegrationTestCase Switch to a different site
assertQueryCount(n) IntegrationTestCase Assert exact SQL query count
assertRedisCallCounts(**kw) IntegrationTestCase Assert Redis command counts
assertRowsRead(n) IntegrationTestCase Assert row-level DB access limits

Database State Management

  • IntegrationTestCase: ALWAYS rolls back database after each test — no cleanup needed
  • UnitTestCase: No database connection — NEVER use frappe.db calls
  • Each test gets a clean state: transactions start in setUp and rollback in tearDown
  • NEVER call frappe.db.commit() in tests — this breaks test isolation
  • Use frappe.flags.in_test to check if code is running under the test runner

Detecting Test Mode

if frappe.flags.in_test:
    # Skip external API calls, emails, etc.
    return mock_response()

NEVER use frappe.flags.in_test to skip validation logic — tests MUST exercise the same code paths as production.

Common Pitfalls

  1. NEVER forget super().setUpClass() — omitting this breaks fixture loading and user setup
  2. NEVER call frappe.db.commit() in tests — this persists data across tests and breaks isolation
  3. ALWAYS reset user in tearDown if you called frappe.set_user() directly (v14 pattern)
  4. ALWAYS prefix test data with _Test — makes cleanup and identification easy
  5. NEVER rely on test execution order — each test MUST be independent
  6. ALWAYS use frappe.flags to guard fixture creation — prevents duplicate inserts

See Also

版本历史

  1. v3.1.1 GitHub ↗
    原版更新说明

    ## What's new Expanded Keywords in all skill descriptions with user-friendly, non-technical discovery terms. Skills are now easier to find when users describe problems in plain language instead of technical terminology. Examples of added terms: - Symptom-based: "app is slow", "nothing shows", "container won't start" - Beginner-friendly: "how do I start", "what is", "getting started" - Error messages: literal error text users would paste - Alternative names: common synonyms and abbreviations No skill content was changed. Only the Keywords line in SKILL.md frontmatter was expanded.

  2. v3.1.0 GitHub ↗
    原版更新说明

    ## What's new - package.json with agents.skills[] manifest for external discovery (60 skills) - agents/openai.yaml for OpenAI Codex - GitHub topic agentskills added - SKILLS_LOG.md added to .gitignore - Em-dashes replaced with colons in 31 SKILL.md section headings Enables discovery via npx skills add, skills.sh, LobeHub, and other platforms.

  3. v3.0.0 GitHub ↗
    原版更新说明

    ## Summary - **60 deterministic skills** for Frappe Framework v14-v16 (up from 53 in v2.0) - **~95% surface area coverage** (up from ~85%) - 7 new skills + 12 existing skills extended with new reference files ## New Skills (7) | Skill | Category | Coverage | |-------|----------|----------| | `frappe-core-translation` | core | i18n, _(), __(), CSV/PO files, string extraction | | `frappe-core-utils` | core | 140+ date, number, string, validation functions | | `frappe-syntax-print` | syntax | Print formats, PDF generation, Letter Head | | `frappe-syntax-query-builder` | syntax | frappe.qb, joins, aggregation, cross-DB | | `frappe-impl-workspace` | impl | Workspace builder, number cards, charts | | `frappe-core-logging` | core | frappe.logger(), Error Log, Sentry integration | | `frappe-core-search` | core | Link search, global search, SQLiteSearch FTS5 | ## Extended Skills (12) 13 new reference files added to existing skills covering: Controls API, Tree View, Portal Generators, Print Format decision tree, Email system, Module/Workspace shipping, complete Document API, custom bench commands, request lifecycle, advanced debugging (VS Code DAP), Frappe Packages, data masking (v16+), and Python type stubs. ## Stats | Category | Count | |----------|:-----:| | syntax/ | 13 | | core/ | 11 | | impl/ | 14 | | errors/ | 7 | | ops/ | 8 | | agents/ | 5 | | testing/ | 2 | | **Total** | **60** | ## Install ```bash git clone https://github.com/OpenAEC-Foundation/Frappe_Claude_Skill_Package.git cp -r Frappe_Claude_Skill_Package/skills/source/* ~/.claude/skills/ ```

  4. v2.0.0 GitHub ↗
    原版更新说明

    ## Frappe Claude Skill Package v2.0.0 Massive upgrade from 28 ERPNext-specific skills to **53 Frappe Framework skills** covering ~85% of the Frappe surface area. ### What's New - **25 new skills** across 3 new categories (ops, testing, agents) - **28 existing skills** fully rewritten with fresh research - **Renamed** from `erpnext-*` to `frappe-*` (all skills are Frappe Framework, not ERPNext-specific) - **7 categories**: syntax (11), core (7), impl (13), errors (7), ops (8), agents (5), testing (2) ### New Categories - **ops/** — Bench CLI, deployment, backup, performance, upgrades, frontend build, cloud - **testing/** — Unit/integration tests, CI/CD with GitHub Actions - **3 new agents** — debugger, migrator, architect ### Key Improvements - All skills verified against official Frappe docs (March 2026) - v16 features documented: `extend_doctype_class`, data masking, type annotations - MIT license (was LGPL-3.0) - Deterministic language throughout (ALWAYS/NEVER) 🤖 Generated with [Claude Code](https://claude.com/claude-code)

  5. v1.1.0 GitHub ↗
    原版更新说明

    V16 compatibility update and documentation improvements. ## Added - USAGE.md with platform-specific guides (Claude.ai, Claude Code, API) - Complete README overhaul with quick start guide ## Changed - All 28 skills updated for ERPNext/Frappe V16 compatibility - Agent Skills now follow standard skill structure - Improved validation: 28/28 skills pass all checks ## Fixed - V16-specific syntax changes in 9 skills - Agent SKILL.md files now under 500 lines

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

2.0

核对来源版本 ↗

质量评测

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

场景价值85/100

亮点

  • 提供 Frappe 单元测试与集成测试的完整实践指南
  • 涵盖测试基类选择决策树、夹具管理、运行命令参数等高频刚需内容
  • 包含大量可复用的代码示例和常见陷阱提醒
触发精准95/100

亮点

  • 关键词覆盖全面且精准(unit test, integration test, IntegrationTestCase, fixtures, bench run-tests)
  • 边界清晰,能有效区分于其他测试相关 Skill
结构规范95/100

待提升项

  • 引用文件缺失 原报告严重程度:轻微

    SKILL.md 中引用了 references/examples.md、references/anti-patterns.md、references/fixtures.md、references/api-reference.md 等文件,但未在 ZIP 包中提供

    改进建议:建议补充引用文件或在文档中移除引用链接

亮点

  • 文档结构清晰,分章节覆盖测试全流程
  • 包含快速参考表格、决策树、代码示例和上下文管理器清单
  • frontmatter 完整,命名规范明确
执行可靠95/100

待提升项

  • description写错位置 原报告严重程度:轻微

    description 在顶层 frontmatter 和 skill_body 内部重复定义

    改进建议:建议仅在顶层 frontmatter 保留 description,移除 skill_body 内的重复定义

亮点

  • 所有命令、类导入、参数均准确对应 Frappe v14-v16 官方实践
  • 提供了完善的异常处理建议和测试隔离最佳实践
  • 不可逆操作(如数据库提交)有明确警告
证据可验 (前四项均值)93/100

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

正文静态检测

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

正文未命中当前规则。

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

权限与使用前检查

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

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

安全评级与访问范围

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

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