11package hcldec
22
33import (
4+ "fmt"
45 "reflect"
56 "testing"
67
@@ -26,6 +27,7 @@ var _ Spec = (*BlockLabelSpec)(nil)
2627var _ Spec = (* DefaultSpec )(nil )
2728var _ Spec = (* TransformExprSpec )(nil )
2829var _ Spec = (* TransformFuncSpec )(nil )
30+ var _ Spec = (* ValidateSpec )(nil )
2931
3032var _ attrSpec = (* AttrSpec )(nil )
3133var _ attrSpec = (* DefaultSpec )(nil )
@@ -139,3 +141,69 @@ bar = barval
139141 }
140142 })
141143}
144+
145+ func TestValidateFuncSpec (t * testing.T ) {
146+ config := `
147+ foo = "invalid"
148+ `
149+ f , diags := hclsyntax .ParseConfig ([]byte (config ), "" , hcl.Pos {Line : 1 , Column : 1 })
150+ if diags .HasErrors () {
151+ t .Fatal (diags .Error ())
152+ }
153+
154+ expectRange := map [string ]* hcl.Range {
155+ "without_range" : nil ,
156+ "with_range" : & hcl.Range {
157+ Filename : "foobar" ,
158+ Start : hcl.Pos {Line : 99 , Column : 99 },
159+ End : hcl.Pos {Line : 999 , Column : 999 },
160+ },
161+ }
162+
163+ for name := range expectRange {
164+ t .Run (name , func (t * testing.T ) {
165+ spec := & ValidateSpec {
166+ Wrapped : & AttrSpec {
167+ Name : "foo" ,
168+ Type : cty .String ,
169+ },
170+ Func : func (value cty.Value ) hcl.Diagnostics {
171+ if value .AsString () != "invalid" {
172+ return hcl.Diagnostics {
173+ & hcl.Diagnostic {
174+ Severity : hcl .DiagError ,
175+ Summary : "incorrect value" ,
176+ Detail : fmt .Sprintf ("invalid value passed in: %s" , value .GoString ()),
177+ },
178+ }
179+ }
180+
181+ return hcl.Diagnostics {
182+ & hcl.Diagnostic {
183+ Severity : hcl .DiagWarning ,
184+ Summary : "OK" ,
185+ Detail : "validation called correctly" ,
186+ Subject : expectRange [name ],
187+ },
188+ }
189+ },
190+ }
191+
192+ _ , diags = Decode (f .Body , spec , nil )
193+ if len (diags ) != 1 ||
194+ diags [0 ].Severity != hcl .DiagWarning ||
195+ diags [0 ].Summary != "OK" ||
196+ diags [0 ].Detail != "validation called correctly" {
197+ t .Fatalf ("unexpected diagnostics: %s" , diags .Error ())
198+ }
199+
200+ if expectRange [name ] == nil && diags [0 ].Subject == nil {
201+ t .Fatal ("returned diagnostic subject missing" )
202+ }
203+
204+ if expectRange [name ] != nil && ! reflect .DeepEqual (expectRange [name ], diags [0 ].Subject ) {
205+ t .Fatalf ("expected range %s, got range %s" , expectRange [name ], diags [0 ].Subject )
206+ }
207+ })
208+ }
209+ }
0 commit comments