subscription_test.go
⎇
Raw
1package server
2
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "net/url"
8 "strings"
9 "testing"
10)
11
12// postForm posts an application/x-www-form-urlencoded body to the router.
13func postForm(router http.Handler, path string, form url.Values) *httptest.ResponseRecorder {
14 req := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
15 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
16 w := httptest.NewRecorder()
17 router.ServeHTTP(w, req)
18 return w
19}
20
21func TestSubscriptionsPageRenders(t *testing.T) {
22 srv, _, cleanup := setupTestServer(t)
23 defer cleanup()
24
25 req := httptest.NewRequest("GET", "/subscriptions", nil)
26 w := httptest.NewRecorder()
27 srv.Router().ServeHTTP(w, req)
28 if w.Code != http.StatusOK {
29 body, _ := io.ReadAll(w.Body)
30 t.Fatalf("expected 200, got %d: %s", w.Code, body)
31 }
32 if !strings.Contains(w.Body.String(), "Create Subscription") {
33 t.Error("subscriptions page missing create form")
34 }
35}
36
37func TestCreateSubscriptionLifecycle(t *testing.T) {
38 srv, _, cleanup := setupTestServer(t)
39 defer cleanup()
40 router := srv.Router()
41
42 // Valid create redirects (303) and persists.
43 w := postForm(router, "/subscriptions", url.Values{
44 "name": {"My Sub"},
45 "url": {"https://example.com/playlist"},
46 "output_dir": {"subscriptions/mine"},
47 "refresh_mode": {"overwrite"},
48 "schedule_kind": {"daily"},
49 })
50 if w.Code != http.StatusSeeOther {
51 t.Fatalf("create: expected 303, got %d", w.Code)
52 }
53
54 // It now appears on the listing with its details.
55 req := httptest.NewRequest("GET", "/subscriptions", nil)
56 lw := httptest.NewRecorder()
57 router.ServeHTTP(lw, req)
58 body := lw.Body.String()
59 for _, want := range []string{"My Sub", "subscriptions/mine", "Next run:"} {
60 if !strings.Contains(body, want) {
61 t.Errorf("listing missing %q", want)
62 }
63 }
64}
65
66func TestCreateSubscriptionValidation(t *testing.T) {
67 srv, _, cleanup := setupTestServer(t)
68 defer cleanup()
69 router := srv.Router()
70
71 // Missing output_dir is rejected.
72 w := postForm(router, "/subscriptions", url.Values{
73 "url": {"https://example.com/x"},
74 "schedule_kind": {"daily"},
75 "output_dir": {""},
76 })
77 if w.Code != http.StatusBadRequest {
78 t.Errorf("empty output_dir: expected 400, got %d", w.Code)
79 }
80
81 // Invalid custom cron is rejected.
82 w = postForm(router, "/subscriptions", url.Values{
83 "url": {"https://example.com/x"},
84 "output_dir": {"foo"},
85 "schedule_kind": {"cron"},
86 "cron_expr": {"definitely not cron"},
87 })
88 if w.Code != http.StatusBadRequest {
89 t.Errorf("bad cron: expected 400, got %d", w.Code)
90 }
91}
92