From 3760527218e88facbdec630f834b184f3c17a45c Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Sat, 13 Mar 2021 23:42:38 -0500 Subject: [PATCH] Unmarshal tests --- internal/unmarshaler/targets.go | 6 ++ internal/unmarshaler/unmarshaler_test.go | 96 ++++++++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/internal/unmarshaler/targets.go b/internal/unmarshaler/targets.go index daff6bb..a0e2fd1 100644 --- a/internal/unmarshaler/targets.go +++ b/internal/unmarshaler/targets.go @@ -100,6 +100,12 @@ func scope(v reflect.Value, name string) (target, error) { switch v.Kind() { case reflect.Struct: return scopeStruct(v, name) + case reflect.Interface: + if v.IsNil() { + panic("not implemented") // TODO + } else { + return scope(v.Elem(), name) + } default: panic(fmt.Errorf("can't scope on a %s", v.Kind())) } diff --git a/internal/unmarshaler/unmarshaler_test.go b/internal/unmarshaler/unmarshaler_test.go index 1759299..900514c 100644 --- a/internal/unmarshaler/unmarshaler_test.go +++ b/internal/unmarshaler/unmarshaler_test.go @@ -9,6 +9,102 @@ import ( "github.com/pelletier/go-toml/v2/internal/ast" ) +func TestUnmarshal(t *testing.T) { + type test struct { + target interface{} + expected interface{} + } + examples := []struct { + desc string + input string + gen func() test + }{ + { + desc: "kv string", + input: `A = "foo"`, + gen: func() test { + type doc struct { + A string + } + return test{ + &doc{}, + &doc{A: "foo"}, + } + }, + }, + { + desc: "string array", + input: `A = ["foo", "bar"]`, + gen: func() test { + type doc struct { + A []string + } + return test{ + &doc{}, + &doc{A: []string{"foo", "bar"}}, + } + }, + }, + { + desc: "inline table", + input: `Name = {First = "hello", Last = "world"}`, + gen: func() test { + type name struct { + First string + Last string + } + type doc struct { + Name name + } + return test{ + &doc{}, + &doc{Name: name{ + First: "hello", + Last: "world", + }}, + } + }, + }, + { + desc: "inline table inside array", + input: `Names = [{First = "hello", Last = "world"}, {First = "ab", Last = "cd"}]`, + gen: func() test { + type name struct { + First string + Last string + } + type doc struct { + Names []name + } + return test{ + &doc{}, + &doc{ + Names: []name{ + { + First: "hello", + Last: "world", + }, + { + First: "ab", + Last: "cd", + }, + }, + }, + } + }, + }, + } + + for _, e := range examples { + t.Run(e.desc, func(t *testing.T) { + test := e.gen() + err := Unmarshal([]byte(e.input), test.target) + require.NoError(t, err) + assert.Equal(t, test.expected, test.target) + }) + } +} + func TestFromAst_KV(t *testing.T) { root := ast.Root{ ast.Node{