Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

testing-patterns

БесплатноБез исполняемых скриптовНе проверен

How to write robust Frappe tests — FrappeTestCase, factories, mocking frappe.sendmail / external HTTP, permission tests, change_settings, anti-patterns to…

UnityAppSuiteот UnityAppSuite★ 24 звезды на GitHub

Об этом скилле

Frappe Testing Patterns

Reference for writing maintainable tests in Frappe v14+. Focused on the patterns that hold up as your test suite grows past a few dozen tests — factory functions, fixture isolation, mocking, and the anti-patterns that cause flaky failures in CI.

Which base class

from frappe.tests.utils import FrappeTestCase

Use FrappeTestCase (not unittest.TestCase) for anything that touches Frappe — controllers, APIs, DB. It handles:

  • Per-test transaction rollback (you don't need to clean up created docs in tearDown)
  • frappe.flags.in_test = True (so production code can branch on test mode if needed)
  • Test record loading from test_records.json
  • Permission isolation (resets frappe.session.user between tests)

Use plain unittest.TestCase only for pure-Python helpers with no Frappe touchpoints (string utilities, math, etc.).

File location and naming

my_app/
└── my_module/
    └── doctype/
        └── expense_claim/
            ├── expense_claim.py
            ├── expense_claim.js
            ├── expense_claim.json
            ├── test_expense_claim.py    ← convention
            └── test_records.json        ← optional: seed data for the suite

Frappe discovers tests by walking each app's <module>/doctype/<doctype>/test_*.py. For non-DocType tests (utilities, integrations), put them in my_app/tests/ and Frappe still finds them.

Test methods must start with test_. Helper methods on the test class (factories, common assertions) should not — name them _make_invoice, _assert_balanced, etc.

Test data lifecycle

test_records.json — suite-level fixtures

[
    {
        "doctype": "Customer",
        "customer_name": "_Test Customer Alpha",
        "customer_type": "Company",
        "territory": "_Test Territory"
    },
    {
        "doctype": "Item",
        "item_code": "_Test Item Widget",
        "item_name": "Widget",
        "stock_uom": "Nos"
    }
]

Loaded once per test run, available to every test in the file via frappe.get_doc("Customer", "_Test Customer Alpha"). Use the _Test prefix on names — it's the team convention so test data is visually distinct from production seed data.

test_records.json is loaded with ignore_permissions=True, so it can create docs the test user doesn't normally have access to.

setUp vs setUpClass

class TestExpenseClaim(FrappeTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # Runs ONCE per test class. Use for read-only setup that won't be mutated.
        cls.approver_user = "[email protected]"
        cls.create_approver_if_missing()

    def setUp(self):
        # Runs before EACH test. Use for state that tests will mutate.
        # Don't put expensive setup here.
        frappe.set_user("Administrator")

    def tearDown(self):
        # Often unneeded — FrappeTestCase rolls back the transaction automatically.
        # Use only for things that escape the transaction (file writes, real HTTP).
        pass

Most tests need no setUp or tearDown at all — the per-test rollback handles it.

Factory pattern

For docs that vary per test, write a _make_<thing> helper that takes overrides:

class TestExpenseClaim(FrappeTestCase):
    def _make_expense_claim(self, **overrides):
        defaults = {
            "doctype": "Expense Claim",
            "employee": "_Test Employee Alpha",
            "expenses": [{
                "expense_type": "Travel",
                "amount": 100.0,
                "expense_date": frappe.utils.nowdate(),
            }],
        }
        defaults.update(overrides)
        doc = frappe.get_doc(defaults)
        doc.insert()
        return doc

    def test_total_calculation(self):
        claim = self._make_expense_claim(expenses=[
            {"expense_type": "Travel", "amount": 100.0, "expense_date": frappe.utils.nowdate()},
            {"expense_type": "Food", "amount": 50.0, "expense_date": frappe.utils.nowdate()},
        ])
        self.assertEqual(claim.total_claimed_amount, 150.0)

    def test_default_status(self):
        claim = self._make_expense_claim()
        self.assertEqual(claim.status, "Draft")

Factories should be idempotent on the parts that don't change between tests. The Customer and Item are seed data; only the Expense Claim is created per test.

Permission tests

def test_employee_cannot_approve_own_claim(self):
    # Set the user we're testing as
    frappe.set_user("[email protected]")  # Employee role
    claim = self._make_expense_claim(employee="HR-EMP-Alice")

    # Try the privileged operation
    with self.assertRaises(frappe.PermissionError):
        from frappe.model.workflow import apply_workflow
        apply_workflow(claim, "Approve")

    # Reset before the next test (FrappeTestCase auto-resets, but explicit is safer)
    frappe.set_user("Administrator")

def test_manager_can_approve(self):
    self
Полный SKILL.md на GitHub

Установить testing-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл testing-patterns?

How to write robust Frappe tests — FrappeTestCase, factories, mocking frappe.sendmail / external HTTP, permission tests, change_settings, anti-patterns to avoid. Use when writing or reviewing test_*.py files, designing test fixtures, or thinking about test isolation. The /frappe-test command runs tests; this skill teaches how to write them.

Как установить скилл testing-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл testing-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить testing-patterns с