internal/mcp/jsonschema: support validating structs
The instance passed to Resolved.Validate can be a struct, or can contain structs. A struct is treated like the JSON object that it marshals to. Also support pointers to any depth. That is, if an instance is a **int, then Validate will treat it like an int (or nil). That won't happen if the instance is unmarshaled into an `any`, but may if it's unmarshaled into a struct. Change-Id: I39f9af58028bd779887495754519615cd5dfb6c8 Reviewed-on: https://go-review.googlesource.com/c/tools/+/670395 Reviewed-by: Alan Donovan <adonovan@google.com> Auto-Submit: Jonathan Amsterdam <jba@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
parent
f8098af1c5
commit
435f5447df
1 changed files with 153 additions and 19 deletions
|
|
@ -80,3 +80,35 @@ func TestValidate(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructInstance(t *testing.T) {
|
||||
instance := struct {
|
||||
I int
|
||||
B bool `json:"b"`
|
||||
u int
|
||||
}{1, true, 0}
|
||||
|
||||
// The instance fails for all of these schemas, demonstrating that it
|
||||
// was processed correctly.
|
||||
for _, schema := range []*Schema{
|
||||
{MinProperties: Ptr(3)},
|
||||
{MaxProperties: Ptr(1)},
|
||||
{Required: []string{"i"}}, // the name is "I"
|
||||
{Required: []string{"B"}}, // the name is "b"
|
||||
{PropertyNames: &Schema{MinLength: Ptr(2)}},
|
||||
{Properties: map[string]*Schema{"b": {Type: "number"}}},
|
||||
{Required: []string{"I"}, AdditionalProperties: falseSchema()},
|
||||
{DependentRequired: map[string][]string{"b": {"u"}}},
|
||||
{DependentSchemas: map[string]*Schema{"b": falseSchema()}},
|
||||
{UnevaluatedProperties: falseSchema()},
|
||||
} {
|
||||
res, err := schema.Resolve("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = res.Validate(instance)
|
||||
if err == nil {
|
||||
t.Errorf("succeeded but wanted failure; schema = %s", schema.json())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue