| 50 | } |
| 51 | |
| 52 | func TestExample(t *testing.T) { |
| 53 | cases := []struct { |
| 54 | Name string |
| 55 | DSL func() |
| 56 | Expected any |
| 57 | Error string |
| 58 | }{ |
| 59 | {"with-example", testdata.WithExampleDSL, "example", ""}, |
| 60 | {"with-array-example", testdata.WithArrayExampleDSL, []int{1, 2}, ""}, |
| 61 | {"with-map-example", testdata.WithMapExampleDSL, map[string]int{"name": 1, "value": 2}, ""}, |
| 62 | {"with-multiple-examples", testdata.WithMultipleExamplesDSL, 100, ""}, |
| 63 | {"overriding-example", testdata.OverridingExampleDSL, map[string]any{"name": "overridden"}, ""}, |
| 64 | {"with-extend", testdata.WithExtendExampleDSL, map[string]any{"name": "example"}, ""}, |
| 65 | {"invalid-example-type", testdata.InvalidExampleTypeDSL, nil, "service \"InvalidExampleType\" method \"Method\": payload - example value map[int]int{1:1} is incompatible with type map"}, |
| 66 | {"empty-example", testdata.EmptyExampleDSL, nil, "too few arguments given to Example in attribute"}, |
| 67 | {"hiding-example", testdata.HidingExampleDSL, nil, ""}, |
| 68 | {"overriding-hidden-examples", testdata.OverridingHiddenExamplesDSL, "example", ""}, |
| 69 | } |
| 70 | r := expr.NewRandom("test") |
| 71 | for _, k := range cases { |
| 72 | t.Run(k.Name, func(t *testing.T) { |
| 73 | if k.Error == "" { |
| 74 | expr.RunDSL(t, k.DSL) |
| 75 | example := expr.Root.Services[0].Methods[0].Payload.Example(r) |
| 76 | if !reflect.DeepEqual(example, k.Expected) { |
| 77 | t.Errorf("invalid example: got %v, expected %v", example, k.Expected) |
| 78 | } |
| 79 | } else { |
| 80 | if err := expr.RunInvalidDSL(t, k.DSL); err == nil { |
| 81 | t.Error("the expected error was not returned") |
| 82 | } else if !strings.Contains(err.Error(), k.Error) { |
| 83 | t.Errorf("invalid error: got %q, expected %q", err.Error(), k.Error) |
| 84 | } |
| 85 | } |
| 86 | }) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // TestByLengthWithAliasType tests that alias types with length validations |
| 91 | // can generate examples correctly. Previously, this would panic because the |