more robust tests

This commit is contained in:
David 2022-05-22 21:31:23 -04:00
parent 51e27879c3
commit ad0b0099d1
2 changed files with 28 additions and 9 deletions

View File

@ -39,15 +39,19 @@ func (i *Index) Page(key string) (*Page, error) {
curr, rest, found := strings.Cut(key, "/") curr, rest, found := strings.Cut(key, "/")
page, pageok := i.Pages[curr] page, pageok := i.Pages[curr]
child, childok := i.Children[curr] child, childok := i.Children[curr]
// no trailing slash and doesn't exist
if !found && !pageok { if !found && !pageok {
return &Page{}, ErrPageNotFound return &Page{}, ErrPageNotFound
} }
// trailing slash, exists as page
if rest == "" && pageok { if rest == "" && pageok {
return &page, nil return &page, nil
} }
// neither page nor child
if !childok { if !childok {
return &Page{}, ErrPageNotFound return &Page{}, ErrPageNotFound
} }
// recurse
return (&child).Page(rest) return (&child).Page(rest)
} }
@ -64,22 +68,27 @@ func (i *Index) Save(key string, page *Page) error {
if key[0] == '/' { // strip leading slash if key[0] == '/' { // strip leading slash
key = key[1:] key = key[1:]
} }
// init maps if not yet created
if i.Pages == nil { if i.Pages == nil {
i.Pages = map[string]Page{} i.Pages = map[string]Page{}
} }
if i.Children == nil { if i.Children == nil {
i.Children = map[string]Index{} i.Children = map[string]Index{}
} }
// save as page
curr, rest, _ := strings.Cut(key, "/") curr, rest, _ := strings.Cut(key, "/")
if rest == "" { if rest == "" {
i.Pages[curr] = *page i.Pages[curr] = *page
} else { return nil
}
// recurse and save in child
children := i.Children[curr] children := i.Children[curr]
err := (&children).Save(rest, page) err := (&children).Save(rest, page)
if err != nil { if err != nil {
return err return err
} }
i.Children[curr] = children i.Children[curr] = children
}
return nil return nil
} }

View File

@ -155,7 +155,17 @@ func TestPage(t *testing.T) {
func TestSave(t *testing.T) { func TestSave(t *testing.T) {
i := &Index{} i := &Index{}
err := i.Save("foo", &Page{Title: "fooroot"}) err := i.Save("/", &Page{Title: "invalid"})
if err == nil {
t.Logf("expected err, received nil")
}
_, err = i.Page("/")
if err == nil {
t.Logf("expected err, received nil")
t.Fail()
}
err = i.Save("foo", &Page{Title: "fooroot"})
if err != nil { if err != nil {
t.Logf("expected no err, received %v", err) t.Logf("expected no err, received %v", err)
} }
@ -169,7 +179,7 @@ func TestSave(t *testing.T) {
t.Fail() t.Fail()
} }
err = i.Save("foo/", &Page{Title: "fooroot2"}) err = i.Save("/foo/", &Page{Title: "fooroot2"})
if err != nil { if err != nil {
t.Logf("expected no err, received %v", err) t.Logf("expected no err, received %v", err)
} }