Files
MarketGrid/xyzserver/server_test.go
T
nixevol fe24a88bac feat: 统计页支持一年时段和按日趋势
在线人数在新的有效访问后尽快刷新,历史查询保留一年并画出每日连接数。
2026-09-28 11:08:28 +08:00

533 lines
15 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
)
func flushAndRefresh(t *testing.T, app *App) {
t.Helper()
if err := app.Flush(context.Background()); err != nil {
t.Fatal(err)
}
if err := app.refreshOnline(context.Background()); err != nil {
t.Fatal(err)
}
}
func newTestApp(t *testing.T, now func() time.Time) *App {
t.Helper()
app, err := NewApp(Config{
Listen: "127.0.0.1:0",
DataDir: t.TempDir(),
OnlineMinutes: 15,
}, now)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = app.Close() })
return app
}
func doReq(t *testing.T, method, rawURL, sid, ua string) (int, http.Header, []byte) {
t.Helper()
req, err := http.NewRequest(method, rawURL, nil)
if err != nil {
t.Fatal(err)
}
if sid != "" {
req.AddCookie(&http.Cookie{Name: "sid", Value: sid})
}
if ua != "" {
req.Header.Set("User-Agent", ua)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return res.StatusCode, res.Header.Clone(), body
}
func sidFromSetCookie(h http.Header) string {
raw := h.Get("Set-Cookie")
const p = "sid="
if !strings.HasPrefix(raw, p) {
return ""
}
rest := raw[len(p):]
if i := strings.IndexByte(rest, ';'); i >= 0 {
rest = rest[:i]
}
return rest
}
type onlineJSON struct {
ServerTime string `json:"server_time"`
OnlineMinutes int `json:"online_minutes"`
Total int `json:"total"`
Tables []tableCount `json:"tables"`
}
func getOnline(t *testing.T, base string) onlineJSON {
t.Helper()
res, err := http.Get(base + "/api/online")
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
b, _ := io.ReadAll(res.Body)
t.Fatalf("online %d %s", res.StatusCode, b)
}
if res.Header.Get("Cache-Control") != "no-store" {
t.Fatalf("cache %s", res.Header.Get("Cache-Control"))
}
var body onlineJSON
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
t.Fatal(err)
}
return body
}
func countsOf(tables []tableCount) map[string]int {
out := map[string]int{}
for _, row := range tables {
out[row.Table] = row.Count
}
return out
}
func TestTileCookieAndOnline(t *testing.T) {
baseTime := time.Date(2026, 9, 23, 9, 0, 0, 0, cst)
clock := baseTime
app := newTestApp(t, func() time.Time { return clock })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
ua := "Mozilla/5.0 QGIS/33801/Windows"
code, hdr, body := doReq(t, http.MethodGet, ts.URL+"/tiles/grid/0/0/0.png?foo=1", "", ua)
if code != 200 {
t.Fatalf("status %d", code)
}
if hdr.Get("Content-Type") != "image/png" {
t.Fatalf("type %s", hdr.Get("Content-Type"))
}
if hdr.Get("Cache-Control") != "no-store" {
t.Fatalf("cache %s", hdr.Get("Cache-Control"))
}
if hdr.Get("Content-Length") != strconv.Itoa(len(body)) || !bytes.Equal(body, app.png) {
t.Fatalf("body %d png %d", len(body), len(app.png))
}
setCookie := hdr.Get("Set-Cookie")
if !strings.Contains(setCookie, "Path=/tiles/") || !strings.Contains(setCookie, "Max-Age=31536000") || !strings.Contains(setCookie, "HttpOnly") {
t.Fatalf("set-cookie %s", setCookie)
}
sid := sidFromSetCookie(hdr)
if !validSID(sid) {
t.Fatalf("sid %q", sid)
}
code, hdr, _ = doReq(t, http.MethodGet, ts.URL+"/tiles/grid/31/0/0.png", "", ua)
if code != 404 || hdr.Get("Set-Cookie") != "" {
t.Fatalf("bad z status %d cookie %q", code, hdr.Get("Set-Cookie"))
}
code, hdr, body = doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
if code != 200 || hdr.Get("Set-Cookie") != "" || !bytes.Equal(body, app.png) {
t.Fatalf("grid with cookie status %d cookie %q", code, hdr.Get("Set-Cookie"))
}
code, hdr, body = doReq(t, http.MethodGet, ts.URL+"/tiles/building/1/2/4.png", sid, ua)
if code != 200 || hdr.Get("Set-Cookie") != "" || !bytes.Equal(body, app.png) {
t.Fatalf("building status %d cookie %q", code, hdr.Get("Set-Cookie"))
}
flushAndRefresh(t, app)
online := getOnline(t, ts.URL)
if online.Total != 2 || online.OnlineMinutes != 15 || !strings.Contains(online.ServerTime, "+08:00") {
t.Fatalf("%+v", online)
}
got := countsOf(online.Tables)
if got["grid"] != 1 || got["building"] != 1 || len(got) != 2 {
t.Fatalf("%+v", online.Tables)
}
if online.Tables[0].Table != "building" || online.Tables[1].Table != "grid" {
t.Fatalf("order %+v", online.Tables)
}
var fp, storedSID string
if err := app.store.db.QueryRow(`SELECT sid, fp FROM sessions WHERE sid = ?`, sid).Scan(&storedSID, &fp); err != nil {
t.Fatal(err)
}
if strings.Contains(fp, ua) || strings.Contains(fp, "127.0.0.1") {
t.Fatalf("raw client data stored in fp %s", fp)
}
}
func TestTwoCookiesSameFingerprint(t *testing.T) {
// 只在同一分钟出现一次的会话区间长度是 0,不会把重叠人数抬高。
// 两个会话要算成 2 人,需要各自跨过至少两分钟并且时间重叠。
baseTime := time.Date(2026, 9, 23, 9, 0, 0, 0, cst)
clock := baseTime
app := newTestApp(t, func() time.Time { return clock })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
ua := "Mozilla/5.0 QGIS/33801/Windows"
c1 := strings.Repeat("A", 22)
c2 := strings.Repeat("B", 22)
for _, sid := range []string{c1, c2} {
clock = baseTime
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
clock = baseTime.Add(time.Minute)
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/4.png", sid, ua)
}
flushAndRefresh(t, app)
online := getOnline(t, ts.URL)
if online.Total != 2 || countsOf(online.Tables)["grid"] != 2 {
t.Fatalf("%+v", online)
}
}
func TestSequentialSessionsCountOne(t *testing.T) {
baseTime := time.Date(2026, 9, 23, 8, 0, 0, 0, cst)
clock := baseTime
app := newTestApp(t, func() time.Time { return clock })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
ua := "Mozilla/5.0 QGIS/33801/Windows"
c1 := strings.Repeat("C", 22)
c2 := strings.Repeat("D", 22)
hit := func(at time.Time, sid string) {
t.Helper()
clock = at
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/1/1.png", sid, ua)
}
hit(baseTime, c1)
hit(baseTime.Add(5*time.Minute), c1)
hit(baseTime.Add(15*time.Minute), c2)
hit(baseTime.Add(20*time.Minute), c2)
clock = baseTime.Add(20 * time.Minute)
if err := app.Flush(context.Background()); err != nil {
t.Fatal(err)
}
q := url.Values{}
q.Set("start", baseTime.Format(time.RFC3339))
q.Set("end", baseTime.Add(20*time.Minute).Format(time.RFC3339))
res, err := http.Get(ts.URL + "/api/range?" + q.Encode())
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
b, _ := io.ReadAll(res.Body)
t.Fatalf("range %d %s", res.StatusCode, b)
}
var body rangeResp
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Total != 1 || countsOf(body.Tables)["grid"] != 1 {
t.Fatalf("%+v", body)
}
if !strings.Contains(body.Start, "+08:00") || !strings.Contains(body.End, "+08:00") {
t.Fatalf("times %s %s", body.Start, body.End)
}
}
func TestOnlyQGISOverHTTPSCounted(t *testing.T) {
now := func() time.Time { return time.Date(2026, 9, 23, 16, 0, 0, 0, cst) }
app, err := NewApp(Config{
Listen: "127.0.0.1:0",
DataDir: t.TempDir(),
OnlineMinutes: 15,
TrustProxy: true,
HTTPSOnly: true,
}, now)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = app.Close() })
hit := func(table, ua, proto string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/tiles/"+table+"/1/2/3.png", nil)
req.Header.Set("User-Agent", ua)
if proto != "" {
req.Header.Set("X-Forwarded-Proto", proto)
}
rr := httptest.NewRecorder()
app.Handler().ServeHTTP(rr, req)
if rr.Code != 200 || !bytes.Equal(rr.Body.Bytes(), app.png) {
t.Fatalf("%s: status %d", table, rr.Code)
}
return rr
}
hit("qgis", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "https")
hit("qfield", "Mozilla/5.0 QField/4.2.0 QGIS/34405/Android 14", "https")
hit("plainhttp", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "http")
hit("noproto", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "")
hit("browser", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/99.0 Safari/537.36", "https")
if rr := hit("curl", "curl/8.13.0", "https"); rr.Header().Get("Set-Cookie") == "" {
t.Fatal("uncounted clients still get a cookie")
}
if err := app.Flush(context.Background()); err != nil {
t.Fatal(err)
}
if err := app.refreshOnline(context.Background()); err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
app.Handler().ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/online", nil))
var online onlineJSON
if err := json.Unmarshal(rr.Body.Bytes(), &online); err != nil {
t.Fatal(err)
}
got := countsOf(online.Tables)
if len(got) != 2 || got["qgis"] != 1 || got["qfield"] != 1 {
t.Fatalf("%+v", online.Tables)
}
if app.ignored.Load() != 4 {
t.Fatalf("ignored %d", app.ignored.Load())
}
}
func TestDailySeries(t *testing.T) {
now := time.Date(2026, 9, 23, 12, 0, 0, 0, cst)
app := newTestApp(t, func() time.Time { return now })
d1 := time.Date(2026, 9, 21, 9, 0, 0, 0, cst).Unix() / 60
d2 := time.Date(2026, 9, 22, 9, 0, 0, 0, cst).Unix() / 60
_, err := app.store.WriteBatch(context.Background(), []hitKey{
{minute: d1, table: "grid", sid: "A"},
{minute: d2, table: "grid", sid: "B"},
}, map[string]*sessionAgg{
"A": {fp: "fp", first: d1, last: d1},
"B": {fp: "fp", first: d2, last: d2},
})
if err != nil {
t.Fatal(err)
}
q := url.Values{}
q.Set("start", time.Date(2026, 9, 21, 0, 0, 0, 0, cst).Format(time.RFC3339))
q.Set("end", time.Date(2026, 9, 22, 23, 0, 0, 0, cst).Format(time.RFC3339))
req := httptest.NewRequest(http.MethodGet, "/api/range?"+q.Encode(), nil)
rr := httptest.NewRecorder()
app.Handler().ServeHTTP(rr, req)
if rr.Code != 200 {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
var body rangeResp
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Total != 1 || len(body.Daily) != 2 {
t.Fatalf("%+v", body)
}
if body.Daily[0].Date != "2026-09-21" || body.Daily[0].Count != 1 || body.Daily[1].Date != "2026-09-22" || body.Daily[1].Count != 1 {
t.Fatalf("%+v", body.Daily)
}
}
func TestHeadDoesNotRecord(t *testing.T) {
app := newTestApp(t, func() time.Time { return time.Date(2026, 9, 23, 9, 0, 0, 0, cst) })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
code, hdr, body := doReq(t, http.MethodHead, ts.URL+"/tiles/grid/1/2/3.png", "", "ua")
if code != 200 {
t.Fatalf("status %d", code)
}
if hdr.Get("Cache-Control") != "no-store" || hdr.Get("Content-Type") != "image/png" {
t.Fatalf("headers %v", hdr)
}
if hdr.Get("Content-Length") != strconv.Itoa(len(app.png)) {
t.Fatalf("content-length %s", hdr.Get("Content-Length"))
}
if len(body) != 0 {
t.Fatalf("head body %d", len(body))
}
flushAndRefresh(t, app)
online := getOnline(t, ts.URL)
if online.Total != 0 || len(online.Tables) != 0 {
t.Fatalf("%+v", online)
}
}
func TestOnlineCacheAndEmpty(t *testing.T) {
baseTime := time.Date(2026, 9, 23, 12, 0, 0, 0, cst)
clock := baseTime
app := newTestApp(t, func() time.Time { return clock })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
flushAndRefresh(t, app)
first := getOnline(t, ts.URL)
if first.Total != 0 || first.OnlineMinutes != 15 || len(first.Tables) != 0 {
t.Fatalf("%+v", first)
}
raw, err := http.Get(ts.URL + "/api/online")
if err != nil {
t.Fatal(err)
}
buf, _ := io.ReadAll(raw.Body)
raw.Body.Close()
if !bytes.Contains(buf, []byte(`"tables":[]`)) {
t.Fatalf("tables not empty array: %s", buf)
}
sid := strings.Repeat("E", 22)
ua := "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2"
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
flushAndRefresh(t, app)
warm := getOnline(t, ts.URL)
if warm.Total != 1 || len(warm.Tables) != 1 {
t.Fatalf("%+v", warm)
}
clock = baseTime.Add(15 * time.Second)
doReq(t, http.MethodGet, ts.URL+"/tiles/building/1/2/3.png", sid, ua)
cached := getOnline(t, ts.URL)
if cached.ServerTime != warm.ServerTime || len(cached.Tables) != 1 {
t.Fatalf("served stale snapshot %+v", cached)
}
flushAndRefresh(t, app)
fresh := getOnline(t, ts.URL)
if len(fresh.Tables) != 2 || fresh.Total != 2 {
t.Fatalf("%+v", fresh)
}
}
func warmTime(s string) time.Time {
tm, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
return tm
}
func TestChineseTableAndPages(t *testing.T) {
app := newTestApp(t, func() time.Time { return time.Date(2026, 9, 23, 10, 0, 0, 0, cst) })
ts := httptest.NewServer(app.Handler())
t.Cleanup(ts.Close)
code, hdr, body := doReq(t, http.MethodGet, ts.URL+"/tiles/%E4%B8%9C%E5%8C%BA/12/3/4.png", strings.Repeat("F", 22), "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2")
if code != 200 || hdr.Get("Set-Cookie") != "" {
t.Fatalf("chinese tile %d %s", code, hdr.Get("Set-Cookie"))
}
if !bytes.Equal(body, app.png) {
t.Fatal("png mismatch")
}
flushAndRefresh(t, app)
online := getOnline(t, ts.URL)
if countsOf(online.Tables)["东区"] != 1 {
t.Fatalf("%+v", online)
}
res, err := http.Get(ts.URL + "/healthz")
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 || string(b) != "ok" {
t.Fatalf("health %d %q", res.StatusCode, b)
}
res, err = http.Get(ts.URL + "/")
if err != nil {
t.Fatal(err)
}
b, _ = io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 {
t.Fatal(res.StatusCode)
}
if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
t.Fatalf("content-type %s", ct)
}
if res.Header.Get("Cache-Control") != "no-cache" {
t.Fatal(res.Header.Get("Cache-Control"))
}
html := string(b)
for _, needle := range []string{
"总在线连接",
"cards",
"overflow: auto",
"datetime-local",
"queryRange();",
"1 小时",
"12 小时",
"1 天",
"1 周",
"1 月",
"id=\"chart\"",
"visibilitychange",
"document.hidden",
"textContent",
"5000",
"encodeURIComponent",
} {
if !strings.Contains(html, needle) {
t.Fatalf("page missing %s", needle)
}
}
if strings.Contains(html, "innerHTML") {
t.Fatal("page uses innerHTML")
}
if strings.Contains(html, "复制") {
t.Fatal("page still has copy button")
}
res, err = http.Get(ts.URL + "/no-such")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != 404 {
t.Fatalf("unknown %d", res.StatusCode)
}
}
func TestStatsUnavailable(t *testing.T) {
app := newTestApp(t, time.Now)
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
app.Handler().ServeHTTP(rr, req)
if rr.Code != 200 || rr.Body.String() != "ok" {
t.Fatalf("health before close %d %s", rr.Code, rr.Body)
}
if err := app.store.db.Close(); err != nil {
t.Fatal(err)
}
rr = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/healthz", nil)
app.Handler().ServeHTTP(rr, req)
if rr.Code != 200 || rr.Body.String() != "ok" {
t.Fatalf("health after close %d %s", rr.Code, rr.Body)
}
rr = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/online", nil)
app.Handler().ServeHTTP(rr, req)
if rr.Code != 503 {
t.Fatalf("online %d %s", rr.Code, rr.Body)
}
var body errJSON
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Error != "stats_unavailable" || body.Message != "统计暂时不可用" {
t.Fatalf("%+v", body)
}
}