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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main

import (
	"database/sql"
	"errors"
	"path/filepath"
	"testing"
)

// The service unit points at a state directory that may not exist yet, so
// opening the database has to create it rather than failing at startup.
func TestOpenDBCreatesStateDir(t *testing.T) {
	path := filepath.Join(t.TempDir(), "state", "nested", "blocks.sqlite")
	db, err := openDB(path)
	if err != nil {
		t.Fatalf("openDB: %v", err)
	}
	defer db.Close()
	if _, err := createPost(db, "works"); err != nil {
		t.Errorf("database unusable after creating its directory: %v", err)
	}
}

func testDB(t *testing.T) *sql.DB {
	t.Helper()
	db, err := openDB(filepath.Join(t.TempDir(), "test.sqlite"))
	if err != nil {
		t.Fatalf("openDB: %v", err)
	}
	t.Cleanup(func() { db.Close() })
	return db
}

// contents returns the blocks' contents in position order, which is the thing
// every ordering test actually cares about.
func contents(t *testing.T, db *sql.DB, postID int64) []string {
	t.Helper()
	blocks, err := blocksOfPost(db, postID)
	if err != nil {
		t.Fatalf("blocksOfPost: %v", err)
	}
	// The dense-sequence invariant is asserted on every read, so no test can
	// pass while positions have drifted.
	for i, b := range blocks {
		if b.Position != i {
			t.Fatalf("block %d has position %d, want %d — positions are not dense", b.ID, b.Position, i)
		}
	}
	out := make([]string, len(blocks))
	for i, b := range blocks {
		out[i] = b.Content
	}
	return out
}

