File: decode_test.go

package info (click to toggle)
golang-github-cue-lang-cue 0.12.0.-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 19,072 kB
  • sloc: sh: 57; makefile: 17
file content (423 lines) | stat: -rw-r--r-- 12,562 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2019 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package jsonschema_test

import (
	"bytes"
	"fmt"
	"io/fs"
	"net/url"
	"path"
	"strings"
	"testing"

	"github.com/go-quicktest/qt"
	"golang.org/x/tools/txtar"

	"cuelang.org/go/cue"
	"cuelang.org/go/cue/ast"
	"cuelang.org/go/cue/cuecontext"
	"cuelang.org/go/cue/errors"
	"cuelang.org/go/cue/format"
	"cuelang.org/go/cue/token"
	"cuelang.org/go/encoding/json"
	"cuelang.org/go/encoding/jsonschema"
	"cuelang.org/go/encoding/yaml"
	"cuelang.org/go/internal/astinternal"
	"cuelang.org/go/internal/cuetdtest"
	"cuelang.org/go/internal/cuetxtar"
	_ "cuelang.org/go/pkg"
)

// TestDecode reads the testdata/*.txtar files, converts the contained
// JSON schema to CUE and compares it against the output.
//
// Set CUE_UPDATE=1 to update test files with the corresponding output.
//
// Each test extracts the JSON Schema from a schema file (either
// schema.json or schema.yaml) and writes the result to
// out/decode/extract.
//
// If there are any files in the "test" directory in the txtar, each one
// is extracted and validated against the extracted schema. If the file
// name starts with "err-" it is expected to fail, otherwise it is
// expected to succeed.
//
// If the first line of a test file starts with a "#" character,
// it should start with `#schema` followed by a CUE path
// of the schema to test within the extracted schema.
//
// The #noverify tag in the txtar header causes verification and
// instance tests to be skipped.
//
// The #version: <version> tag selects the default schema version URI to use.
// As a special case, when this is "openapi", OpenAPI extraction
// mode is enabled.
func TestDecode(t *testing.T) {
	test := cuetxtar.TxTarTest{
		Root:   "./testdata/txtar",
		Name:   "decode",
		Matrix: cuetdtest.FullMatrix,
	}
	test.Run(t, func(t *cuetxtar.Test) {
		cfg := &jsonschema.Config{}

		if t.HasTag("brokenInV2") && t.M.Name() == "v2" {
			t.Skip("skipping because test is broken under the v2 evaluator")
		}

		if versStr, ok := t.Value("version"); ok {
			// TODO most schemas have neither an explicit $schema or a #version
			// tag, so when we update the default version, they could break.
			// We should probably change most of the tests to use an explicit $schema
			// field apart from when we're explicitly testing the default version logic.
			if versStr == "openapi" {
				// OpenAPI doesn't have a JSON Schema URI so it gets a special case.
				cfg.DefaultVersion = jsonschema.VersionOpenAPI
				cfg.Root = "#/components/schemas/"
				cfg.StrictKeywords = true // OpenAPI always uses strict keywords
				cfg.Map = func(p token.Pos, a []string) ([]ast.Label, error) {
					// Just for testing: does not validate the path.
					return []ast.Label{ast.NewIdent("#" + a[len(a)-1])}, nil
				}
			} else {
				vers, err := jsonschema.ParseVersion(versStr)
				qt.Assert(t, qt.IsNil(err))
				cfg.DefaultVersion = vers
			}
		}
		cfg.Strict = t.HasTag("strict")
		cfg.StrictKeywords = cfg.StrictKeywords || t.HasTag("strictKeywords")
		cfg.AllowNonExistentRoot = t.HasTag("allowNonExistentRoot")
		cfg.StrictFeatures = t.HasTag("strictFeatures")
		cfg.PkgName, _ = t.Value("pkgName")

		ctx := t.CueContext()

		fsys, err := txtar.FS(t.Archive)
		if err != nil {
			t.Fatal(err)
		}
		v, err := readSchema(ctx, fsys)
		if err != nil {
			t.Fatal(err)
		}
		if err := v.Err(); err != nil {
			t.Fatal(err)
		}

		w := t.Writer("extract")
		expr, err := jsonschema.Extract(v, cfg)
		if err != nil {
			got := "ERROR:\n" + errors.Details(err, nil)
			w.Write([]byte(strings.TrimSpace(got) + "\n"))
			return
		}
		if expr == nil {
			t.Fatal("no expression was extracted")
		}

		b, err := format.Node(expr, format.Simplify())
		if err != nil {
			t.Fatal(errors.Details(err, nil))
		}
		b = append(bytes.TrimSpace(b), '\n')
		w.Write(b)
		if t.HasTag("noverify") {
			return
		}
		// Verify that the generated CUE compiles.
		schemav := ctx.CompileBytes(b, cue.Filename("generated.cue"))
		if err := schemav.Err(); err != nil {
			t.Fatal(errors.Details(err, nil), qt.Commentf("generated code: %q", b))
		}
		testEntries, err := fs.ReadDir(fsys, "test")
		if err != nil {
			return
		}
		for _, e := range testEntries {
			file := path.Join("test", e.Name())
			var v cue.Value
			base := ""
			testData, err := fs.ReadFile(fsys, file)
			if err != nil {
				t.Fatal(err)
			}
			var schemaPath cue.Path
			if bytes.HasPrefix(testData, []byte("#")) {
				directiveBytes, rest, _ := bytes.Cut(testData, []byte("\n"))
				// Replace the directive with a newline so the line numbers
				// are correct in any error messages.
				testData = append([]byte("\n"), rest...)
				directive := string(directiveBytes)
				verb, arg, ok := strings.Cut(directive, " ")
				if verb != "#schema" {
					t.Fatalf("unknown directive %q in test file %v", directiveBytes, file)
				}
				if !ok {
					t.Fatalf("no schema path argument to #schema directive in %s", file)
				}
				schemaPath = cue.ParsePath(arg)
				qt.Assert(t, qt.IsNil(schemaPath.Err()))
			}

			switch {
			case strings.HasSuffix(file, ".json"):
				expr, err := json.Extract(file, testData)
				if err != nil {
					t.Fatal(err)
				}
				v = ctx.BuildExpr(expr)
				base = strings.TrimSuffix(e.Name(), ".json")

			case strings.HasSuffix(file, ".yaml"):
				file, err := yaml.Extract(file, testData)
				if err != nil {
					t.Fatal(err)
				}
				v = ctx.BuildFile(file)
				base = strings.TrimSuffix(e.Name(), ".yaml")
			default:
				t.Fatalf("unknown file encoding for test file %v", file)
			}
			if err := v.Err(); err != nil {
				t.Fatalf("error building expression for test %v: %v", file, err)
			}
			subSchema := schemav.LookupPath(schemaPath)
			if !subSchema.Exists() {
				t.Fatalf("path %q does not exist within schema", schemaPath)
			}
			rv := subSchema.Unify(v)
			if strings.HasPrefix(e.Name(), "err-") {
				err := rv.Err()
				if err == nil {
					t.Fatalf("test %v unexpectedly passes", file)
				}
				if t.M.IsDefault() {
					// The error results of the different evaluators can vary,
					// so only test the exact results for the default evaluator.
					t.Writer(path.Join("testerr", base)).Write([]byte(errors.Details(err, nil)))
				}
			} else {
				if err := rv.Err(); err != nil {
					t.Fatalf("test %v unexpectedly fails: %v", file, errors.Details(err, nil))
				}
			}
		}
	})
}

