From ae103fc4912d2cf267e8ce89dbd1990a42bebbf4 Mon Sep 17 00:00:00 2001 From: Daniel Schmidt Date: Wed, 16 Oct 2024 16:24:55 +0200 Subject: [PATCH] test: emit a nice error message if the user uses ephemeral resource in terrafom test --- internal/command/test_test.go | 2 +- internal/moduletest/eval_context.go | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/internal/command/test_test.go b/internal/command/test_test.go index adbe0da160..bf566e3f21 100644 --- a/internal/command/test_test.go +++ b/internal/command/test_test.go @@ -273,7 +273,7 @@ func TestTest_Runs(t *testing.T) { "ephemeral_resource": { expectedOut: []string{"0 passed, 1 failed."}, // TODO: Improve error message, say something about ephemeral resources not being accessible in tests due to their ephemeral nature - expectedErr: []string{"Ephemeral resource instance has expired"}, + expectedErr: []string{"Ephemeral resource instance has expired", "Ephemeral resources not supported in the context of tests"}, code: 1, }, } diff --git a/internal/moduletest/eval_context.go b/internal/moduletest/eval_context.go index fe4fb3be62..01f081b136 100644 --- a/internal/moduletest/eval_context.go +++ b/internal/moduletest/eval_context.go @@ -92,6 +92,12 @@ func (ec *EvalContext) Evaluate() (Status, cty.Value, tfdiags.Diagnostics) { ruleDiags = ruleDiags.Append(moreDiags) refs = append(refs, moreRefs...) + // We want to emit diagnostics if users are using ephemeral resources in their checks + // as they are not supported since they are closed before this is evaluated. + // We do not remove the diagnostic about the ephemeral resource being closed already as it + // might be useful to the user. + ruleDiags = ruleDiags.Append(diagsForEphemeralResources(refs)) + hclCtx, moreDiags := scope.EvalContext(refs) ruleDiags = ruleDiags.Append(moreDiags) if moreDiags.HasErrors() { @@ -198,6 +204,23 @@ func (ec *EvalContext) Evaluate() (Status, cty.Value, tfdiags.Diagnostics) { return status, cty.ObjectVal(outputVals), diags } +func diagsForEphemeralResources(refs []*addrs.Reference) (diags tfdiags.Diagnostics) { + for _, ref := range refs { + switch v := ref.Subject.(type) { + case addrs.ResourceInstance: + if v.Resource.Mode == addrs.EphemeralResourceMode { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Ephemeral resources not supported in the context of tests", + Detail: "Ephemeral resources are not supported in the context of terraform test.", + Subject: ref.SourceRange.ToHCL().Ptr(), + }) + } + } + } + return diags +} + // evaluationData augments an underlying lang.Data -- presumably resulting // from a terraform.Context.PlanAndEval or terraform.Context.ApplyAndEval call -- // with results from prior runs that should therefore be available when