跳到正文
cccskills
免费在 GitHub 公开

hasura-tests

Wraps Hasura GraphQL Engine testing patterns: docker-compose test instance, the metadata API for declarative schema/permission setup, x-hasura-role and x-hasura-user-id session headers for role-based permission tests, the v1/graphql endpoint via curl/HTTPie/native HTTP clients, and the role-by-table-by-operation permission-matrix pattern. Use for a metadata-driven Hasura engine where row-level permissions dominate; for a code-first server runtime harness use graphql-yoga-tests (Mercurius in its references) or apollo-server-tests instead, not this skill.

中文简介正在准备中。当前显示原文说明。

testland/qa星标 13(GitHub 13 + cccskills 0)
集成工具GitHubPostgreSQL

实测评分 未实测

查看安装方法

包含的文件(3)

  • SKILL.md10.4 KB
  • .tessl-plugin/plugin.json687 B
  • references/permission-matrix-tests.md1.9 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

hasura-tests

Overview

Per hasura.io/docs/2.0/auth/authorization/quickstart/, Hasura permissions are configured per table, role, and operation (select / insert / update / delete), with row- filter expressions and column-level scopes.

The testable concerns are different from Apollo / Yoga:

  • Permission rules are declarative; tests verify the rule produces the expected filter SQL.
  • Roles + session variables drive everything; tests inject x-hasura-role + custom claims and assert the response shape.
  • Metadata is the source of truth; tests apply a fixture metadata then run queries.

When to use

  • Testing a Hasura-backed API where row-level isolation is the primary concern (composes with cross-tenant-data-leak-tests in the qa-multi-tenancy plugin).
  • Verifying a new role's permission rules.
  • PR review of hasura/metadata/ changes.
  • Regression-testing role transitions (user becomes admin, etc.).

How to use

  1. Bring up the ephemeral test stack (docker compose -f docker-compose.test.yml up -d) with introspection disabled and the console off.
  2. Apply the fixture metadata that declares the permission rules under test, via the /v1/metadata API or hasura metadata apply.
  3. Seed per-test rows so no test depends on another test's data.
  4. Send queries to /v1/graphql with the admin secret plus an x-hasura-role override (and x-hasura-user-id / custom claims) to act as any role.
  5. Assert the response shape: rows are row-filtered to the role, or the failure carries extensions.code = "permission-error" (or affected_rows: 0).
  6. Cover the full role x table x operation matrix from a checked-in fixture, and add one smoke test through the real JWT path.
  7. Tear the stack down with -v and reset metadata between suites.

Authoring

Test instance setup

# docker-compose.test.yml
services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: ${PG_PASSWORD:?set PG_PASSWORD}

  hasura:
    image: hasura/graphql-engine:v2.42.0
    ports: ["8080:8080"]
    depends_on: [postgres]
    environment:
      HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:${PG_PASSWORD}@postgres:5432/postgres
      HASURA_GRAPHQL_ADMIN_SECRET: ${HASURA_GRAPHQL_ADMIN_SECRET:?set HASURA_GRAPHQL_ADMIN_SECRET}
      HASURA_GRAPHQL_DISABLE_INTROSPECTION_PUBLIC_API: "true"  # per graphql-complexity-limit-tester references/introspection.md
      HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
docker compose -f docker-compose.test.yml up -d

Never write the admin secret or DB password into the compose file or a test. Per Compose interpolation, ${VAR} is read from the shell or a git-ignored .env, and ${VAR:?error} stops Compose when it is unset. Every command and test below reads HASURA_GRAPHQL_ADMIN_SECRET from the environment.

Apply metadata for test

Per Hasura docs, the metadata API at /v1/metadata:

curl -X POST http://localhost:8080/v1/metadata \
  -H "x-hasura-admin-secret: $HASURA_GRAPHQL_ADMIN_SECRET" \
  -H "Content-Type: application/json" \
  -d @hasura/metadata-fixture.json

metadata-fixture.json contains the declarative permission rules being tested.

Or via hasura CLI:

hasura migrate apply --endpoint http://localhost:8080 --admin-secret "$HASURA_GRAPHQL_ADMIN_SECRET"
hasura metadata apply --endpoint http://localhost:8080 --admin-secret "$HASURA_GRAPHQL_ADMIN_SECRET"

Role-based permission tests

Tests act as any role via admin secret + x-hasura-role override, and a full per-role x per-table x per-operation audit is generated from a checked-in fixture. Both patterns - the httpx by-role queries and the parametrized matrix - are in references/permission-matrix-tests.md.

