-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathunit.test.ts
More file actions
292 lines (266 loc) · 9.67 KB
/
Copy pathunit.test.ts
File metadata and controls
292 lines (266 loc) · 9.67 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import {
createExecutionContext,
runDurableObjectAlarm,
runInDurableObject,
} from "cloudflare:test";
import { env, RpcStub } from "cloudflare:workers";
import { describe, it, onTestFinished } from "vitest";
import TestDefaultEntrypoint, { TestObject } from "../src";
import { Counter } from "../src/counter";
describe("named entrypoints", () => {
it("dispatches fetch request to named ExportedHandler", async ({
expect,
}) => {
const response = await env.TEST_NAMED_HANDLER.fetch("https://example.com");
expect(await response.json()).toMatchObject({
ctxWaitUntil: "function",
method: "GET",
source: "testNamedHandler",
url: "https://example.com/",
});
});
it("dispatches fetch request to named WorkerEntrypoint", async ({
expect,
}) => {
const response = await env.TEST_NAMED_ENTRYPOINT.fetch(
"https://example.com"
);
expect(await response.json()).toMatchObject({
ctxWaitUntil: "function",
method: "GET",
source: "TestNamedEntrypoint",
url: "https://example.com/",
});
});
it("calls method with rpc", async ({ expect }) => {
const result = await env.TEST_NAMED_ENTRYPOINT.ping();
expect(result).toBe("pong");
});
it("receives RpcTarget over RPC", async ({ expect }) => {
const result = await env.TEST_NAMED_ENTRYPOINT.getCounter();
expect(await result.value).toBe(0);
result.increment();
result.increment();
expect(await result.value).toBe(2);
const counter2 = result.clone();
counter2.increment();
expect(await counter2.value).toBe(3);
expect(await result.value).toBe(2);
});
it("receives plain objects over RPC", async ({ expect }) => {
const result = await env.TEST_NAMED_ENTRYPOINT.getCounter();
result.increment();
expect(await result.asObject()).toMatchObject({ val: 1 });
});
});
describe("Durable Object", () => {
const orderingAttempts = 5;
const orderingCalls = 100;
function expectedOrderingLog() {
return Array.from({ length: orderingCalls }, (_, i) => `call-${i}`);
}
function orderingTargetName(prefix: string, attempt: number) {
return `${prefix}-${crypto.randomUUID()}-${attempt}`;
}
it("dispatches fetch request", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
const response = await stub.fetch("https://example.com");
expect(await response.json()).toMatchObject({
ctxWaitUntil: "function",
method: "GET",
source: "TestObject",
url: "https://example.com/",
});
});
it("increments count and allows direct/rpc access to instance/storage", async ({
expect,
}) => {
// Check sending request directly to instance
const id = env.TEST_OBJECT.idFromName("/path");
const stub = env.TEST_OBJECT.get(id);
const result = await runInDurableObject(stub, (instance: TestObject) => {
expect(instance).toBeInstanceOf(TestObject); // Exact same class as import
return instance.increment(1);
});
expect(result).toBe(1);
// Check direct access to properties and storage
await runInDurableObject(stub, async (instance: TestObject, state) => {
expect(instance.value).toBe(1);
expect(await state.storage.get<number>("count")).toBe(1);
});
// Check calling method over RPC
expect(await stub.increment(3)).toBe(4);
// Check accessing property over RPC
expect(await stub.value).toBe(4);
});
it("dispatches RPC methods from proxy-returning Durable Objects", async ({
expect,
}) => {
const id = env.PROXIED_TEST_OBJECT.newUniqueId();
const stub = env.PROXIED_TEST_OBJECT.get(id);
expect(await stub.readPrivateValue()).toBe("private value");
});
it("rejects instance overrides of prototype methods", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
await expect(
async () => await stub.overriddenPrototypeMethod()
).rejects.toThrowErrorMatchingInlineSnapshot(
`[TypeError: The RPC receiver does not implement the method "overriddenPrototypeMethod".]`
);
});
it("immediately executes alarm", async ({ expect }) => {
// Schedule alarm by directly calling method over RPC
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
await stub.increment(3);
await stub.scheduleReset(60_000);
// Check counter has non-zero value
expect(await stub.value).toBe(3);
// Immediately execute the alarm to reset the counter
let ran = await runDurableObjectAlarm(stub);
expect(ran).toBe(true); // ...as there was an alarm scheduled
// Check counter value was reset
expect(await stub.value).toBe(0);
});
it("cannot access instance properties or methods", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
await expect(async () => await stub.instanceProperty).rejects
.toThrowErrorMatchingInlineSnapshot(`
[TypeError: The RPC receiver's prototype does not implement "instanceProperty", but the receiver instance does.
Only properties and methods defined on the prototype can be accessed over RPC.
Ensure properties are declared like \`get instanceProperty() { ... }\` instead of \`instanceProperty = ...\`,
and methods are declared like \`instanceProperty() { ... }\` instead of \`instanceProperty = () => { ... }\`.]
`);
});
it("cannot access non-existent properties or methods", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
await expect(
// @ts-expect-error intentionally testing incorrect types
async () => await stub.nonExistentProperty
).rejects.toThrowErrorMatchingInlineSnapshot(
`[TypeError: The RPC receiver does not implement "nonExistentProperty".]`
);
});
it("receives RpcTarget over RPC", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
using result = await stub.getCounter();
expect(await result.value).toBe(0);
await result.increment();
await result.increment();
expect(await result.value).toBe(2);
// TODO: Improve RPC types so this casting isn't required
using counter2 = (await result.clone()) as unknown as Counter & Disposable;
await counter2.increment();
expect(await counter2.value).toBe(3);
expect(await result.value).toBe(2);
});
it("receives plain objects over RPC", async ({ expect }) => {
const id = env.TEST_OBJECT.newUniqueId();
const stub = env.TEST_OBJECT.get(id);
using result = await stub.getObject();
expect(result).toMatchObject({ hello: "world" });
});
// Regression repro for https://github.com/cloudflare/workers-sdk/issues/13433.
it("preserves same-type RPC call order", async ({ expect }) => {
for (let attempt = 0; attempt < orderingAttempts; attempt++) {
const id = env.TEST_OBJECT.idFromName(
orderingTargetName("ordering", attempt)
);
const stub = env.TEST_OBJECT.get(id);
const promises: Promise<void>[] = [];
for (let i = 0; i < orderingCalls; i++) {
promises.push(stub.record(`call-${i}`));
}
await Promise.all(promises);
expect(await stub.getLog()).toEqual(expectedOrderingLog());
}
});
it("preserves same-type RPC call order after prewarming instance", async ({
expect,
}) => {
for (let attempt = 0; attempt < orderingAttempts; attempt++) {
const id = env.TEST_OBJECT.idFromName(
orderingTargetName("prewarmed-ordering", attempt)
);
const stub = env.TEST_OBJECT.get(id);
await stub.getLog();
const promises: Promise<void>[] = [];
for (let i = 0; i < orderingCalls; i++) {
promises.push(stub.record(`call-${i}`));
}
await Promise.all(promises);
expect(await stub.getLog()).toEqual(expectedOrderingLog());
}
});
it("preserves same-type RPC call order from a WorkerEntrypoint caller", async ({
expect,
}) => {
for (let attempt = 0; attempt < orderingAttempts; attempt++) {
expect(
await env.TEST_NAMED_ENTRYPOINT.recordFromWorkerEntrypoint(
orderingTargetName("worker-entrypoint-ordering", attempt),
orderingCalls
)
).toEqual(expectedOrderingLog());
}
});
it("preserves same-type RPC call order from a Durable Object caller", async ({
expect,
}) => {
for (let attempt = 0; attempt < orderingAttempts; attempt++) {
const id = env.TEST_OBJECT.idFromName(
orderingTargetName("do-caller", attempt)
);
const stub = env.TEST_OBJECT.get(id);
expect(
await stub.recordFromDurableObject(
orderingTargetName("do-caller-ordering", attempt),
orderingCalls
)
).toEqual(expectedOrderingLog());
}
});
});
// Regression: https://github.com/cloudflare/workers-sdk/issues/7077
// Fixed in workerd by https://github.com/cloudflare/workerd/pull/3782
it("can construct a WorkerEntrypoint with mocked env", async ({ expect }) => {
const data = new Map<string, string>([["mocked-key", "mocked-value"]]);
const mockedKv = new Proxy(env.KV_NAMESPACE, {
get: (target, prop, receiver) =>
prop === "get"
? async (key: string) => data.get(key) ?? null
: Reflect.get(target, prop, receiver),
});
const ctx = createExecutionContext();
const worker = new TestDefaultEntrypoint(ctx, {
...env,
KV_NAMESPACE: mockedKv,
});
expect(await worker.read("mocked-key")).toBe("mocked-value");
});
describe("counter", () => {
it("increments count", ({ expect }) => {
const counter = new Counter(3);
expect(counter.increment()).toBe(4);
expect(counter.increment(2)).toBe(6);
expect(counter.value).toBe(6);
});
it("clones counters", ({ expect }) => {
const counter = new Counter(3);
const clone = counter.clone();
expect(counter.increment()).toBe(4);
expect(clone.value).toBe(3);
});
it("calls methods with loopback rpc and pipelining", async ({ expect }) => {
const stub = new RpcStub(new Counter(1));
// TODO(soon): replace with `using` when supported
onTestFinished(() => stub[Symbol.dispose]());
const result = await stub.clone().increment(3);
expect(result).toBe(4);
});
});