| 157 | } |
| 158 | |
| 159 | func TestValidateFuncSpec(t *testing.T) { |
| 160 | config := ` |
| 161 | foo = "invalid" |
| 162 | ` |
| 163 | f, diags := hclsyntax.ParseConfig([]byte(config), "", hcl.Pos{Line: 1, Column: 1}) |
| 164 | if diags.HasErrors() { |
| 165 | t.Fatal(diags.Error()) |
| 166 | } |
| 167 | |
| 168 | expectRange := map[string]*hcl.Range{ |
| 169 | "without_range": nil, |
| 170 | "with_range": &hcl.Range{ |
| 171 | Filename: "foobar", |
| 172 | Start: hcl.Pos{Line: 99, Column: 99}, |
| 173 | End: hcl.Pos{Line: 999, Column: 999}, |
| 174 | }, |
| 175 | } |
| 176 | |
| 177 | for name := range expectRange { |
| 178 | t.Run(name, func(t *testing.T) { |
| 179 | spec := &ValidateSpec{ |
| 180 | Wrapped: &AttrSpec{ |
| 181 | Name: "foo", |
| 182 | Type: cty.String, |
| 183 | }, |
| 184 | Func: func(value cty.Value) hcl.Diagnostics { |
| 185 | if value.AsString() != "invalid" { |
| 186 | return hcl.Diagnostics{ |
| 187 | &hcl.Diagnostic{ |
| 188 | Severity: hcl.DiagError, |
| 189 | Summary: "incorrect value", |
| 190 | Detail: fmt.Sprintf("invalid value passed in: %s", value.GoString()), |
| 191 | }, |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | return hcl.Diagnostics{ |
| 196 | &hcl.Diagnostic{ |
| 197 | Severity: hcl.DiagWarning, |
| 198 | Summary: "OK", |
| 199 | Detail: "validation called correctly", |
| 200 | Subject: expectRange[name], |
| 201 | }, |
| 202 | } |
| 203 | }, |
| 204 | } |
| 205 | |
| 206 | _, diags = Decode(f.Body, spec, nil) |
| 207 | if len(diags) != 1 || |
| 208 | diags[0].Severity != hcl.DiagWarning || |
| 209 | diags[0].Summary != "OK" || |
| 210 | diags[0].Detail != "validation called correctly" { |
| 211 | t.Fatalf("unexpected diagnostics: %s", diags.Error()) |
| 212 | } |
| 213 | |
| 214 | if expectRange[name] == nil && diags[0].Subject == nil { |
| 215 | t.Fatal("returned diagnostic subject missing") |
| 216 | } |