summaryrefslogtreecommitdiff
path: root/internal/feed/feed_test.go
blob: a529e6f608f6277906b18a415a0977432c654d4e (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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package feed

import (
	"encoding/xml"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func writeFiles(t *testing.T, names ...string) string {
	t.Helper()
	dir := t.TempDir()
	for i, n := range names {
		// Distinct sizes so enclosure length is verifiably per-file.
		body := strings.Repeat("x", 100+i)
		if err := os.WriteFile(filepath.Join(dir, n), []byte(body), 0o644); err != nil {
			t.Fatalf("writing %s: %v", n, err)
		}
	}
	return dir
}

func build(t *testing.T, dir string, opts ...func(*Options)) *RSS {
	t.Helper()
	o := Options{
		Dir:     dir,
		BaseURL: "https://example.com/audio/",
		Title:   "Personal Physics Lectures",
		Epoch:   time.Date(2020, time.March, 1, 12, 0, 0, 0, time.UTC),
	}
	for _, f := range opts {
		f(&o)
	}
	r, err := Build(o, nil)
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	return r
}

func TestParseName(t *testing.T) {
	cases := []struct {
		in    string
		track int
		title string
	}{
		{"01 - The Law of Gravitation.mp3", 1, "The Law of Gravitation"},
		{"07 - Seeking New Laws.mp3", 7, "Seeking New Laws"},
		{"10 - Probability & Uncertainty.mp3", 10, "Probability & Uncertainty"},
		{"3 - Short Prefix.mp3", 3, "Short Prefix"},
		{"04 – En Dash Separator.mp3", 4, "En Dash Separator"},
		{"No Number Here.mp3", 0, "No Number Here"},
		{"  Padded Name  .mp3", 0, "Padded Name"},
	}
	for _, c := range cases {
		track, title := ParseName(c.in)
		if track != c.track || title != c.title {
			t.Errorf("ParseName(%q) = (%d, %q), want (%d, %q)", c.in, track, title, c.track, c.title)
		}
	}
}

// Filenames routinely contain spaces and ampersands. Pasting them into the
// enclosure URL unescaped produces both an invalid URL and invalid XML — the
// single most likely way a hand-rolled feed fails to load at all.
func TestEnclosureURL_EscapesFilenames(t *testing.T) {
	got, err := EnclosureURL("https://example.com/audio/", "10 - Probability & Uncertainty.mp3")
	if err != nil {
		t.Fatalf("EnclosureURL: %v", err)
	}
	if strings.ContainsAny(got, " ") {
		t.Errorf("URL still contains a raw space: %q", got)
	}
	for _, want := range []string{"%20", "&"} {
		_ = want
	}
	if !strings.Contains(got, "10%20-%20Probability") {
		t.Errorf("spaces not percent-encoded: %q", got)
	}
	if !strings.HasPrefix(got, "https://example.com/audio/") {
		t.Errorf("base URL mangled: %q", got)
	}
}

func TestEnclosureURL_HandlesMissingTrailingSlash(t *testing.T) {
	got, err := EnclosureURL("https://example.com/audio", "01 - One.mp3")
	if err != nil {
		t.Fatalf("EnclosureURL: %v", err)
	}
	if !strings.Contains(got, "/audio/01") {
		t.Errorf("expected a separator to be inserted, got %q", got)
	}
}

func TestEnclosureURL_RejectsBadBase(t *testing.T) {
	for _, bad := range []string{"", "not-a-url", "/just/a/path"} {
		if _, err := EnclosureURL(bad, "a.mp3"); err == nil {
			t.Errorf("EnclosureURL(%q) should have failed", bad)
		}
	}
}

// Zero-padding is a convention, not a guarantee. Ordering has to come from the
// parsed track number, or a series with ten or more parts plays 1, 10, 2.
func TestBuild_OrdersByTrackNumberNotFilename(t *testing.T) {
	dir := writeFiles(t,
		"1 - One.mp3",
		"10 - Ten.mp3",
		"2 - Two.mp3",
	)
	r := build(t, dir)

	var titles []string
	for _, it := range r.Channel.Items {
		titles = append(titles, it.Title)
	}
	want := []string{"One", "Two", "Ten"}
	for i := range want {
		if titles[i] != want[i] {
			t.Fatalf("order = %v, want %v", titles, want)
		}
	}
}

// Files with no track number should not displace the numbered sequence.
func TestBuild_UntrackedFilesSortLast(t *testing.T) {
	dir := writeFiles(t, "Intro.mp3", "01 - One.mp3", "02 - Two.mp3")
	r := build(t, dir)
	last := r.Channel.Items[len(r.Channel.Items)-1]
	if last.Title != "Intro" {
		t.Errorf("last item = %q, want the untracked Intro", last.Title)
	}
}

// Anything that is not audio must be ignored, including the .part files an
// interrupted download leaves behind and any cover art.
func TestBuild_IgnoresNonAudio(t *testing.T) {
	dir := writeFiles(t,
		"01 - One.mp3",
		"cover.jpg",
		"02 - Two.mp3.part",
		"notes.txt",
	)
	r := build(t, dir)
	if len(r.Channel.Items) != 1 {
		var got []string
		for _, i := range r.Channel.Items {
			got = append(got, i.Title)
		}
		t.Errorf("got %d items %v, want only the mp3", len(r.Channel.Items), got)
	}
}

func TestBuild_EnclosureLengthIsTheFileSize(t *testing.T) {
	dir := writeFiles(t, "01 - One.mp3")
	info, err := os.Stat(filepath.Join(dir, "01 - One.mp3"))
	if err != nil {
		t.Fatal(err)
	}
	r := build(t, dir)
	if got := r.Channel.Items[0].Enclosure.Length; got != info.Size() {
		t.Errorf("Length = %d, want %d", got, info.Size())
	}
}

// Every item needs a distinct, increasing date or clients are free to order
// the series however they like.
func TestBuild_PubDatesAreDistinctAndAscending(t *testing.T) {
	dir := writeFiles(t, "01 - One.mp3", "02 - Two.mp3", "03 - Three.mp3")
	r := build(t, dir)

	var prev time.Time
	for i, it := range r.Channel.Items {
		got, err := time.Parse(time.RFC1123Z, it.PubDate)
		if err != nil {
			t.Fatalf("item %d has an unparseable pubDate %q: %v", i, it.PubDate, err)
		}
		if i > 0 && !got.After(prev) {
			t.Errorf("item %d pubDate %v is not after the previous %v", i, got, prev)
		}
		prev = got
	}
}

func TestBuild_EpisodeNumbersFollowTracks(t *testing.T) {
	dir := writeFiles(t, "01 - One.mp3", "02 - Two.mp3")
	r := build(t, dir)
	for i, want := range []int{1, 2} {
		if r.Channel.Items[i].Episode != want {
			t.Errorf("item %d episode = %d, want %d", i, r.Channel.Items[i].Episode, want)
		}
	}
}

// A lecture course must be presented oldest-first; the default for a podcast
// is newest-first, which would start the listener at the final lecture.
func TestBuild_MarkedAsSerial(t *testing.T) {
	r := build(t, writeFiles(t, "01 - One.mp3"))
	if r.Channel.ITunesType != "serial" {
		t.Errorf("itunes:type = %q, want serial", r.Channel.ITunesType)
	}
}

func TestBuild_RequiresATitle(t *testing.T) {
	_, err := Build(Options{Dir: t.TempDir(), BaseURL: "https://e.com/"}, nil)
	if err == nil {
		t.Error("expected an error when no feed title is given")
	}
}

// A missing directory must be an error, not an empty feed that looks like a
// working setup with nothing in it.
func TestBuild_MissingDirectoryIsAnError(t *testing.T) {
	_, err := Build(Options{
		Dir: filepath.Join(t.TempDir(), "nope"), BaseURL: "https://e.com/", Title: "T",
	}, nil)
	if err == nil {
		t.Error("expected an error for a missing directory")
	}
}

func TestBuild_ChannelHasRequiredElements(t *testing.T) {
	r := build(t, writeFiles(t, "01 - One.mp3"))
	if r.Channel.Title == "" {
		t.Error("channel title is empty")
	}
	if r.Channel.Description == "" {
		t.Error("channel description is empty — many clients reject a feed without one")
	}
	if r.Channel.Link == "" {
		t.Error("channel link is empty")
	}
}

// ID3 tags, when present, are better than a filename guess.
func TestBuild_PrefersTagsOverFilenames(t *testing.T) {
	dir := writeFiles(t, "01 - filename title.mp3")
	r, err := Build(Options{
		Dir: dir, BaseURL: "https://example.com/a/", Title: "T",
	}, func(string) (string, int, bool) {
		return "Tagged Title", 5, true
	})
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	if r.Channel.Items[0].Title != "Tagged Title" {
		t.Errorf("title = %q, want the tag value", r.Channel.Items[0].Title)
	}
	if r.Channel.Items[0].Episode != 5 {
		t.Errorf("episode = %d, want the tag track", r.Channel.Items[0].Episode)
	}
}

// A tag reader that finds nothing must not blank out the filename-derived title.
func TestBuild_FallsBackWhenTagsAreAbsent(t *testing.T) {
	dir := writeFiles(t, "01 - Filename Title.mp3")
	r, err := Build(Options{Dir: dir, BaseURL: "https://e.com/a/", Title: "T"},
		func(string) (string, int, bool) { return "", 0, false })
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	if r.Channel.Items[0].Title != "Filename Title" {
		t.Errorf("title = %q, want the filename fallback", r.Channel.Items[0].Title)
	}
}

// The whole document must be well-formed and round-trip through a parser —
// this is what a podcast client does first, and the thing most likely to fail
// on unescaped content.
func TestMarshal_ProducesParseableXML(t *testing.T) {
	dir := writeFiles(t, "10 - Probability & Uncertainty.mp3", "01 - One <thing>.mp3")
	r := build(t, dir)

	out, err := Marshal(r)
	if err != nil {
		t.Fatalf("Marshal: %v", err)
	}
	if !strings.HasPrefix(string(out), xml.Header) {
		t.Error("missing XML declaration")
	}

	var parsed struct {
		Channel struct {
			Title string `xml:"title"`
			Items []struct {
				Title     string `xml:"title"`
				Enclosure struct {
					URL    string `xml:"url,attr"`
					Length int64  `xml:"length,attr"`
				} `xml:"enclosure"`
			} `xml:"item"`
		} `xml:"channel"`
	}
	if err := xml.Unmarshal(out, &parsed); err != nil {
		t.Fatalf("generated feed does not parse: %v\n%s", err, out)
	}
	if len(parsed.Channel.Items) != 2 {
		t.Fatalf("parsed %d items, want 2", len(parsed.Channel.Items))
	}
	for _, it := range parsed.Channel.Items {
		if it.Enclosure.URL == "" {
			t.Error("an item has no enclosure URL")
		}
		if it.Enclosure.Length == 0 {
			t.Error("an item has a zero enclosure length")
		}
	}
}

// The original hand-rolled struct had a field with no xml tag, which the
// marshaller emitted as a stray <EnclosureURL> element. Guard against any
// element leaking in that a reader would not expect.
func TestMarshal_NoStrayElements(t *testing.T) {
	out, err := Marshal(build(t, writeFiles(t, "01 - One.mp3")))
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(string(out), "EnclosureURL") {
		t.Error("stray EnclosureURL element in output")
	}
	if strings.Contains(string(out), "XMLName") {
		t.Error("stray XMLName element in output")
	}
}

func TestMarshal_GUIDIsNotAPermalink(t *testing.T) {
	out, _ := Marshal(build(t, writeFiles(t, "01 - One.mp3")))
	if !strings.Contains(string(out), `isPermaLink="false"`) {
		t.Error(`guid should carry isPermaLink="false"; it is not a URL`)
	}
}

func TestBuild_EmptyDirectoryProducesAValidEmptyFeed(t *testing.T) {
	r := build(t, t.TempDir())
	if len(r.Channel.Items) != 0 {
		t.Errorf("got %d items, want 0", len(r.Channel.Items))
	}
	if _, err := Marshal(r); err != nil {
		t.Errorf("an empty feed should still marshal: %v", err)
	}
}