5be7f7f04b
- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
211 lines
7.1 KiB
Go
211 lines
7.1 KiB
Go
package api_test
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
"github.com/misaki/Schedule/server/internal/api"
|
|
"github.com/misaki/Schedule/server/internal/config"
|
|
"github.com/misaki/Schedule/server/internal/model"
|
|
"github.com/misaki/Schedule/server/internal/service"
|
|
"github.com/misaki/Schedule/server/internal/store"
|
|
)
|
|
|
|
func newTestServer(t *testing.T) (*httptest.Server, config.Config) {
|
|
t.Helper()
|
|
st, err := store.Open(filepath.Join(t.TempDir(), "sync.db"))
|
|
if err != nil {
|
|
t.Fatalf("open store: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = st.Close() })
|
|
cfg := config.Config{MaxBatch: 100, TokenPepper: "test-pepper"}
|
|
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
|
svc := service.New(st, cfg)
|
|
server := httptest.NewServer(api.New(svc, cfg, logger).Handler())
|
|
t.Cleanup(server.Close)
|
|
return server, cfg
|
|
}
|
|
|
|
type registered struct {
|
|
DeviceID string `json:"device_id"`
|
|
Token string `json:"token"`
|
|
LatestSeq int64 `json:"latest_seq"`
|
|
}
|
|
|
|
func register(t *testing.T, server *httptest.Server, id, name string) registered {
|
|
t.Helper()
|
|
body := []byte(fmt.Sprintf(`{"device_id":%q,"name":%q}`, id, name))
|
|
response, err := http.Post(server.URL+"/v1/devices/register", "application/json", bytes.NewReader(body))
|
|
if err != nil {
|
|
t.Fatalf("register request: %v", err)
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
data, _ := io.ReadAll(response.Body)
|
|
t.Fatalf("register status=%d body=%s", response.StatusCode, data)
|
|
}
|
|
var result registered
|
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
|
t.Fatalf("decode register: %v", err)
|
|
}
|
|
if result.DeviceID != id || result.Token == "" {
|
|
t.Fatalf("unexpected registration: %+v", result)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func requestJSON(t *testing.T, method, url, token string, body any) (int, []byte) {
|
|
t.Helper()
|
|
var reader io.Reader
|
|
if body != nil {
|
|
data, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatalf("marshal: %v", err)
|
|
}
|
|
reader = bytes.NewReader(data)
|
|
}
|
|
request, err := http.NewRequest(method, url, reader)
|
|
if err != nil {
|
|
t.Fatalf("new request: %v", err)
|
|
}
|
|
if body != nil {
|
|
request.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if token != "" {
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
response, err := http.DefaultClient.Do(request)
|
|
if err != nil {
|
|
t.Fatalf("request: %v", err)
|
|
}
|
|
defer response.Body.Close()
|
|
data, _ := io.ReadAll(response.Body)
|
|
return response.StatusCode, data
|
|
}
|
|
|
|
func TestRegisterAndAuth(t *testing.T) {
|
|
server, _ := newTestServer(t)
|
|
device := register(t, server, "device-1", "Laptop")
|
|
if device.LatestSeq != 0 {
|
|
t.Fatalf("latest seq = %d", device.LatestSeq)
|
|
}
|
|
if status, _ := requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", "", nil); status != http.StatusUnauthorized {
|
|
t.Fatalf("pull without auth status = %d", status)
|
|
}
|
|
if status, _ := requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", device.Token, nil); status != http.StatusOK {
|
|
t.Fatalf("pull with auth status = %d", status)
|
|
}
|
|
}
|
|
|
|
func TestPushPullAndExport(t *testing.T) {
|
|
server, _ := newTestServer(t)
|
|
device1 := register(t, server, "device-1", "Laptop")
|
|
device2 := register(t, server, "device-2", "Desktop")
|
|
|
|
push := map[string]any{
|
|
"changes": []model.ChangeInput{
|
|
{EntityType: "task", EntityID: "task-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"task-1","title":"写周报"}`)},
|
|
{EntityType: "timeblock", EntityID: "block-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"block-1","task_id":"task-1"}`)},
|
|
},
|
|
}
|
|
status, data := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device1.Token, push)
|
|
if status != http.StatusOK {
|
|
t.Fatalf("push status=%d body=%s", status, data)
|
|
}
|
|
var pushed struct {
|
|
Accepted int `json:"accepted"`
|
|
LastSeq int64 `json:"last_seq"`
|
|
}
|
|
if err := json.Unmarshal(data, &pushed); err != nil || pushed.Accepted != 2 || pushed.LastSeq != 2 {
|
|
t.Fatalf("unexpected push: %s err=%v", data, err)
|
|
}
|
|
|
|
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", device2.Token, nil)
|
|
if status != http.StatusOK {
|
|
t.Fatalf("pull status=%d body=%s", status, data)
|
|
}
|
|
var pulled struct {
|
|
Changes []model.Change `json:"changes"`
|
|
LatestSeq int64 `json:"latest_seq"`
|
|
HasMore bool `json:"has_more"`
|
|
}
|
|
if err := json.Unmarshal(data, &pulled); err != nil {
|
|
t.Fatalf("decode pull: %v", err)
|
|
}
|
|
if len(pulled.Changes) != 2 || pulled.LatestSeq != 2 || pulled.HasMore {
|
|
t.Fatalf("unexpected pull: %+v", pulled)
|
|
}
|
|
if pulled.Changes[0].DeviceID != "device-1" || pulled.Changes[0].EntityType != "task" {
|
|
t.Fatalf("unexpected first change: %+v", pulled.Changes[0])
|
|
}
|
|
|
|
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=2", device2.Token, nil)
|
|
if status != http.StatusOK || !strings.Contains(string(data), `"changes":[]`) {
|
|
t.Fatalf("empty pull status=%d body=%s", status, data)
|
|
}
|
|
|
|
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/export", device1.Token, nil)
|
|
if status != http.StatusOK {
|
|
t.Fatalf("export status=%d body=%s", status, data)
|
|
}
|
|
if strings.Contains(string(data), "token_hash") || !strings.Contains(string(data), "task-1") {
|
|
t.Fatalf("unexpected export: %s", data)
|
|
}
|
|
}
|
|
|
|
func TestRejectsInvalidChange(t *testing.T) {
|
|
server, _ := newTestServer(t)
|
|
device := register(t, server, "device-1", "Laptop")
|
|
push := map[string]any{
|
|
"changes": []model.ChangeInput{
|
|
{EntityType: "unknown", EntityID: "x", Op: "upsert", UpdatedAt: time.Now().UTC().Format(time.RFC3339), Payload: json.RawMessage(`{}`)},
|
|
},
|
|
}
|
|
status, _ := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device.Token, push)
|
|
if status != http.StatusBadRequest {
|
|
t.Fatalf("invalid change status = %d", status)
|
|
}
|
|
}
|
|
|
|
func TestWebSocketNotification(t *testing.T) {
|
|
server, _ := newTestServer(t)
|
|
device1 := register(t, server, "device-1", "Laptop")
|
|
device2 := register(t, server, "device-2", "Desktop")
|
|
|
|
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/v1/stream?token=" + device1.Token
|
|
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
|
|
if err != nil {
|
|
t.Fatalf("dial websocket: %v", err)
|
|
}
|
|
defer conn.Close()
|
|
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
|
_, ready, err := conn.ReadMessage()
|
|
if err != nil || !strings.Contains(string(ready), "ready") {
|
|
t.Fatalf("ready message=%s err=%v", ready, err)
|
|
}
|
|
|
|
push := map[string]any{
|
|
"changes": []model.ChangeInput{
|
|
{EntityType: "task", EntityID: "task-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"task-1"}`)},
|
|
},
|
|
}
|
|
status, data := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device2.Token, push)
|
|
if status != http.StatusOK {
|
|
t.Fatalf("push status=%d body=%s", status, data)
|
|
}
|
|
_, notification, err := conn.ReadMessage()
|
|
if err != nil || !strings.Contains(string(notification), `"type":"changes"`) {
|
|
t.Fatalf("notification=%s err=%v", notification, err)
|
|
}
|
|
}
|