Files
supermarket/internal/web/engines_test.go
T
davidandClaude Opus 5.5 1b2947de7c Phase 9, part 2: one database layer for SQLite and Postgres
db.DB wraps database/sql for either database. The SQL stays SQLite's: on
Postgres each statement's ? become $n and LIKE ignores case as SQLite's
does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds
SQLite's instr, json_extract and two-argument max/min, and a nocase ICU
collation. Needs Postgres 18.

LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON
CONFLICT DO NOTHING, upserts qualify their columns, and three queries
group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test
suite on Postgres, a new schema per test; all tests pass on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:10:44 -07:00

196 lines
9.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package web
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/crm"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
func TestEnginesPage(t *testing.T) {
s, h := newTestServer(t, nil)
key, _ := seo.IndexNowKey(s.DB)
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/"+key+".txt" {
fmt.Fprint(w, key)
return
}
http.NotFound(w, r)
}))
defer site.Close()
b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/GetRankAndTrafficStats":
w.Write([]byte(`{"d":[{"Clicks":12,"Impressions":340,"Date":"/Date(1763337600000)/"}]}`))
case "/GetQueryStats":
w.Write([]byte(`{"d":[]}`))
case "/GetCrawlIssues":
w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404}]}`))
}
}))
defer b.Close()
bingBase = b.URL
defer func() { bingBase = "" }()
var pinged string
in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pinged = r.URL.Path; w.WriteHeader(200) }))
defer in.Close()
seo.IndexNowURL = in.URL
defer func() { seo.IndexNowURL = "https://api.indexnow.org/indexnow" }()
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: site.URL}}})
postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}})
body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String()
for _, want := range []string{key, "the site serves it", "340", "https://us.example/old (404)", "Connect Search Console", "Open the pull request"} {
if !strings.Contains(body, want) {
t.Errorf("page lacks %q", want)
}
}
if rec := postForm(h, "/seo/engines/ping?site=0", nil); rec.Code != http.StatusSeeOther || pinged == "" {
t.Errorf("ping: %d %q", rec.Code, pinged)
}
if body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String(); !strings.Contains(body, "accepted (200)") {
t.Error("the ping isn't listed")
}
}
func TestMarginsForm(t *testing.T) {
s, h := newTestServer(t, nil)
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, status, currency, amount, period_start, product, description)
VALUES ('in_1', 'il_1', 'paid', 'usd', 4900, ?, 'prod_core', '1 × Federated Core (at $49.00 / month)')`, time.Now().Unix())
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Federated Core") || !strings.Contains(body, `placeholder="60"`) {
t.Fatal("the margin table isn't shown")
}
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"55%"}, "margin:prod_core": {"70"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body)
}
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, `name="margin:prod_core" value="70"`) || !strings.Contains(body, `name="default" value="55"`) {
t.Error("the margins weren't saved")
}
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"abc"}}); !strings.Contains(rec.Body.String(), "percentage") {
t.Error("a bad default was accepted")
}
}
func TestMRRPages(t *testing.T) {
s, h := newTestServer(t, nil)
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}'),
('customer', 'cus_a', '', '{"id":"cus_a","name":"Acme","email":"a@acme.example"}')`)
now := time.Now().UTC()
for i := 3; i >= 0; i-- {
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -i, 0)
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), start.Unix(), start.AddDate(0, 1, 0).Unix())
}
body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String()
for _, want := range []string{"$99", "ARR $1,188", "Month by month", "<svg class=\"chart\"", "Cohorts"} {
if !strings.Contains(body, want) {
t.Errorf("metrics lacks %q", want)
}
}
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -3, 0).Format("2006-01")
if body := do(h, http.MethodGet, "/metrics/month/"+first, nil, nil).Body.String(); !strings.Contains(body, "Acme") || !strings.Contains(body, "new") {
t.Errorf("month detail: %s", first)
}
if rec := do(h, http.MethodGet, "/metrics/month/1999-01", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown month: %d", rec.Code)
}
postForm(h, "/metrics/start", url.Values{"month": {first}})
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Counted from "+first) {
t.Error("the start month isn't used")
}
if rec := postForm(h, "/metrics/start", url.Values{"month": {"soon"}}); !strings.Contains(rec.Body.String(), "isn&#39;t a month") {
t.Errorf("bad month: %s", rec.Body)
}
}
func TestCustomersPage(t *testing.T) {
s, h := newTestServer(t, nil)
s.DB.Exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, synced_at) VALUES ('Account', 'a1', 'Acme', '', 'acme.example', '{}', '')`)
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', 'cus_x', 'cus_x', '{"name":"Xco","email":"x@xco.example"}'),
('customer', 'cus_a', 'cus_a', '{"name":"Acme Ltd","email":"pay@acme.example"}')`)
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'in_1', 'cus_x', 'paid', 'usd', '{}'), ('invoice', 'in_2', 'cus_a', 'paid', 'usd', '{}')`)
body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String()
if !strings.Contains(body, "Xco") || strings.Contains(body, "Acme Ltd") {
t.Fatal("the to-fix list should hold only the unmatched customer")
}
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"account"}, "account": {"Acme"}})
if body := do(h, http.MethodGet, "/metrics/customers?show=all", nil, nil).Body.String(); !strings.Contains(body, "Acme <span class=\"muted small\">by you</span>") {
t.Error("the manual match isn't shown")
}
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"auto"}})
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"add"}})
if acts, _ := crm.List(s.DB, 10); len(acts) != 1 || acts[0].Entity != "Account" || acts[0].Fields["website"] != "https://xco.example" {
t.Errorf("queued: %+v", acts)
}
if body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String(); !strings.Contains(body, "queued for the CRM") {
t.Error("the queued Account isn't shown")
}
if rec := postForm(h, "/metrics/customers/bad", url.Values{"do": {"none"}}); rec.Code != http.StatusNotFound {
t.Errorf("bad id: %d", rec.Code)
}
}
func TestSpendPage(t *testing.T) {
_, h := newTestServer(t, nil)
if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"$320"}, "note": {"ads"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("add: %d %s", rec.Code, rec.Body)
}
if rec := postForm(h, "/metrics/spend", url.Values{"csv": {"2026-09,general,1000,tools"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("csv: %d %s", rec.Code, rec.Body)
}
body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String()
for _, want := range []string{"$320", "ads", "$1,000", "General"} {
if !strings.Contains(body, want) {
t.Errorf("spend page lacks %q", want)
}
}
if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"lots"}}); !strings.Contains(rec.Body.String(), "isn&#39;t an amount") {
t.Error("a bad amount was accepted")
}
postForm(h, "/metrics/spend/1/delete", nil)
if body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String(); strings.Contains(body, ">ads<") {
t.Error("the entry wasn't deleted")
}
}
func TestExportAndPublishPages(t *testing.T) {
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}')`)
start := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -2, 0)
for i := 0; i < 3; i++ {
ps := start.AddDate(0, i, 0)
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), ps.Unix(), ps.AddDate(0, 1, 0).Unix())
}
rec := do(h, http.MethodGet, "/metrics/export/mrr.csv", nil, nil)
if rec.Header().Get("Content-Type") != "text/csv; charset=utf-8" || !strings.Contains(rec.Header().Get("Content-Disposition"), "supermarket-mrr-") ||
!strings.HasPrefix(rec.Body.String(), "month,partial,mrr") {
t.Errorf("export: %v %s", rec.Header(), rec.Body)
}
if rec := do(h, http.MethodGet, "/metrics/export/secrets.csv", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown export: %d", rec.Code)
}
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "/metrics/export/mrr.csv") {
t.Error("no download link on Metrics")
}
postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {"/numbers/"}, "title": {"Our numbers"}, "part": {"mrr", "table"}, "do": {"save"}})
body := do(h, http.MethodGet, "/metrics/publish", nil, nil).Body.String()
for _, want := range []string{`value="/numbers/"`, "Monthly recurring revenue:** $99", "| Month | MRR |"} {
if !strings.Contains(body, want) {
t.Errorf("publish page lacks %q", want)
}
}
if rec := postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {""}, "title": {"x"}}); !strings.Contains(rec.Body.String(), "an address and a title") {
t.Error("an empty address was accepted")
}
}