func equal(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// seed creates a post with markdown blocks "a", "b", "c", … in order.
func seed(t *testing.T, db *sql.DB, n int) (int64, []int64) {
	t.Helper()
	post, err := createPost(db, "Test Post")
	if err != nil {
		t.Fatalf("createPost: %v", err)
	}
	var ids []int64
	for i := 0; i < n; i++ {
		b, err := insertBlock(db, post.ID, i-1, KindMarkdown, string(rune('a'+i)), nil, BlockMeta{})
		if err != nil {
			t.Fatalf("insertBlock: %v", err)
		}
		ids = append(ids, b.ID)
	}
	return post.ID, ids
}

func TestInsertAppendsInOrder(t *testing.T) {
	db := testDB(t)
	postID, _ := seed(t, db, 4)
	if got := contents(t, db, postID); !equal(got, []string{"a", "b", "c", "d"}) {
		t.Errorf("got %v", got)
	}
}

// Dropping a file onto a block inserts after it — the core interaction, so it
// gets a test at every position including both edges.
func TestInsertAfterPosition(t *testing.T) {
	cases := []struct {
		after int
		want  []string
	}{
		{-1, []string{"X", "a", "b", "c"}},
		{0, []string{"a", "X", "b", "c"}},
		{1, []string{"a", "b", "X", "c"}},
		{2, []string{"a", "b", "c", "X"}},
		// Out-of-range values clamp instead of failing, so a stale position
		// from the browser appends rather than erroring.
		{99, []string{"a", "b", "c", "X"}},
		{-99, []string{"X", "a", "b", "c"}},
	}
	for _, c := range cases {
		db := testDB(t)
		postID, _ := seed(t, db, 3)
		if _, err := insertBlock(db, postID, c.after, KindMarkdown, "X", nil, BlockMeta{}); err != nil {
			t.Fatalf("after=%d: %v", c.after, err)
		}
		if got := contents(t, db, postID); !equal(got, c.want) {
			t.Errorf("after=%d: got %v, want %v", c.after, got, c.want)
		}
	}
}

func TestMoveBlock(t *testing.T) {
	cases := []struct {
		name   string
		idx    int
		target int
		want   []string
	}{
		{"first to last", 0, 3, []string{"b", "c", "d", "a"}},
		{"last to first", 3, 0, []string{"d", "a", "b", "c"}},
		{"forward one", 1, 2, []string{"a", "c", "b", "d"}},
		{"backward one", 2, 1, []string{"a", "c", "b", "d"}},
		{"to itself", 2, 2, []string{"a", "b", "c", "d"}},
		{"clamped high", 0, 99, []string{"b", "c", "d", "a"}},
		{"clamped low", 3, -5, []string{"d", "a", "b", "c"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			db := testDB(t)
			postID, ids := seed(t, db, 4)
			if err := moveBlock(db, ids[c.idx], c.target); err != nil {
				t.Fatalf("moveBlock: %v", err)
			}
			if got := contents(t, db, postID); !equal(got, c.want) {
				t.Errorf("got %v, want %v", got, c.want)
			}
		})
	}
}

// Many moves in a row are where a fractional position scheme would eventually
// collide; the renumbering approach must stay exactly dense forever.
func TestRepeatedMovesStayDense(t *testing.T) {
	db := testDB(t)
	postID, ids := seed(t, db, 6)
	for i := 0; i < 200; i++ {
		if err := moveBlock(db, ids[i%len(ids)], i%6); err != nil {
			t.Fatalf("move %d: %v", i, err)
		}
	}
	// contents asserts density; this only checks nothing was lost.
	if got := contents(t, db, postID); len(got) != 6 {
		t.Errorf("got %d blocks, want 6", len(got))
	}
}

func TestDeleteBlockClosesGap(t *testing.T) {
	db := testDB(t)
	postID, ids := seed(t, db, 4)
	if err := deleteBlock(db, ids[1]); err != nil {
		t.Fatalf("deleteBlock: %v", err)
	}
	if got := contents(t, db, postID); !equal(got, []string{"a", "c", "d"}) {
		t.Errorf("got %v", got)
	}
}

func TestUpdateBlock(t *testing.T) {
	db := testDB(t)
	postID, ids := seed(t, db, 2)
	if err := updateBlock(db, ids[0], "updated", BlockMeta{Language: "go"}); err != nil {
		t.Fatalf("updateBlock: %v", err)
	}
	blocks, err := blocksOfPost(db, postID)
	if err != nil {
		t.Fatal(err)
	}
	if blocks[0].Content != "updated" {
		t.Errorf("content = %q", blocks[0].Content)
	}
	if blocks[0].Meta.Language != "go" {
		t.Errorf("meta.Language = %q", blocks[0].Meta.Language)
	}
}

func TestDeletePostCascadesToBlocks(t *testing.T) {
	db := testDB(t)
	postID, _ := seed(t, db, 3)
	if err := deletePost(db, postID); err != nil {
		t.Fatalf("deletePost: %v", err)
	}
	var n int
	if err := db.QueryRow(`SELECT COUNT(*) FROM block WHERE post_id = ?`, postID).Scan(&n); err != nil {
		t.Fatal(err)
	}
	if n != 0 {
		t.Errorf("%d blocks survived the post; ON DELETE CASCADE is not in effect", n)
	}
}

func TestUnknownBlockKindRejected(t *testing.T) {
	db := testDB(t)
	postID, _ := seed(t, db, 1)
	if _, err := insertBlock(db, postID, 0, "spreadsheet", "", nil, BlockMeta{}); err == nil {
		t.Error("expected an error for an unknown block kind")
	}
}

// Inserting into a post that does not exist must be reported as a missing
// post, not as an opaque foreign-key violation.
func TestInsertIntoMissingPost(t *testing.T) {
	db := testDB(t)
	_, err := insertBlock(db, 9999, -1, KindMarkdown, "x", nil, BlockMeta{})
	if !errorIsNotFound(err) {
		t.Errorf("got %v, want ErrNotFound", err)
	}
}

func errorIsNotFound(err error) bool {
	return err != nil && errors.Is(err, ErrNotFound)
}

func TestMissingBlockReportsNotFound(t *testing.T) {
	db := testDB(t)
	for name, err := range map[string]error{
		"update": updateBlock(db, 9999, "x", BlockMeta{}),
		"move":   moveBlock(db, 9999, 0),
		"delete": deleteBlock(db, 9999),
	} {
		if err == nil {
			t.Errorf("%s: expected an error", name)
		}
	}
}

func TestSlugify(t *testing.T) {
	cases := map[string]string{
		"Hello World":            "hello-world",
		"lorri is now in golang": "lorri-is-now-in-golang",
		"  Trim  --  Me  ":       "trim-me",
		"Ünïcödé":                "n-c-d",
		"":                       "untitled",
		"!!!":                    "untitled",
		"C++ & Rust":             "c-rust",
	}
	for in, want := range cases {
		if got := slugify(in); got != want {
			t.Errorf("slugify(%q) = %q, want %q", in, got, want)
		}
	}
}

// Two posts with the same title must not collide, since slug is UNIQUE and a
// second insert would otherwise fail outright.
func TestUniqueSlug(t *testing.T) {
	db := testDB(t)
	for i, want := range []string{"same-title", "same-title-2", "same-title-3"} {
		p, err := createPost(db, "Same Title")
		if err != nil {
			t.Fatalf("post %d: %v", i, err)
		}
		if p.Slug != want {
			t.Errorf("post %d: slug = %q, want %q", i, p.Slug, want)
		}
	}
}

// Renaming a post changes its URL, but editing only the subtitle must not:
// a link that has been shared should keep working while you fix a typo.
func TestSlugStabilityOnUpdate(t *testing.T) {
	db := testDB(t)
	p, err := createPost(db, "Original Title")
	if err != nil {
		t.Fatal(err)
	}
	same, err := updatePost(db, p.ID, "Original Title", "a new subtitle", "draft")
	if err != nil {
		t.Fatal(err)
	}
	if same.Slug != p.Slug {
		t.Errorf("slug changed to %q when only the subtitle changed", same.Slug)
	}
	renamed, err := updatePost(db, p.ID, "A Different Title", "", "draft")
	if err != nil {
		t.Fatal(err)
	}
	if renamed.Slug != "a-different-title" {
		t.Errorf("slug = %q after rename", renamed.Slug)
	}
}