From 1c1c7acc1c85302dfe0c9f64457882c1253c8c5c Mon Sep 17 00:00:00 2001 From: tphilippeau-tower <44652880+tphilippeau-tower@users.noreply.github.com> Date: Fri, 12 Nov 2021 08:40:34 -0500 Subject: [PATCH] Fix creation of default section (#301) --- file.go | 5 +++-- file_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/file.go b/file.go index b96d172..1345918 100644 --- a/file.go +++ b/file.go @@ -168,8 +168,9 @@ func (f *File) SectionsByName(name string) ([]*Section, error) { func (f *File) Section(name string) *Section { sec, err := f.GetSection(name) if err != nil { - // Note: It's OK here because the only possible error is empty section name, - // but if it's empty, this piece of code won't be executed. + if name == "" { + name = DefaultSection + } sec, _ = f.NewSection(name) return sec } diff --git a/file_test.go b/file_test.go index 3081e99..3b43b0a 100644 --- a/file_test.go +++ b/file_test.go @@ -18,6 +18,7 @@ import ( "bytes" "io/ioutil" "runtime" + "sort" "testing" "github.com/stretchr/testify/assert" @@ -264,6 +265,33 @@ VERSION = v1`)) assert.Equal(t, "ini", f.Section("").Key("name").String()) assert.Equal(t, "v1", f.Section("").Key("version").String()) }) + + Convey("Get section after deletion", t, func() { + f, err := ini.Load([]byte(` +[RANDOM] +`)) + So(f, ShouldNotBeNil) + So(err, ShouldBeNil) + sectionNames := f.SectionStrings() + sort.Strings(sectionNames) + So(sectionNames, ShouldResemble, []string{ini.DefaultSection, "RANDOM"}) + + for _, currentSection := range sectionNames { + f.DeleteSection(currentSection) + } + Convey("Section recreated", func() { + for sectionParam, expectedSectionName := range map[string]string{ + "": ini.DefaultSection, + "RANDOM": "RANDOM", + } { + sec := f.Section(sectionParam) + So(sec, ShouldNotBeNil) + So(sec.Name(), ShouldEqual, expectedSectionName) + } + }) + + }) + } func TestFile_Sections(t *testing.T) {