Worked example

Scenario: a new user role must see only its own rows in the user table.

  1. In the fixture metadata, give user a select permission on user filtered by id = X-Hasura-User-Id; apply it with hasura metadata apply.
  2. POST { user { id name } } to /v1/graphql with headers x-hasura-admin-secret, x-hasura-role: user, x-hasura-user-id: 3.
  3. Assert status_code == 200 and every returned row has id == 3 - the row filter held.
  4. POST the same query with x-hasura-role: admin (no user-id) and assert len(rows) > 1 - admin is not restricted.

Result: one pair of requests proves the row-filter rule for the restricted role and confirms it does not leak into the admin role.

Running

docker compose -f docker-compose.test.yml up -d
hasura metadata apply --endpoint http://localhost:8080 --admin-secret "$HASURA_GRAPHQL_ADMIN_SECRET"
pytest tests/hasura/
docker compose -f docker-compose.test.yml down -v

Parsing results

Hasura returns standard GraphQL response format:

{
  "data": { "user": [{"id": 3, "name": "alice"}] },
  "errors": [{"message": "user.id: permission has failed", "extensions": {"code": "permission-error"}}]
}

Permission failures use extensions.code = "permission-error". Assertion patterns:

def test_user_cannot_update_other_users_row():
    resp = httpx.post(ENDPOINT, headers={
        "x-hasura-admin-secret": os.environ["HASURA_GRAPHQL_ADMIN_SECRET"],
        "x-hasura-role": "user",
        "x-hasura-user-id": "3",
    }, json={
        "query": "mutation { update_user_by_pk(pk_columns: {id: 4}, _set: {name: \"hacked\"}) { id } }"
    })
    body = resp.json()
    # Either errors out OR returns affected_rows: 0 depending on permission setup
    if "errors" in body:
        assert any(
            "permission" in e["extensions"].get("code", "")
            for e in body["errors"]
        )
    else:
        assert body["data"]["update_user_by_pk"] is None  # row was filtered out

CI integration

jobs:
  hasura-permission-matrix:
    runs-on: ubuntu-latest
    env:
      HASURA_GRAPHQL_ADMIN_SECRET: ${{ secrets.HASURA_ADMIN_SECRET }}
    services:
      postgres:
        image: postgres:16
        env: { POSTGRES_PASSWORD: "${{ secrets.CI_DB_PASSWORD }}" }
        ports: [5432]
      hasura:
        image: hasura/graphql-engine:v2.42.0
        env:
          HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:${{ secrets.CI_DB_PASSWORD }}@postgres:5432/postgres
          HASURA_GRAPHQL_ADMIN_SECRET: ${{ secrets.HASURA_ADMIN_SECRET }}
          HASURA_GRAPHQL_DISABLE_INTROSPECTION_PUBLIC_API: "true"
        ports: [8080]
    steps:
      - uses: actions/checkout@v5
      - run: |
          npm install -g hasura-cli
          hasura migrate apply --endpoint http://localhost:8080 --admin-secret "$HASURA_GRAPHQL_ADMIN_SECRET"
          hasura metadata apply --endpoint http://localhost:8080 --admin-secret "$HASURA_GRAPHQL_ADMIN_SECRET"
      - run: pytest tests/hasura/ --tb=short

Per the GitHub Actions contexts reference, secrets is available in job env and in service-container env, so neither the admin secret nor the DB password appears in the workflow file.

Anti-patterns

Anti-patternWhy it failsFix
Tests run against shared Hasura instancePermission changes leak between testsPer-test or per-suite ephemeral DB + metadata reset
Skipping HASURA_GRAPHQL_DISABLE_INTROSPECTION_PUBLIC_API in CIProduction-config drift; introspection assertions don't holdSet in test docker-compose
Permission tests using admin secret without x-hasura-role overrideTests run as admin -> bypass all permissionsAlways add x-hasura-role
Hardcoded user IDs across testsOne test mutates user 3 -> next test stalePer-test user seeding
Skipping insert / update / delete testsPermission rules differ per operationCover the full matrix
Not testing JWT pathAdmin-secret-override bypasses production auth flowOne smoke test using real JWT against HASURA_GRAPHQL_JWT_SECRET config
Permission matrix in code onlyPR reviewers can't see what changesMatrix as a checked-in YAML / JSON fixture
Tests don't reset metadata between suitesMigration drift between test runshasura metadata clear + reapply in setup

