-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestClientHelpers.js
More file actions
252 lines (220 loc) · 7.51 KB
/
testClientHelpers.js
File metadata and controls
252 lines (220 loc) · 7.51 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
import BosBase, { BaseAuthStore } from "bosbase";
function createFakeToken(expSecondsFromNow = 60) {
const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString(
"base64url",
);
const payload = Buffer.from(
JSON.stringify({
exp: Math.floor(Date.now() / 1000) + expSecondsFromNow,
collectionName: "users",
collectionId: "pbc_123",
id: "rec_test",
}),
).toString("base64url");
return `${header}.${payload}.sig`;
}
async function testFilterHelper() {
console.log("[INFO] Testing pb.filter helper...");
const pb = new BosBase("http://example.com");
const filter = pb.filter(
"name = {:name} && age >= {:age} && meta = {:meta} && created >= {:ts}",
{
name: "O'Connor",
age: 21,
meta: { active: true },
ts: new Date("2024-01-01T12:34:56Z"),
},
);
if (
!filter.includes("name = 'O\\'Connor'") ||
!filter.includes("age >= 21") ||
!filter.includes("meta = '{\"active\":true}'") ||
!filter.includes("created >= '2024-01-01 12:34:56.000Z'")
) {
throw new Error("pb.filter did not escape or format parameters correctly");
}
console.log("[SUCCESS] pb.filter escaped strings, numbers, objects, and dates");
}
async function testHooksAndRequestOptions() {
console.log("[INFO] Testing beforeSend/afterSend hooks...");
const pb = new BosBase("http://api.test.local");
pb.beforeSend = (url, options) => {
const nextHeaders = Object.assign({}, options.headers, {
"X-Test-Token": "hooks",
});
options.headers = nextHeaders;
return { url: `${url}?through=hook`, options };
};
pb.afterSend = (response, data) => {
return Object.assign({}, data, {
statusFromAfterSend: response.status,
seenHeader: response.headers?.["X-Test-Token"],
});
};
const stubFetch = async (url, options) => {
return {
status: 200,
url,
headers: options.headers || {},
json: async () => ({
echoedUrl: url,
headers: options.headers,
method: options.method,
body: options.body,
}),
};
};
const result = await pb.send("/api/demo", {
method: "POST",
body: { hello: "world" },
fetch: stubFetch,
});
if (
result.statusFromAfterSend !== 200 ||
!String(result.echoedUrl || "").includes("through=hook") ||
result.headers["X-Test-Token"] !== "hooks" ||
result.seenHeader !== "hooks"
) {
throw new Error("beforeSend/afterSend hooks did not propagate changes");
}
console.log("[SUCCESS] beforeSend/afterSend hooks applied url and header changes");
}
async function testAutoCancellationAndCancelAll() {
console.log("[INFO] Testing auto cancellation and cancelAllRequests...");
const pb = new BosBase("http://api.test.local");
let fetchCallCount = 0;
const delayedFetch = (url, options) =>
new Promise((resolve, reject) => {
fetchCallCount += 1;
const currentCall = fetchCallCount;
const timer = setTimeout(() => {
resolve({
status: 200,
url,
json: async () => ({ call: currentCall, url }),
});
}, 50);
options.signal?.addEventListener("abort", () => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
});
});
let firstCancelled = false;
const first = pb
.send("/api/cancel-me", { method: "GET", fetch: delayedFetch })
.catch((err) => {
firstCancelled = err?.isAbort === true;
return null;
});
const second = pb.send("/api/cancel-me", { method: "GET", fetch: delayedFetch });
const [, secondResult] = await Promise.all([first, second]);
if (!firstCancelled) {
throw new Error("First duplicate request was not auto-cancelled");
}
if (!secondResult || secondResult.call !== 2) {
throw new Error("Second request did not complete after cancellation");
}
const manualPending = pb
.send("/api/wait", {
method: "GET",
fetch: delayedFetch,
requestKey: "manual_key",
})
.then(() => {
throw new Error("Manual request should have been cancelled");
})
.catch((err) => {
if (!err?.isAbort) {
throw err;
}
});
pb.cancelAllRequests();
await manualPending;
console.log("[SUCCESS] Auto cancellation and cancelAllRequests behave as expected");
}
async function testAuthStoreCookieFlow() {
console.log("[INFO] Testing BaseAuthStore export/load and onChange...");
const store = new BaseAuthStore();
const observed = [];
const unsubscribe = store.onChange((token, record) => {
observed.push({ token, record });
});
const token = createFakeToken(120);
const record = { id: "rec_test", collectionName: "users", email: "demo@example.com" };
store.save(token, record);
const cookie = store.exportToCookie();
if (!cookie.includes("pb_auth=")) {
throw new Error("exportToCookie did not include pb_auth key");
}
const nextStore = new BaseAuthStore();
nextStore.loadFromCookie(cookie);
if (nextStore.token !== token || nextStore.record?.email !== record.email) {
throw new Error("loadFromCookie did not restore auth state");
}
if (!nextStore.isValid) {
throw new Error("Stored token should be treated as valid");
}
store.clear();
unsubscribe();
if (observed.length < 2 || observed[0].token !== token || observed[1].token !== "") {
throw new Error("onChange callbacks did not fire for save/clear");
}
console.log("[SUCCESS] BaseAuthStore cookie round-trip and onChange verified");
}
async function testDeprecatedMethods() {
console.log("[INFO] Testing deprecated Client methods...");
const pb = new BosBase("http://example.com");
// Test deprecated buildUrl() method
if (typeof pb.buildUrl === "function") {
const url1 = pb.buildURL("/api/test");
const url2 = pb.buildUrl("/api/test");
if (url1 === url2) {
console.log("[SUCCESS] Deprecated buildUrl() works and matches buildURL()");
} else {
throw new Error("Deprecated buildUrl() should return same result as buildURL()");
}
} else {
throw new Error("buildUrl() method is not available");
}
// Test deprecated getFileUrl() method
if (typeof pb.getFileUrl === "function") {
const testRecord = {
id: "test123",
collectionId: "col_abc",
image: "test.jpg",
};
const url1 = pb.files.getURL(testRecord, testRecord.image);
const url2 = pb.getFileUrl(testRecord, testRecord.image);
if (url1 === url2) {
console.log("[SUCCESS] Deprecated getFileUrl() works and matches files.getURL()");
} else {
throw new Error("Deprecated getFileUrl() should return same result as files.getURL()");
}
} else {
throw new Error("getFileUrl() method is not available");
}
// Test deprecated baseUrl property (getter/setter)
const originalBaseUrl = pb.baseURL;
pb.baseUrl = "http://new.example.com";
if (pb.baseURL === "http://new.example.com" && pb.baseUrl === "http://new.example.com") {
console.log("[SUCCESS] Deprecated baseUrl property works and matches baseURL");
pb.baseURL = originalBaseUrl; // Restore
} else {
throw new Error("Deprecated baseUrl property should work and match baseURL");
}
}
async function main() {
try {
await testFilterHelper();
await testHooksAndRequestOptions();
await testAutoCancellationAndCancelAll();
await testAuthStoreCookieFlow();
await testDeprecatedMethods();
console.log("\n========== Client helper tests completed ==========");
} catch (error) {
console.error("[ERROR] Client helper test failed:");
console.error(error?.stack || error);
process.exit(1);
}
}
main();