Files
im_server/server/legal_http_test.go
T

66 lines
2.0 KiB
Go

package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestServeLegalDocument(t *testing.T) {
tests := []struct {
path string
title string
}{
{path: "/legal/user-terms", title: "讯工捷使软件服务协议"},
{path: "/legal/privacy-policy", title: "讯工捷使隐私政策"},
}
for _, tc := range tests {
t.Run(tc.path, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
rec := httptest.NewRecorder()
serveLegalDocument(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d body=%s", rec.Code, rec.Body.String())
}
if got := rec.Header().Get("Content-Type"); got != "text/html; charset=utf-8" {
t.Fatalf("content type: got %q", got)
}
if rec.Header().Get("ETag") == "" {
t.Fatal("missing ETag")
}
if !strings.Contains(rec.Body.String(), "<title>"+tc.title+"</title>") ||
!strings.Contains(rec.Body.String(), "<meta name=\"viewport\"") {
t.Fatal("legal page is missing title or mobile viewport")
}
})
}
}
func TestServeLegalDocumentConditionalHead(t *testing.T) {
getReq := httptest.NewRequest(http.MethodGet, "/legal/user-terms", nil)
getRec := httptest.NewRecorder()
serveLegalDocument(getRec, getReq)
headReq := httptest.NewRequest(http.MethodHead, "/legal/user-terms", nil)
headReq.Header.Set("If-None-Match", getRec.Header().Get("ETag"))
headRec := httptest.NewRecorder()
serveLegalDocument(headRec, headReq)
if headRec.Code != http.StatusNotModified || headRec.Body.Len() != 0 {
t.Fatalf("conditional HEAD: status=%d body=%q", headRec.Code, headRec.Body.String())
}
}
func TestLegalDocumentDoesNotRequireAPIKey(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/legal/user-terms", serveLegalDocument)
handler := withIMHTTPProtocol("/v1/im/", mux)
req := httptest.NewRequest(http.MethodGet, "/legal/user-terms", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("public legal page was blocked: status=%d body=%s", rec.Code, rec.Body.String())
}
}