func readSchema(ctx *cue.Context, fsys fs.FS) (cue.Value, error) {
	jsonData, jsonErr := fs.ReadFile(fsys, "schema.json")
	yamlData, yamlErr := fs.ReadFile(fsys, "schema.yaml")
	switch {
	case jsonErr == nil && yamlErr == nil:
		return cue.Value{}, fmt.Errorf("cannot define both schema.json and schema.yaml")
	case jsonErr == nil:
		expr, err := json.Extract("schema.json", jsonData)
		if err != nil {
			return cue.Value{}, err
		}
		return ctx.BuildExpr(expr), nil
	case yamlErr == nil:
		file, err := yaml.Extract("schema.yaml", yamlData)
		if err != nil {
			return cue.Value{}, err
		}
		return ctx.BuildFile(file), nil
	}
	return cue.Value{}, fmt.Errorf("no schema.yaml or schema.json file found for test")
}

func TestMapURL(t *testing.T) {
	v := cuecontext.New().CompileString(`
type: "object"
properties: x: $ref: "https://something.test/foo#/definitions/blah"
`)
	var calls []string
	expr, err := jsonschema.Extract(v, &jsonschema.Config{
		MapURL: func(u *url.URL) (string, cue.Path, error) {
			calls = append(calls, u.String())
			return "other.test/something:blah", cue.ParsePath("#Foo.bar"), nil
		},
	})
	qt.Assert(t, qt.IsNil(err))
	b, err := format.Node(expr, format.Simplify())
	if err != nil {
		t.Fatal(errors.Details(err, nil))
	}
	qt.Assert(t, qt.DeepEquals(calls, []string{"https://something.test/foo"}))
	qt.Assert(t, qt.Equals(string(b), `
import "other.test/something:blah"

x?: blah.#Foo.bar.#blah
...
`[1:]))
}

