From 4d3c81d85a0ffa407ab7585576ff7f045798e7cb Mon Sep 17 00:00:00 2001 From: Erik Winter Date: Wed, 25 Dec 2024 11:16:12 +0100 Subject: [PATCH] json marshaling item --- item/item.go | 8 +++++ item/item_test.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 item/item_test.go diff --git a/item/item.go b/item/item.go index 10d3cc8..af1b379 100644 --- a/item/item.go +++ b/item/item.go @@ -4,6 +4,7 @@ import ( "encoding/json" "time" + "github.com/google/go-cmp/cmp" "github.com/google/uuid" ) @@ -68,3 +69,10 @@ func NewItem(k Kind, body string) Item { Body: body, } } + +func ItemDiff(exp, got Item) string { + expJSON, _ := json.Marshal(exp) + actJSON, _ := json.Marshal(got) + + return cmp.Diff(string(expJSON), string(actJSON)) +} diff --git a/item/item_test.go b/item/item_test.go new file mode 100644 index 0000000..f23f95c --- /dev/null +++ b/item/item_test.go @@ -0,0 +1,83 @@ +package item_test + +import ( + "bytes" + "encoding/json" + "testing" + "time" + + "go-mod.ewintr.nl/planner/item" +) + +func TestItemJSON(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + item item.Item + expJSON string + }{ + { + name: "minimal", + item: item.Item{ + ID: "a", + Kind: item.KindTask, + Body: `{"title":"title"}`, + }, + expJSON: `{ + "recurrer": "", + "id": "a", + "kind": "task", + "updated": "0001-01-01T00:00:00Z", + "deleted": false, + "date": "", + "recurNext": "", + "body": "{\"title\":\"title\"}" +}`, + }, + { + name: "full", + item: item.Item{ + ID: "a", + Kind: item.KindTask, + Updated: time.Date(2024, 12, 25, 11, 9, 0, 0, time.UTC), + Deleted: true, + Date: item.NewDate(2024, 12, 26), + Recurrer: item.NewRecurrer("2024-12-25, daily"), + RecurNext: item.NewDateFromString("2024-12-30"), + Body: `{"title":"title"}`, + }, + expJSON: `{ + "recurrer": "2024-12-25, daily", + "id": "a", + "kind": "task", + "updated": "2024-12-25T11:09:00Z", + "deleted": true, + "date": "2024-12-26", + "recurNext": "2024-12-30", + "body": "{\"title\":\"title\"}" +}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + actJSON, err := json.Marshal(tc.item) + if err != nil { + t.Errorf("exp nil, got %v", err) + } + expJSON := bytes.NewBuffer([]byte(``)) + if err := json.Compact(expJSON, []byte(tc.expJSON)); err != nil { + t.Errorf("exp nil, got %v", err) + } + if expJSON.String() != string(actJSON) { + t.Errorf("exp %v, got %v", expJSON.String(), string(actJSON)) + } + var actItem item.Item + if err := json.Unmarshal(actJSON, &actItem); err != nil { + t.Errorf("exp nil, got %v", err) + } + if diff := item.ItemDiff(tc.item, actItem); diff != "" { + t.Errorf("(+exp, -got)%s\n", diff) + } + }) + } +}