AshGrant.PolicyTest.YamlParser (AshGrant v0.14.1)

Copy Markdown View Source

Parses YAML policy test files and runs them.

YAML provides an alternative format for defining policy tests, useful for:

  • Non-Elixir developers reviewing permissions
  • Generating tests from external tools
  • Documentation purposes

YAML Format

resource: MyApp.Document

actors:
  reader:
    role: reader
  author:
    role: author
    id: "author_001"

tests:
  - name: "reader can read"
    assert_can:
      actor: reader
      action: read

  - name: "reader can read published"
    assert_can:
      actor: reader
      action: read
      record:
        status: published

  - name: "reader cannot read drafts"
    assert_cannot:
      actor: reader
      action: read
      record:
        status: draft

Argument-based scopes

Scopes can reference action arguments via ^arg(:name). To exercise those in a YAML test, supply an arguments: map alongside record::

- name: "manager can update refund in their unit"
  assert_can:
    actor: unit_manager
    action: update
    record:
      author_id: "u1"
    arguments:
      center_id: "center_A"

Usage

# Parse YAML file
{:ok, parsed} = YamlParser.parse_file("policy_tests/document.yaml")

# Run tests from YAML file
{:ok, results} = YamlParser.run_yaml_tests("policy_tests/document.yaml")

Summary

Functions

Parses a YAML policy test file.

Parses a YAML policy test file and raises on error.

Runs tests from a YAML file and returns results.

Types

parsed()

@type parsed() :: %{
  resource: module(),
  actors: %{required(atom()) => map()},
  tests: [parsed_test()]
}

parsed_test()

@type parsed_test() :: %{
  name: String.t(),
  type:
    :assert_can
    | :assert_cannot
    | :assert_fields_visible
    | :assert_fields_hidden,
  actor: atom(),
  action: atom() | nil,
  action_type: atom() | nil,
  record: map() | nil,
  arguments: map(),
  fields: [atom()] | nil
}

Functions

parse_file(path)

@spec parse_file(String.t()) :: {:ok, parsed()} | {:error, term()}

Parses a YAML policy test file.

Returns {:ok, parsed} on success or {:error, reason} on failure.

parse_file!(path)

@spec parse_file!(String.t()) :: parsed()

Parses a YAML policy test file and raises on error.

run_yaml_tests(path)

@spec run_yaml_tests(String.t()) ::
  {:ok, [AshGrant.PolicyTest.Result.t()]} | {:error, term()}

Runs tests from a YAML file and returns results.