Limitations

  • Doesn't test the auth service. Hasura accepts JWT / webhook / admin-secret claims; verifying the auth-service issues correct claims is separate.
  • Permission rules are SQL-translated. Some rules that look right in metadata may produce slow SQL; performance is a separate test concern (use EXPLAIN queries via Hasura's introspection - admin-only).
  • Action / Remote-schema testing. Hasura's Actions and Remote Schemas delegate to other services; this skill tests the Hasura -> upstream contract, not the upstream itself.
  • Subscription testing requires a long-running connection. Hasura subscriptions use server-sent updates over HTTP/WS; pytest async patterns needed.
  • Event-trigger testing. Hasura's webhook event triggers fire on data changes; test via the Webhook receiver, not Hasura itself.

References

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Builds a CI gate that fails the build on **new** WCAG / a11y violations introduced by a PR while grandfathering pre-existing violations on a per-rule / per-page baseline. Aggregates verdicts from axe-core / pa11y / Lighthouse a11y / WAVE / IBM Equal Access scans. Use when a project has accumulated a11y debt and a strict "zero violations" gate would block every PR - the ratchet pattern lets the team ship while preventing regressions.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Workflow skill that builds an A/B-test validity checklist from an experiment proposal, walking the canonical design-correctness gates - pre-registered OEC/power/guardrails, randomization unit + SRM check, assignment integrity, telemetry, peeking discipline, novelty/primacy, post-experiment SRM re-check - into a per-experiment checklist + sign-off form. Use when launching, auditing, or governing an experiment. For pitfall mechanics (guardrails, peeking) see experiment-results-interpreter's references; to read an already-valid result use experiment-results-interpreter; for per-SDK harness tests use experiment-sdk-testing - this gates DESIGN, not SDK code.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

The single install-flow skill: the reference contract for the PWA install flow (installability gate fields, `beforeinstallprompt` handshake, per-platform paths - Android WebAPK / iOS Share menu / Firefox no-op - and the `display-mode` post-install signal, in references/install-flow-reference.md) plus the build-an-X workflow that emits the Add-to-Home-Screen suite. Walks the four-stage timeline, emitting one test per gate cell per [web.dev/articles/install-criteria][install-criteria], the deferred-prompt → `prompt()` → `userChoice` chain per [web.dev/articles/customize-install][customize-install], the iOS Safari manual-metadata branch (`apple-touch-icon`) per [web.dev/learn/pwa/installation][learn-pwa], and the post-install `(display-mode: standalone)` MQ assertion. Output: a Playwright spec with per-stage cells plus a coverage matrix. Use when a PWA's manifest, icons, or install handler change, when install conversion drops at an unknown stage, or when triaging a flaky install assertion.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Build-an-X workflow that uses an LLM to map existing tests to spec sections - given a spec doc + the test suite, the LLM identifies which tests cover which sections, surfaces uncovered sections (gap), and recommends specific tests to add. Output is a coverage matrix per spec ID. Scope is mapping tests that already exist and naming the gaps, not authoring tests for new acceptance criteria. Use when a spec doc and a test suite both exist but nobody can say which requirements are actually covered - before a release sign-off, an audit, or a decision about where to spend the next round of test effort.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Generates tests from natural-language specs (acceptance criteria, user stories, requirements) using an LLM, with confidence scoring per test case (LLM self-assessment plus heuristics: assertion quality, naming, completeness), batching uncertain cases for human review, and integration with the team's existing test framework. Use when the user asks to generate unit tests from acceptance criteria, convert user stories to test cases, automate test creation from requirements, or augment a spec-driven test suite with AI-generated stubs that are then curated before merge.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Configures Allure Report (test-runner adapter install, `allure-results` directory wiring, `categories.json` for failure classification, `history-trend.json` retention via the copy-history-between-runs pattern), runs the Allure CLI to convert `allure-results` to a static HTML site, and uploads the report as a CI artifact. Use when the team needs richer test reporting than JUnit XML - step-level attachments, per-test history, retry tracking, and severity / epic / feature labeling across framework-agnostic adapters (pytest, Jest, JUnit, TestNG, NUnit, Mocha). As a rich static HTML report generator, it is the open-source alternative to the sunset ExtentReports (JVM/.NET per-test HTML narrative); for hosted cross-run flakiness analytics rather than a static per-run report use currents-integration.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

查看 testland 的全部技能

报告此技能的问题