github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/tfdiags/hcl_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package tfdiags 5 6 import ( 7 "fmt" 8 "testing" 9 10 "github.com/google/go-cmp/cmp" 11 "github.com/google/go-cmp/cmp/cmpopts" 12 "github.com/hashicorp/hcl/v2" 13 "github.com/zclconf/go-cty/cty" 14 ) 15 16 func TestDiagnosticsToHCL(t *testing.T) { 17 var diags Diagnostics 18 diags = diags.Append(Sourceless( 19 Error, 20 "A sourceless diagnostic", 21 "...that has a detail", 22 )) 23 diags = diags.Append(fmt.Errorf("a diagnostic promoted from an error")) 24 diags = diags.Append(SimpleWarning("A diagnostic from a simple warning")) 25 diags = diags.Append(&hcl.Diagnostic{ 26 Severity: hcl.DiagWarning, 27 Summary: "A diagnostic from HCL", 28 Detail: "...that has a detail and source information", 29 Subject: &hcl.Range{ 30 Filename: "test.tf", 31 Start: hcl.Pos{Line: 1, Column: 2, Byte: 1}, 32 End: hcl.Pos{Line: 1, Column: 3, Byte: 2}, 33 }, 34 Context: &hcl.Range{ 35 Filename: "test.tf", 36 Start: hcl.Pos{Line: 1, Column: 1, Byte: 0}, 37 End: hcl.Pos{Line: 1, Column: 4, Byte: 3}, 38 }, 39 EvalContext: &hcl.EvalContext{}, 40 Expression: &fakeHCLExpression{}, 41 }) 42 43 got := diags.ToHCL() 44 want := hcl.Diagnostics{ 45 { 46 Severity: hcl.DiagError, 47 Summary: "A sourceless diagnostic", 48 Detail: "...that has a detail", 49 }, 50 { 51 Severity: hcl.DiagError, 52 Summary: "a diagnostic promoted from an error", 53 }, 54 { 55 Severity: hcl.DiagWarning, 56 Summary: "A diagnostic from a simple warning", 57 }, 58 { 59 Severity: hcl.DiagWarning, 60 Summary: "A diagnostic from HCL", 61 Detail: "...that has a detail and source information", 62 Subject: &hcl.Range{ 63 Filename: "test.tf", 64 Start: hcl.Pos{Line: 1, Column: 2, Byte: 1}, 65 End: hcl.Pos{Line: 1, Column: 3, Byte: 2}, 66 }, 67 Context: &hcl.Range{ 68 Filename: "test.tf", 69 Start: hcl.Pos{Line: 1, Column: 1, Byte: 0}, 70 End: hcl.Pos{Line: 1, Column: 4, Byte: 3}, 71 }, 72 EvalContext: &hcl.EvalContext{}, 73 Expression: &fakeHCLExpression{}, 74 }, 75 } 76 77 if diff := cmp.Diff(want, got, cmpopts.IgnoreUnexported(hcl.EvalContext{})); diff != "" { 78 t.Errorf("incorrect result\n%s", diff) 79 } 80 } 81 82 // We have this here just to give us something easy to compare in the test 83 // above, because we only care that the expression passes through, not about 84 // how exactly it is shaped. 85 type fakeHCLExpression struct { 86 } 87 88 func (e *fakeHCLExpression) Range() hcl.Range { 89 return hcl.Range{} 90 } 91 92 func (e *fakeHCLExpression) StartRange() hcl.Range { 93 return hcl.Range{} 94 } 95 96 func (e *fakeHCLExpression) Variables() []hcl.Traversal { 97 return nil 98 } 99 100 func (e *fakeHCLExpression) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { 101 return cty.DynamicVal, nil 102 }