|
| 1 | +package gen |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/stretchr/testify/require" |
| 7 | + |
| 8 | + "github.com/ogen-go/ogen/jsonschema" |
| 9 | +) |
| 10 | + |
| 11 | +type captureFS struct { |
| 12 | + files map[string][]byte |
| 13 | +} |
| 14 | + |
| 15 | +func (c *captureFS) WriteFile(baseName string, source []byte) error { |
| 16 | + if c.files == nil { |
| 17 | + c.files = map[string][]byte{} |
| 18 | + } |
| 19 | + c.files[baseName] = source |
| 20 | + return nil |
| 21 | +} |
| 22 | + |
| 23 | +func TestGenerateSchemaConstURICompiles(t *testing.T) { |
| 24 | + a := require.New(t) |
| 25 | + |
| 26 | + const uri = "https://example.com/context.jsonld" |
| 27 | + schema := &jsonschema.Schema{ |
| 28 | + Type: jsonschema.Object, |
| 29 | + Properties: []jsonschema.Property{ |
| 30 | + { |
| 31 | + Name: "@context", |
| 32 | + Schema: &jsonschema.Schema{ |
| 33 | + Type: jsonschema.String, |
| 34 | + Format: "uri", |
| 35 | + Const: uri, |
| 36 | + ConstSet: true, |
| 37 | + }, |
| 38 | + Required: true, |
| 39 | + }, |
| 40 | + { |
| 41 | + Name: "homepage", |
| 42 | + Schema: &jsonschema.Schema{ |
| 43 | + Type: jsonschema.String, |
| 44 | + Format: "uri", |
| 45 | + Const: "https://example.com/", |
| 46 | + ConstSet: true, |
| 47 | + }, |
| 48 | + }, |
| 49 | + }, |
| 50 | + } |
| 51 | + |
| 52 | + fs := &captureFS{} |
| 53 | + err := GenerateSchema(schema, fs, GenerateSchemaOptions{ |
| 54 | + TypeName: "Source", |
| 55 | + FileName: "output.gen.go", |
| 56 | + PkgName: "output", |
| 57 | + }) |
| 58 | + a.NoError(err) |
| 59 | + |
| 60 | + src, ok := fs.files["output.gen.go"] |
| 61 | + a.True(ok, "expected generated output.gen.go") |
| 62 | + got := string(src) |
| 63 | + |
| 64 | + // Regression for ogen-go/ogen#1751: const uri was passed as a string to |
| 65 | + // json.EncodeURI, which expects url.URL, so generated code did not compile. |
| 66 | + a.NotContains(got, `json.EncodeURI(e, "`+uri+`")`) |
| 67 | + a.NotContains(got, `json.EncodeURI(e, "https://example.com/")`) |
| 68 | + a.Contains(got, `e.Str("`+uri+`")`) |
| 69 | + a.Contains(got, `e.Str("https://example.com/")`) |
| 70 | +} |
0 commit comments