provider-test-patterns

hashicorp/agent-skills · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/hashicorp/agent-skills --skill provider-test-patterns
0 commentsdiscussion
summary

Patterns for writing acceptance tests using

  • terraform-plugin-testing
  • with the Plugin Framework.
skill.md

Provider Acceptance Test Patterns

Patterns for writing acceptance tests using terraform-plugin-testing with the Plugin Framework.

Source: HashiCorp Testing Patterns

References (load when needed):

  • references/checks.md — statecheck, plancheck, knownvalue types, tfjsonpath, comparers
  • references/sweepers.md — sweeper setup, TestMain, dependencies
  • references/ephemeral.md — ephemeral resource testing, echoprovider, multi-step patterns

Test Lifecycle

The framework runs each TestStep through: plan → apply → refresh → final plan. If the final plan shows a diff, the test fails (unless ExpectNonEmptyPlan is set). After all steps, destroy runs followed by CheckDestroy. This means every test automatically verifies that configurations apply cleanly and produce no drift — no assertions needed for that.


Test Function Structure

func TestAccExample_basic(t *testing.T) {
    var widget example.Widget
    rName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
    resourceName := "example_widget.test"

    resource.ParallelTest(t, resource.TestCase{
        PreCheck:                 func() { testAccPreCheck(t) },
        ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
        CheckDestroy:             testAccCheckExampleDestroy,
        Steps: []resource.TestStep{
            {
                Config: testAccExampleConfig_basic(rName),
                ConfigStateChecks: []statecheck.StateCheck{
                    stateCheckExampleExists(resourceName, &widget),
                    statecheck.ExpectKnownValue(resourceName,
                        tfjsonpath.New("name"), knownvalue.StringExact(rName)),
                    statecheck.ExpectKnownValue(resourceName,
                        tfjsonpath.New("id"), knownvalue.NotNull()),
                },
            },
        },
    })
}

Use resource.ParallelTest by default. Use resource.Test only when tests share state or cannot run concurrently.


Provider Factory

// provider_test.go — Plugin Framework with Protocol 6 (use Protocol5 variant if needed)
var testAccProtoV6ProviderFactories = map[string]func() (tfprotov6.ProviderServer, error){
    "example": providerserver.NewProtocol6WithError(New("test")()),
}

TestCase Fields

Field Purpose
PreCheck func() — verify prerequisites (env vars, API access)
ProtoV6ProviderFactories Plugin Framework provider factories
CheckDestroy TestCheckFunc — verify resources destroyed after all steps
Steps []TestStep — sequential test operations
TerraformVersionChecks []tfversion.TerraformVersionCheck — gate by CLI version

TestStep Fields

Config Mode

Field Purpose
Config Inline HCL string to apply
ConfigStateChecks []statecheck.StateCheck — modern assertions (preferred)
ConfigPlanChecks resource.ConfigPlanChecks{PreApply: []plancheck.PlanCheck{...}}
ExpectError *regexp.Regexp — expect failure matching pattern
ExpectNonEmptyPlan bool — expect non-empty plan after apply
PlanOnly bool — plan without applying
Destroy bool — run destroy step
PreConfig func() — setup before step

Import Mode

Field Purpose
ImportState true to enable import mode
ImportStateVerify Verify imported state matches prior state
ImportStateVerifyIgnore []string — attributes to skip during verify
ImportStateKind resource.ImportBlockWithID — import block generation
ResourceName Resource address to import
ImportStateId Override the ID used for import

Check Functions

Modern: ConfigStateChecks (preferred)

Type-safe with aggregated error reporting. Compose built-in checks with custom statecheck.StateCheck implementations. See references/checks.md for full knownvalue types, tfjsonpath navigation, and comparers.

ConfigStateChecks: []statecheck.StateCheck{
    stateCheckExampleExists(resourceName, &widget),
    statecheck.ExpectKnownValue(resourceName,
        tfjsonpath.New("name"), knownvalue.StringExact("my-widget")),
    statecheck.ExpectKnownValue(resourceName,
        tfjsonpath.New("enabled"), knownvalue.Bool(true)),
    statecheck.ExpectKnownValue(resourceName,
        tfjsonpath.New("id"), knownvalue.NotNull()),
    statecheck.ExpectSensitiveValue(resourceName,
        tfjsonpath.New("api_key")),
},

Do not mix Check (legacy) and ConfigStateChecks in the same step.

Legacy: Check (for CheckDestroy and migration)

CheckDestroy on TestCase requires TestCheckFunc. The Check field on TestStep also accepts TestCheckFunc but prefer ConfigStateChecks for new tests.

Check: resource.ComposeAggregateTestCheckFunc(
    resource.TestCheckResourceAttr(name, "key", "expected"),
    resource.TestCheckResourceAttrSet(name, "id"),
    resource.TestCheckNoResourceAttr(name, "removed"),
    resource.TestMatchResourceAttr(name, "url", regexp.MustCompile(`^https://`)),
    resource.TestCheckResourceAttrPair(res1, "ref_id", res2, "id"),
),

ComposeAggregateTestCheckFunc reports all errors; ComposeTestCheckFunc fails fast on the first.


Config Helpers

Use numbered format verbs — %[1]q for quoted strings, %[1]s for raw:

func testAccExampleConfig_basic(rName string) string {
    return fmt.Sprintf(`
resource "example_widget" "test" {
  name = %[1]q
}
`, rName)
}

func testAccExampleConfig_full(rName, description string) string {
    return fmt.Sprintf(`
resource "example_widget" "test" {
  name        = %[1]q
  description = %[2]q
  enabled     = true
}
`, rName, description)
}

Scenario Patterns

Basic + Update (combine in one test — updates are supersets of basic)

Steps: []resource.TestStep{
    {
        Config: testAccExampleConfig_basic(rName),
        ConfigStateChecks: []statecheck.StateCheck{
            stateCheckExampleExists(resourceName, &widget),
            statecheck.ExpectKnownValue(resourceName,
                tfjsonpath.New("name"), knownvalue.StringExact(rName)),
        },
    },
    {
        Config: testAccExampleConfig_full(rName, "updated"),
        Co
how to use provider-test-patterns

How to use provider-test-patterns on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add provider-test-patterns
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/hashicorp/agent-skills --skill provider-test-patterns

The skills CLI fetches provider-test-patterns from GitHub repository hashicorp/agent-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/provider-test-patterns

Reload or restart Cursor to activate provider-test-patterns. Access the skill through slash commands (e.g., /provider-test-patterns) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.528 reviews
  • Dhruvi Jain· Dec 12, 2024

    provider-test-patterns is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Hiroshi Mensah· Dec 8, 2024

    Solid pick for teams standardizing on skills: provider-test-patterns is focused, and the summary matches what you get after install.

  • Oshnikdeep· Nov 3, 2024

    Useful defaults in provider-test-patterns — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Ganesh Mohane· Oct 22, 2024

    Registry listing for provider-test-patterns matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Harper Yang· Sep 17, 2024

    Useful defaults in provider-test-patterns — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Sakshi Patil· Sep 1, 2024

    provider-test-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Nia Sharma· Sep 1, 2024

    Registry listing for provider-test-patterns matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Chaitanya Patil· Aug 20, 2024

    provider-test-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Luis Bansal· Aug 20, 2024

    Useful defaults in provider-test-patterns — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Ishan Gonzalez· Aug 8, 2024

    Registry listing for provider-test-patterns matched our evaluation — installs cleanly and behaves as described in the markdown.

showing 1-10 of 28

1 / 3