Provider contract and lifecycle testing
A lifecycle contract is more than CRUD
Create, Read, Update and Delete methods connect Terraform’s state model with service operations. The framework passes request structures containing plan, configuration or prior state as appropriate. The provider reports results through response state and diagnostics. Start by testing the service adapter independently, then test the actual provider integration with Terraform in isolation. Our supplied Go fixture is an intentionally small in-memory service with a capacity limit, stable IDs and an injected post-commit error. It cannot reach the network and does not import the Plugin Framework.
Lifecycle contract for fictional lab_noteCreate(key, name, body): allocate one stable ID per request keyRead(id): return current record; authoritative absence is not a transient errorUpdate(id, name, body): change fields, preserve identityDelete(id): absent is success in this serviceImport(id): lookup existing record, do not createUpgrade v0 -> v1: label becomes name; preserve id and bodyThe request key is part of the toy service contract, not a Terraform-provided universal idempotency token. A real provider needs a supported service-side deduplication mechanism or another verified way to reconcile ambiguous requests. Do not assume retrying an arbitrary Create is safe.
Create and Read: confirm identity and actual data
Create decodes the plan, checks diagnostics, requests creation and records the confirmed object in state. Return known values consistent with the plan; compute service-generated IDs from the response. A timeout after a successful service commit is ambiguous: an object may exist even though the client did not receive confirmation. In the toy service, a repeated identical request key returns the existing record. A different payload for an already-used key is rejected. A key for a deleted object is not automatically reusable.
Toy service trace (asserted by Go tests)Create("k1", "blue", "draft") -> committed; injected errorCreate("k1", "blue", "draft") -> note-1Read("note-1") -> blue, draftNumber of records -> 1Read should update state to reflect what the service actually returns. An authoritative not-found response can justify removing the resource from state. A transient failure, permission error or uncertain response is not proof of deletion. Preserve identity and return a useful diagnostic in those cases. The next Terraform plan can then distinguish real absence from an unsuccessful refresh.
Update and Delete: keep state truthful
Update receives planned values and prior state, and should preserve the identity of an in-place change. If an API supports only replacement, express that in planning rather than silently deleting and recreating an object during update. Delete requests removal of the prior object; an authoritative absence is success in our service. For actual providers, classify API errors carefully and follow the framework response rules. Report known partial results where appropriate; an error diagnostic does not automatically discard all returned state. Use context deadlines and bounded backoff for retryable failures, rather than retrying invalid input or missing permissions indefinitely.
// Illustrative decision model, not an actual framework method.switch {case authoritativeMissing: // Read: remove from state; Delete: already absent.case retryable && budgetRemaining: // Wait with cancellation support, then retry safe operations.case err != nil: // Preserve known identity; add sanitized error diagnostic.default: // Record verified result consistent with the plan.}The mock fixture tests error classification through explicit sentinel errors and tests canceled contexts. Its retry logic is represented by deliberate repeated calls, not by a production retry library. A real service can have asynchronous deletion, read-after-write lag or quota limits; use an operation-specific timeout and verify actual completion.
Import and schema migration
Import should identify an existing object and populate enough state for the next Read; it must not allocate a replacement object as a shortcut. In a simple ID-based framework resource, ImportState can pass the ID into the ID attribute. More complex imports may need multiple identifying values. A state upgrader is different: it converts an old state shape to the current resource schema without inventing a new remote identity.
// Illustrative import method fragment; imports and resource type omitted.func (r *noteResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)}In the fixture, import calls Read; the upgrade function maps version zero label to version one name, preserving ID and body. Missing or unsupported legacy data is an error. Real framework upgrade implementations must produce the full current schema state and handle every supported prior version. Test both successful translation and rejection before shipping a provider upgrade.
Test in layers and collect real evidence
Unit tests exercise local pure logic, model conversion and client behavior. Mock-service tests can exercise controlled responses, identity preservation, cancellation and repeated operations. Provider acceptance tests run Terraform through the plugin-testing library and can create infrastructure even if invoked from a Go test command. Keep those tests behind explicit authorization, use an isolated environment, verify cleanup and record which versions actually ran. A successful mock test does not prove provider protocol compatibility, schema validity, Terraform state consistency or remote API behavior.
# From lab-fixtures/provider-development/local-service# Standard library only, no Terraform CLI or cloud accounts needed.GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local go test -count=1 -v ./...The packaged results contain the actual Go test output. Inspect failures rather than editing expected results to make the suite green. The next integration layer would need a version-pinned provider server, a bounded mock service shared across plugin process lifetimes, and tests for initial apply, empty subsequent plan, update, import verification, drift, deletion, cancellation and upgrade. No such layer is claimed to have run.
Review before releasing
Write a support matrix for the Go toolchain, Framework, protocol and CLI. Review schema evolution, credential handling, diagnostic sanitization, concurrency, retries, documentation and tests with positive and negative assertions. Package the provider only after verifying dependencies and supply-chain requirements. Publishing and real acceptance tests need separate approval. This lesson ends with a local test suite and a design worksheet, not a released provider. Next: infrastructure delivery, migration and operational excellence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Provider contract and lifecycle testing — knowledge check
Review provider schema and lifecycle contracts.
Create times out after a possible commit. What is safest?
When should Read treat an object as absent?
What does an import operation do in this toy contract?
Which check demonstrates the v0 to v1 mapping?
What does a passing mock service test prove?