summaryrefslogtreecommitdiff
path: root/model/recipe_test.go
blob: 6bc7b54f3c366e8aeafdcec85d028278ddf25e92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package model

import (
	"database/sql"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"testing"
)

func TestRecipeCrud(t *testing.T) {
	storagePath, err := os.MkdirTemp("", "ceres")
	if err != nil {
		fmt.Println("Error creating temporary directory:", err)
		return
	}
	t.Logf("Storage path: %v\n", storagePath)
	defer os.RemoveAll(storagePath)

	storage := NewStorage(storagePath)

	database, err := OpenDB(filepath.Join(storage.Path, "ceres.sqlite3"))
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		err := database.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()

	err = database.Migrate()
	if err != nil {
		t.Fatal(err)
	}

	err = database.CreateExamples()
	if err != nil {
		t.Fatal(err)
	}

	err = database.Transaction(func(tx *sql.Tx) error {
		var original, readback, update, updated, deleted Recipe

		recipes := RecipeTestData()
		original = recipes[0]
		update = recipes[1]

		err = original.Create(tx)
		if err != nil {
			t.Fatalf("Failed to create test recipe in DB: %v\n", err)
		}

		readback.Id = original.Id
		err = readback.Read(tx)
		if err != nil {
			t.Fatalf("Failed to read test recipe from DB: %v\n", err)
		}

		if !reflect.DeepEqual(original, readback) {
			t.Fatalf("Recipes did not match after create / read cycle:\n"+
				"Before: %s\nAfter: %s\n", original, readback)
		}

		update.Id = original.Id

		err = update.Update(tx)
		if err != nil {
			t.Fatalf("Failed to update recipe: %v\n", err)
		}

		updated.Id = original.Id
		err = updated.Read(tx)
		if err != nil {
			t.Fatalf("Failed to read back updated recipe: %v\n", err)
		}

		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) {
			t.Fatalf("Updated and original recipe match")
		}

		err = updated.Delete(tx)
		if err != nil {
			t.Fatalf("Failed to delete updated recipe: %v\n", err)
		}

		deleted.Id = updated.Id
		err = deleted.Read(tx)
		if err == nil {
			t.Fatalf("Was able to read back deleted recipe")
		}

		return nil
	})
	if err != nil {
		t.Fatalf("Failed to read recipes from database: %s", err)
	}
}