From 74fc87dcfaa8a65c14c0ef6fe88b6df02f2e90cb Mon Sep 17 00:00:00 2001
From: xengineering <me@xengineering.eu>
Date: Mon, 4 Mar 2024 20:39:17 +0100
Subject: model: Implement Stringer interface for Recipe

This allows to print a recipe with a fmt.Printf() call more easily:

	fmt.Printf("%s\n", recipe)

This is also used for better error output in unit tests with t.Fatalf().

The Stringer interface is implemented with the JSON package because an
indented version of a recipe is a useful string representation.
---
 model/recipe.go      | 6 ++++++
 model/recipe_test.go | 8 +++++---
 2 files changed, 11 insertions(+), 3 deletions(-)

(limited to 'model')

diff --git a/model/recipe.go b/model/recipe.go
index ce16ee4..b9830e6 100644
--- a/model/recipe.go
+++ b/model/recipe.go
@@ -2,6 +2,7 @@ package model
 
 import (
 	"database/sql"
+	"encoding/json"
 	"errors"
 	"fmt"
 	"time"
@@ -17,6 +18,11 @@ type Recipe struct {
 	LastChanged string `json:"last_changed"`
 }
 
+func (r Recipe) String() string {
+	b, _ := json.MarshalIndent(r, "", "    ")
+	return string(b)
+}
+
 func (r *Recipe) Touch() {
 	now := time.Now().Unix()
 	r.LastChanged = fmt.Sprint(now)
diff --git a/model/recipe_test.go b/model/recipe_test.go
index 0057a3d..55041a6 100644
--- a/model/recipe_test.go
+++ b/model/recipe_test.go
@@ -30,7 +30,8 @@ func TestRecipeCrud(t *testing.T) {
 	}
 
 	if !reflect.DeepEqual(original, readback) {
-		t.Fatalf("Recipes did not match after create / read cycle")
+		t.Fatalf("Recipes did not match after create / read cycle:\n"+
+			"Before: %s\nAfter: %s\n", original, readback)
 	}
 
 	update.Id = original.Id
@@ -46,8 +47,9 @@ func TestRecipeCrud(t *testing.T) {
 		t.Fatalf("Failed to read back updated recipe: %v\n", err)
 	}
 
-	if !reflect.DeepEqual(updated, update) {
-		t.Fatalf("Recipes did not match after update / read cycle")
+	if !reflect.DeepEqual(update, updated) {
+		t.Fatalf("Recipes did not match after update / read cycle:\n"+
+			"Update: %s\nUpdated: %s\n", update, updated)
 	}
 
 	if reflect.DeepEqual(updated, original) {
-- 
cgit v1.2.3-70-g09d2