From e9ff323f69b4b0889e3333a99a5c4f26c70255c5 Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Sun, 28 Apr 2024 19:34:59 -0400 Subject: [PATCH] Key/value parsing always checks group integrity --- key-value/key-value.go | 24 +++++++++++++++++------- key-value/key-value_test.go | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/key-value/key-value.go b/key-value/key-value.go index 30349df..ab18e93 100644 --- a/key-value/key-value.go +++ b/key-value/key-value.go @@ -64,6 +64,18 @@ func Parse (reader io.Reader) (File, error) { var file = File { } var group Group var specifiedValues map[string] struct { } + + checkGroupIntegrity := func () error { + if group != nil { + for key := range group { + if _, ok := specifiedValues[key]; !ok { + return ErrNoDefaultValue + } + } + } + return nil + } + for { line, err := buffer.ReadString('\n') if errors.Is(err, io.EOF) { break } @@ -78,13 +90,8 @@ func Parse (reader io.Reader) (File, error) { // group header case strings.HasPrefix(line, "["): // check integrity of prev. group - if group != nil { - for key := range group { - if _, ok := specifiedValues[key]; !ok { - return nil, ErrNoDefaultValue - } - } - } + err := checkGroupIntegrity() + if err != nil { return File { }, err } // create new group name, err := parseGroupHeader(line) @@ -122,6 +129,9 @@ func Parse (reader io.Reader) (File, error) { } } + err := checkGroupIntegrity() + if err != nil { return File { }, err } + return file, nil } diff --git a/key-value/key-value_test.go b/key-value/key-value_test.go index 7ba3efa..494d71c 100644 --- a/key-value/key-value_test.go +++ b/key-value/key-value_test.go @@ -52,6 +52,15 @@ func testParseString (test *testing.T, input string, correct File) { } } +func testParseErr (test *testing.T, input string, correct error) { + _, err := Parse(strings.NewReader(input)) + if err != correct { + test.Fatalf ( + "errors are different\n---correct---\n%v\n---got---\n%v\n", + err, correct) + } +} + func testEntry (value string) Entry { entry := newEntry() entry.Value = value @@ -222,3 +231,12 @@ File { }, }, })} + +func TestParseErrNoDefaultValue (test *testing.T) { +testParseErr(test, ` +[Group 0] +Name[xx_XX]=other thing +Name[yy_YY]=another thing +Name[zz_ZZ]=yet another thing +`, ErrNoDefaultValue) +}