package modules_test import ( "errors" "strings" "testing" "uberbringer/internal/pkg/modules" ) type decodeTarget struct { Name string `json:"name"` Count int `json:"count"` On *bool `json:"on"` Tags []string `json:"tags"` Marks []int `json:"marks"` Skip string `json:"-"` } func TestDecodeStrict(t *testing.T) { var got decodeTarget body := `{"name":"n","count":3,"on":false,"tags":["a","b"],"marks":[1,2],"count":4}` if err := modules.DecodeStrict([]byte(body), &got); err != nil { t.Fatal(err) } if got.Name != "n" || got.Count != 4 || got.On == nil || *got.On || strings.Join(got.Tags, ",") != "a,b" || len(got.Marks) != 2 { t.Errorf("decoded %+v", got) } var empty decodeTarget if err := modules.DecodeStrict([]byte(` {"name": null} `), &empty); err != nil || empty.Name != "" { t.Errorf("a null field: %v, %+v; want it treated as absent", err, empty) } } func TestDecodeStrictProblems(t *testing.T) { tests := []struct { name, body string want []string // the complete list of problems }{ {"empty body", "", []string{"body: empty; expected a JSON object"}}, {"blank body", " \n", []string{"body: empty; expected a JSON object"}}, {"array", `[1]`, []string{"body: expected a JSON object, got array"}}, {"string", `"x"`, []string{"body: expected a JSON object, got string"}}, {"null", `null`, []string{"body: expected a JSON object, got null"}}, {"syntax error", `{"name":`, []string{"body: not valid JSON: unexpected EOF"}}, {"trailing data", `{} {}`, []string{"body: trailing data after the payload"}}, {"every problem at once", `{"Name":"x","colour":1,"count":"3","on":"yes","tags":[1],"marks":[1.5],"hidden":"h","Skip":"s","-":1}`, []string{ "-: unknown field", "Name: unknown field", "Skip: unknown field", "colour: unknown field", "count: expected a whole number", "hidden: unknown field", "marks: expected an array of whole numbers", "on: expected true or false", "tags: expected an array of strings", }}, {"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}}, {"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{ `"a b": unknown field`, strings.Repeat("x", 64) + "...: unknown field", }}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var v decodeTarget err := modules.DecodeStrict([]byte(tt.body), &v) var pe *modules.PayloadError if !errors.As(err, &pe) { t.Fatalf("err = %v, want *PayloadError", err) } if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") { t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n")) } }) } } func TestDecodeStrictNeedsAStruct(t *testing.T) { defer func() { if recover() == nil { t.Error("DecodeStrict into a map did not panic") } }() var m map[string]any _ = modules.DecodeStrict([]byte(`{}`), &m) }