func TestMapURLErrors(t *testing.T) {
	v := cuecontext.New().CompileString(`
type: "object"
properties: {
	x: $ref: "https://something.test/foo#/definitions/x"
	y: $ref: "https://something.test/foo#/definitions/y"
}
`, cue.Filename("foo.cue"))
	_, err := jsonschema.Extract(v, &jsonschema.Config{
		MapURL: func(u *url.URL) (string, cue.Path, error) {
			return "", cue.Path{}, fmt.Errorf("some error")
		},
	})
	qt.Assert(t, qt.Equals(errors.Details(err, nil), `
cannot determine CUE location for JSON Schema location id=https://something.test/foo#/definitions/x: some error:
    foo.cue:4:5
cannot determine CUE location for JSON Schema location id=https://something.test/foo#/definitions/y: some error:
    foo.cue:5:5
`[1:]))
}

func TestMapRef(t *testing.T) {
	v := cuecontext.New().CompileString(`
type: "object"
$id: "https://this.test"
$defs: foo: type: "string"
properties: x: $ref: "https://something.test/foo#/$defs/blah"
`)
	var calls []string
	expr, err := jsonschema.Extract(v, &jsonschema.Config{
		MapRef: func(loc jsonschema.SchemaLoc) (string, cue.Path, error) {
			calls = append(calls, loc.String())
			switch loc.ID.String() {
			case "https://this.test#/$defs/foo":
				return "", cue.ParsePath("#x.#def.#foo"), nil
			case "https://something.test/foo#/$defs/blah":
				return "other.test/something:blah", cue.ParsePath("#Foo.bar"), nil
			case "https://this.test":
				return "", cue.Path{}, nil
			}
			t.Errorf("unexpected ID")
			return "", cue.Path{}, fmt.Errorf("unexpected ID %q passed to MapRef", loc.ID)
		},
	})
	qt.Assert(t, qt.IsNil(err))
	b, err := format.Node(expr, format.Simplify())
	if err != nil {
		t.Fatal(errors.Details(err, nil))
	}
	qt.Assert(t, qt.DeepEquals(calls, []string{
		"id=https://this.test#/$defs/foo localPath=$defs.foo",
		"id=https://something.test/foo#/$defs/blah",
		"id=https://this.test localPath=",
		"id=https://something.test/foo#/$defs/blah",
	}))
	qt.Assert(t, qt.Equals(string(b), `
import "other.test/something:blah"

@jsonschema(id="https://this.test")
x?: blah.#Foo.bar

#x: #def: #foo: string
...
`[1:]))
}

func TestMapRefExternalRefForInternalSchema(t *testing.T) {
	v := cuecontext.New().CompileString(`
type: "object"
$id: "https://this.test"
$defs: foo: type: ["number", "string"]
$ref: "#/$defs/foo"
`)
	var calls []string
	defines := make(map[string]string)
	expr, err := jsonschema.Extract(v, &jsonschema.Config{
		MapRef: func(loc jsonschema.SchemaLoc) (string, cue.Path, error) {
			calls = append(calls, loc.String())
			switch loc.ID.String() {
			case "https://this.test#/$defs/foo":
				return "otherpkg.example/foo", cue.ParsePath("#foo"), nil
			case "https://this.test":
				return "", cue.Path{}, nil
			}
			t.Errorf("unexpected ID")
			return "", cue.Path{}, fmt.Errorf("unexpected ID %q passed to MapRef", loc.ID)
		},
		DefineSchema: func(importPath string, path cue.Path, e ast.Expr) {
			data, err := format.Node(e)
			if err != nil {
				t.Errorf("cannot format: %v", err)
				return
			}
			defines[fmt.Sprintf("%s.%v", importPath, path)] = string(data)
		},
	})
	qt.Assert(t, qt.IsNil(err))
	b, err := format.Node(expr, format.Simplify())
	if err != nil {
		t.Fatal(errors.Details(err, nil))
	}
	qt.Assert(t, qt.DeepEquals(calls, []string{
		"id=https://this.test#/$defs/foo localPath=$defs.foo",
		"id=https://this.test localPath=",
	}))
	qt.Assert(t, qt.Equals(string(b), `
import "otherpkg.example/foo"

@jsonschema(id="https://this.test")
foo.#foo & {
	...
}
`[1:]))
	qt.Assert(t, qt.DeepEquals(defines, map[string]string{
		"otherpkg.example/foo.#foo": "number | string",
	}))
}

func TestX(t *testing.T) {
	t.Skip()
	data := `
-- schema.json --
`

	a := txtar.Parse([]byte(data))

	ctx := cuecontext.New()
	var v cue.Value
	var err error
	for _, f := range a.Files {
		switch path.Ext(f.Name) {
		case ".json":
			expr, err := json.Extract(f.Name, f.Data)
			if err != nil {
				t.Fatal(err)
			}
			v = ctx.BuildExpr(expr)
		case ".yaml":
			file, err := yaml.Extract(f.Name, f.Data)
			if err != nil {
				t.Fatal(err)
			}
			v = ctx.BuildFile(file)
		}
	}

	cfg := &jsonschema.Config{ID: "test"}
	expr, err := jsonschema.Extract(v, cfg)
	if err != nil {
		t.Fatal(err)
	}

	t.Fatal(astinternal.DebugStr(expr))
}