Repository navigation
Expand file tree
/
Copy pathapi_test.go
More file actions
258 lines (240 loc) · 8.42 KB
/
Copy pathapi_test.go
File metadata and controls
258 lines (240 loc) · 8.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/Microsoft/go-winio"
"github.com/ApolloF/syncer/internal/conflict"
)
type fakeBackend struct {
mu sync.Mutex
fs []apiFolder
synced []string
opened int
}
func (f *fakeBackend) status(context.Context) apiStatus {
return apiStatus{Syncthing: true, Games: len(f.fs)}
}
func (f *fakeBackend) folders(context.Context) ([]apiFolder, error) {
f.mu.Lock()
defer f.mu.Unlock()
return append([]apiFolder(nil), f.fs...), nil
}
func (f *fakeBackend) syncNow(_ context.Context, ids []string) []apiSyncResult {
f.synced = append(f.synced, ids...)
var out []apiSyncResult
for _, id := range ids {
out = append(out, apiSyncResult{ID: id, Done: true, State: "idle"})
}
return out
}
func (f *fakeBackend) backupNow(context.Context, bool) (apiBackupResult, error) {
return apiBackupResult{Started: true, Finished: true, OK: true}, nil
}
func (f *fakeBackend) conflicts(id string) ([]conflict.Conflict, error) {
if id != "a" {
return nil, fmt.Errorf("unknown folder")
}
return []conflict.Conflict{{Rel: "save.dat", Copy: "save.sync-conflict-1.dat"}}, nil
}
func (f *fakeBackend) resolveConflict(string, string, bool) error { return nil }
func (f *fakeBackend) getNewer(context.Context, string) (int, error) { return 2, nil }
func (f *fakeBackend) open() error { f.opened++; return nil }
func (f *fakeBackend) accounts() apiAccounts {
return apiAccounts{Enabled: true, Active: "aaaaaa", Accounts: []apiAccount{{ID: "aaaaaa", Name: "A", Active: true}}}
}
func (f *fakeBackend) switchAccount(_ context.Context, id string) error {
if id != "aaaaaa" {
return fmt.Errorf("unknown account")
}
return nil
}
func (f *fakeBackend) launcherData(_ context.Context, launcher, path string) (apiLauncherData, error) {
if path != `C:\Users\x\AppData\Roaming\Seaglass\Profile` {
return apiLauncherData{}, fmt.Errorf("the folder must be in AppData")
}
return apiLauncherData{ID: "seaglass", Label: launcher, Sync: true, Backup: true, Added: true}, nil
}
type client struct {
t *testing.T
c net.Conn
sc *bufio.Scanner
id int
}
func dial(t *testing.T, name string) *client {
t.Helper()
d := 2 * time.Second
c, err := winio.DialPipe(name, &d)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { c.Close() })
sc := bufio.NewScanner(c)
sc.Buffer(make([]byte, 1<<20), 1<<20)
return &client{t: t, c: c, sc: sc}
}
func (c *client) raw(line string) map[string]any {
c.t.Helper()
_ = c.c.SetDeadline(time.Now().Add(5 * time.Second))
if _, err := c.c.Write([]byte(line + "\n")); err != nil {
c.t.Fatal(err)
}
return c.read()
}
func (c *client) read() map[string]any {
c.t.Helper()
if !c.sc.Scan() {
c.t.Fatalf("no answer: %v", c.sc.Err())
}
var m map[string]any
if err := json.Unmarshal(c.sc.Bytes(), &m); err != nil {
c.t.Fatal(err)
}
return m
}
func (c *client) call(method string, params any) map[string]any {
c.t.Helper()
c.id++
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": params})
return c.raw(string(b))
}
func startTest(t *testing.T, b apiBackend) (string, *apiServer) {
t.Helper()
name := fmt.Sprintf(`\\.\pipe\syncer-test-%d-%d`, os.Getpid(), time.Now().UnixNano())
ln, err := listenAPI(name)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
s := newAPIServer(b, ln, "")
go s.serve()
return name, s
}
func TestAPIBasics(t *testing.T) {
name, _ := startTest(t, &fakeBackend{})
if _, err := listenAPI(name); err == nil {
t.Fatal("a second server on the same pipe must fail")
}
c := dial(t, name)
st := c.call("status", nil)["result"].(map[string]any)
if st["protocol"].(float64) != apiProtocol || st["syncthing"] != true {
t.Errorf("status = %v", st)
}
if e := c.call("nope", nil)["error"].(map[string]any); e["code"].(float64) != rpcMethodNotFound {
t.Errorf("unknown method = %v", e)
}
if e := c.raw("{not json")["error"].(map[string]any); e["code"].(float64) != rpcParseError {
t.Errorf("bad json = %v", e)
}
if e := c.raw(`{"jsonrpc":"1.0","id":1,"method":"status"}`)["error"].(map[string]any); e["code"].(float64) != rpcInvalidRequest {
t.Errorf("wrong version = %v", e)
}
if e := c.call("syncNow", map[string]any{"ids": []string{}})["error"].(map[string]any); e["code"].(float64) != rpcInvalidParams {
t.Errorf("syncNow without ids = %v", e)
}
if e := c.call("conflicts", map[string]any{"id": "zzz"})["error"].(map[string]any); !strings.Contains(e["message"].(string), "unknown") {
t.Errorf("conflicts error = %v", e)
}
// A notification (no id) gets no answer; the next call's answer comes next.
_, _ = c.c.Write([]byte(`{"jsonrpc":"2.0","method":"open"}` + "\n"))
if r := c.call("conflicts", map[string]any{"id": "a"}); r["result"] == nil {
t.Errorf("conflicts = %v", r)
}
}
func TestAPIGameStatus(t *testing.T) {
b := &fakeBackend{fs: []apiFolder{
{ID: "a", Label: "Elden Ring", State: "idle"},
{ID: "b", Label: "Hollow Knight (RUNE saves)", State: "backup-only"},
{ID: "c", Label: "Some Other Game"},
}}
name, _ := startTest(t, b)
c := dial(t, name)
ids := func(r map[string]any) []string {
res := r["result"].(map[string]any)
var out []string
for _, f := range res["folders"].([]any) {
out = append(out, f.(map[string]any)["id"].(string))
}
return out
}
if got := ids(c.call("gameStatus", map[string]any{"title": "ELDEN RING"})); len(got) != 1 || got[0] != "a" {
t.Errorf("by title = %v", got)
}
if got := ids(c.call("gameStatus", map[string]any{"title": "Hollow Knight"})); len(got) != 1 || got[0] != "b" {
t.Errorf("emulator saves = %v", got)
}
if got := ids(c.call("gameStatus", map[string]any{"title": "Unknown"})); len(got) != 0 {
t.Errorf("unknown = %v", got)
}
// A launcher registers its folder names; the folder then finds the game.
c.call("registerGames", map[string]any{"games": []map[string]any{
{"title": "Some Other Game", "dir": `D:\Games\SOG-Repack`},
{"title": "", "dir": `D:\x`},
{"title": "Relative", "dir": `games\x`},
}})
if got := ids(c.call("gameStatus", map[string]any{"dir": `d:\games\sog-repack\`})); len(got) != 1 || got[0] != "c" {
t.Errorf("by registered dir = %v", got)
}
if e := c.call("gameStatus", map[string]any{})["error"]; e == nil {
t.Error("gameStatus without anything must fail")
}
}
func TestAPISubscribe(t *testing.T) {
b := &fakeBackend{fs: []apiFolder{{ID: "a", Label: "Game", State: "idle"}}}
name, _ := startTest(t, b)
c := dial(t, name)
if r := c.call("subscribe", nil); r["result"] != true {
t.Fatalf("subscribe = %v", r)
}
time.Sleep(3500 * time.Millisecond) // first poll records the state
b.mu.Lock()
b.fs[0].State = "syncing"
b.mu.Unlock()
_ = c.c.SetDeadline(time.Now().Add(8 * time.Second))
if m := c.read(); m["method"] != "changed" {
t.Errorf("notification = %v", m)
}
}
func TestTimeoutOf(t *testing.T) {
if timeoutOf(0, time.Second, time.Minute) != time.Second || timeoutOf(999999999, time.Second, time.Minute) != time.Minute {
t.Error("timeoutOf limits")
}
}
func TestAPIAccounts(t *testing.T) {
name, _ := startTest(t, &fakeBackend{})
c := dial(t, name)
r := c.call("accounts", nil)["result"].(map[string]any)
if r["active"] != "aaaaaa" || len(r["accounts"].([]any)) != 1 {
t.Errorf("accounts = %v", r)
}
if e := c.call("switchAccount", map[string]any{})["error"].(map[string]any); e["code"].(float64) != rpcInvalidParams {
t.Errorf("switchAccount without id = %v", e)
}
if e := c.call("switchAccount", map[string]any{"id": "zzzzzz"})["error"].(map[string]any); e["code"].(float64) != rpcFailed {
t.Errorf("unknown account = %v", e)
}
if r := c.call("switchAccount", map[string]any{"id": "aaaaaa"}); r["result"] != true {
t.Errorf("switchAccount = %v", r)
}
}
func TestAPILauncherData(t *testing.T) {
name, _ := startTest(t, &fakeBackend{})
c := dial(t, name)
if e := c.call("launcherData", map[string]any{"launcher": "Seaglass"})["error"].(map[string]any); e["code"].(float64) != rpcInvalidParams {
t.Errorf("launcherData without path = %v", e)
}
if e := c.call("launcherData", map[string]any{"launcher": "Seaglass", "path": `C:\Windows`})["error"].(map[string]any); e["code"].(float64) != rpcFailed {
t.Errorf("launcherData outside AppData = %v", e)
}
r := c.call("launcherData", map[string]any{"launcher": "Seaglass", "path": `C:\Users\x\AppData\Roaming\Seaglass\Profile`})["result"].(map[string]any)
if r["id"] != "seaglass" || r["sync"] != true || r["added"] != true {
t.Errorf("launcherData = %v", r)
}
}