From 6c83f4197d1eb93376f731ac1e24601379636be2 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 31 Dec 2021 16:47:00 -0500 Subject: [PATCH] test marshalling a just-a-string todo returns just-a-string --- pttodo/todo.go | 8 ++++++++ pttodo/todo_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/pttodo/todo.go b/pttodo/todo.go index fdc14b2..e22a769 100644 --- a/pttodo/todo.go +++ b/pttodo/todo.go @@ -16,6 +16,14 @@ func (todo Todo) Triggered() bool { return err == nil && time.Now().After(next) } +func (todo Todo) MarshalYAML() (interface{}, error) { + if todo == (Todo{Todo: todo.Todo}) { + return todo.Todo, nil + } + type Alt Todo + return (Alt)(todo), nil +} + func (todo *Todo) UnmarshalYAML(unmarshal func(interface{}) error) error { *todo = Todo{} if err := unmarshal(&todo.Todo); err == nil { diff --git a/pttodo/todo_test.go b/pttodo/todo_test.go index e1631a5..2320647 100644 --- a/pttodo/todo_test.go +++ b/pttodo/todo_test.go @@ -2,6 +2,7 @@ package pttodo import ( "encoding/json" + "strings" "testing" yaml "gopkg.in/yaml.v2" @@ -82,3 +83,44 @@ todo: } }) } + +func TestMarshalTodo(t *testing.T) { + t.Run(`empty should return ""`, func(t *testing.T) { + var todo Todo + if b, err := yaml.Marshal(Todo{}); err != nil { + t.Fatal(err) + } else if s := string(b); strings.TrimSpace(s) != `""` { + t.Fatalf("%q", s) + } else if err := yaml.Unmarshal(b, &todo); err != nil { + t.Fatal(err) + } else if todo.Todo != "" { + t.Fatal(todo.Todo) + } + }) + + t.Run(`just "a" should return a`, func(t *testing.T) { + var todo Todo + if b, err := yaml.Marshal(Todo{Todo: "a"}); err != nil { + t.Fatal(err) + } else if s := string(b); strings.TrimSpace(s) != `a` { + t.Fatalf("%q", s) + } else if err := yaml.Unmarshal(b, &todo); err != nil { + t.Fatal(err) + } else if todo.Todo != "a" { + t.Fatal(todo.Todo) + } + }) + + t.Run(`struct should return struct`, func(t *testing.T) { + var todo Todo + if b, err := yaml.Marshal(Todo{Todo: "a", Detail: "b"}); err != nil { + t.Fatal(err) + } else if err := yaml.Unmarshal(b, &todo); err != nil { + t.Fatal(err) + } else if todo.Todo != "a" { + t.Fatal(todo.Todo) + } else if todo.Detail != "b" { + t.Fatal(todo.Detail) + } + }) +}