From 848e2b2b00b0e05500f18a714ffc982a91dfc629 Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Fri, 29 Sep 2023 17:02:25 +0100 Subject: [PATCH] Improve error message on type mismatch Before: Key 'group.d' is not an date-local but map[type:date-local value:1979-05-27]: Expected: map[string]interface {}{"type":"date-local", "value":"1979-05-27"} Your encoder: map[string]interface {}{"type":"date", "value":"1979-05-27"} After: Key "group.d" is not "date-local" but "date": Expected: map[string]any{"type":"date-local", "value":"1979-05-27"} Your encoder: map[string]any{"type":"date", "value":"1979-05-27"} --- json.go | 16 ++++++++-------- toml.go | 5 ++--- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/json.go b/json.go index 65bf985..3f8e2ac 100644 --- a/json.go +++ b/json.go @@ -241,15 +241,15 @@ func isValue(m map[string]any) bool { } func (r Test) mismatch(wantType string, want, have any) Test { - return r.fail("Key '%[1]s' is not an %[2]s but %[5]s:\n"+ - " Expected: %#[3]v\n"+ - " Your encoder: %#[4]v", - r.Key, wantType, want, have, fmtType(have)) + return r.fail("Key %[1]q is not %[2]q but %[5]q:\n"+ + " Expected: %s\n"+ + " Your encoder: %s", + r.Key, wantType, fmtHashV(want), fmtHashV(have), fmtType(have)) } func (r Test) valMismatch(wantType, haveType string, want, have any) Test { - return r.fail("Key '%s' is not an %s but %s:\n"+ - " Expected: %#[3]v\n"+ - " Your encoder: %#[4]v", - r.Key, wantType, want, have) + return r.fail("Key %q is not %q but %q:\n"+ + " Expected: %s\n"+ + " Your encoder: %s", + r.Key, wantType, haveType, fmtHashV(want), fmtHashV(have)) } diff --git a/toml.go b/toml.go index e4d049e..e803ee0 100644 --- a/toml.go +++ b/toml.go @@ -135,6 +135,5 @@ func isTomlValue(v any) bool { } // fmt %T with "interface {}" replaced with "any", which is far more readable. -func fmtType(t any) string { - return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any") -} +func fmtType(t any) string { return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any") } +func fmtHashV(t any) string { return strings.ReplaceAll(fmt.Sprintf("%#v", t), "interface {}", "any") }