test pttodo.NewRootFromFile accepts both []Todo and Root
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package pttodo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
@@ -13,6 +14,10 @@ type Root struct {
|
||||
}
|
||||
|
||||
func NewRootFromFile(p string) (Root, error) {
|
||||
if b, err := os.ReadFile(p); err == nil && len(bytes.TrimSpace(b)) == 0 {
|
||||
return Root{}, nil
|
||||
}
|
||||
|
||||
f, err := os.Open(p)
|
||||
if os.IsNotExist(err) {
|
||||
return Root{}, nil
|
||||
@@ -24,7 +29,11 @@ func NewRootFromFile(p string) (Root, error) {
|
||||
|
||||
var result Root
|
||||
if err := yaml.NewDecoder(f).Decode(&result); err != nil {
|
||||
return Root{}, err
|
||||
todos, err2 := NewTodosFromFile(p)
|
||||
if err2 != nil {
|
||||
return Root{}, err
|
||||
}
|
||||
result.Todo = todos
|
||||
}
|
||||
|
||||
result.AutoMove()
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -180,3 +182,54 @@ done:
|
||||
t.Fatalf("want\n\t%q, got\n\t%q", want, string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootFromFile(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
given string
|
||||
want Root
|
||||
}{
|
||||
"empty": {},
|
||||
"happy": {
|
||||
given: `{"todo":["a", "b"],"scheduled":["c"], "done":[{"todo": "d"}]}`,
|
||||
want: Root{
|
||||
Todo: []Todo{
|
||||
Todo{Todo: "a"},
|
||||
Todo{Todo: "b"},
|
||||
},
|
||||
Scheduled: []Todo{
|
||||
Todo{Todo: "c"},
|
||||
},
|
||||
Done: []Todo{
|
||||
Todo{Todo: "d"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"todos": {
|
||||
given: `["a", {"todo": "b"}]`,
|
||||
want: Root{
|
||||
Todo: []Todo{
|
||||
{Todo: "a"},
|
||||
{Todo: "b"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for name, d := range cases {
|
||||
c := d
|
||||
t.Run(name, func(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
p := path.Join(d, "input.yaml")
|
||||
if err := os.WriteFile(p, []byte(c.given), os.ModePerm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := NewRootFromFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmt.Sprintf("%+v", got) != fmt.Sprintf("%+v", c.want) {
|
||||
t.Errorf("want\n\t%+v, got\n\t%+v", c.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user