summaryrefslogtreecommitdiff
path: root/src/post/asset/asset_test.go
blob: 366e6a54618828ad7d88d1b715c6e684384d3d9a (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
package asset

import (
	"bytes"
	"io"
	"testing"

	"dev.mediocregopher.com/mediocre-blog.git/src/post"
	"github.com/stretchr/testify/assert"
)

type testHarness struct {
	store Store
}

func newTestHarness(t *testing.T) *testHarness {

	db := post.NewInMemSQLDB()
	t.Cleanup(func() { db.Close() })

	store := NewStore(db)

	return &testHarness{
		store: store,
	}
}

func (h *testHarness) assertGet(t *testing.T, exp, id string) {
	t.Helper()
	buf := new(bytes.Buffer)
	err := h.store.Get(id, buf)
	assert.NoError(t, err)
	assert.Equal(t, exp, buf.String())
}

func (h *testHarness) assertNotFound(t *testing.T, id string) {
	t.Helper()
	err := h.store.Get(id, io.Discard)
	assert.ErrorIs(t, ErrNotFound, err)
}

func TestStore(t *testing.T) {

	testStore := func(t *testing.T, h *testHarness) {
		t.Helper()

		h.assertNotFound(t, "foo")
		h.assertNotFound(t, "bar")

		err := h.store.Set("foo", bytes.NewBufferString("FOO"))
		assert.NoError(t, err)

		h.assertGet(t, "FOO", "foo")
		h.assertNotFound(t, "bar")

		err = h.store.Set("foo", bytes.NewBufferString("FOOFOO"))
		assert.NoError(t, err)

		h.assertGet(t, "FOOFOO", "foo")
		h.assertNotFound(t, "bar")

		assert.NoError(t, h.store.Delete("foo"))
		h.assertNotFound(t, "foo")
		h.assertNotFound(t, "bar")

		assert.NoError(t, h.store.Delete("bar"))
		h.assertNotFound(t, "foo")
		h.assertNotFound(t, "bar")

		// test list

		ids, err := h.store.List()
		assert.NoError(t, err)
		assert.Empty(t, ids)

		err = h.store.Set("foo", bytes.NewBufferString("FOOFOO"))
		assert.NoError(t, err)
		err = h.store.Set("foo", bytes.NewBufferString("FOOFOO"))
		assert.NoError(t, err)
		err = h.store.Set("bar", bytes.NewBufferString("FOOFOO"))
		assert.NoError(t, err)

		ids, err = h.store.List()
		assert.NoError(t, err)
		assert.Equal(t, []string{"bar", "foo"}, ids)
	}

	t.Run("sql", func(t *testing.T) {
		h := newTestHarness(t)
		testStore(t, h)
	})
}