forked from marimo-team/marimo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.test.ts
More file actions
468 lines (392 loc) · 13.2 KB
/
Copy pathmodel.test.ts
File metadata and controls
468 lines (392 loc) · 13.2 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/* Copyright 2026 Marimo. All rights reserved. */
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { TestUtils } from "@/__tests__/test-helpers";
import {
getMarimoInternal,
handleWidgetMessage,
Model,
visibleForTesting,
} from "../model";
import type { WidgetModelId } from "../types";
import { BINDING_MANAGER } from "../widget-binding";
const { ModelManager } = visibleForTesting;
// Helper to create typed model IDs for tests
const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
// Mock the request client
const mockSendModelValue = vi.fn().mockResolvedValue(null);
vi.mock("@/core/network/requests", () => ({
getRequestClient: () => ({
sendModelValue: mockSendModelValue,
}),
}));
// Mock isStaticNotebook — default to false (normal mode)
const mockIsStatic = vi.fn().mockReturnValue(false);
vi.mock("@/core/static/static-state", () => ({
isStaticNotebook: () => mockIsStatic(),
}));
// Helper to create a mock MarimoComm
function createMockComm<T>() {
return {
sendUpdate: vi.fn().mockResolvedValue(undefined),
sendCustomMessage: vi.fn().mockResolvedValue(undefined),
};
}
describe("Model", () => {
let model: Model<{ foo: string; bar: number }>;
let mockComm: ReturnType<typeof createMockComm<{ foo: string; bar: number }>>;
beforeEach(() => {
mockComm = createMockComm();
mockSendModelValue.mockClear();
model = new Model({ foo: "test", bar: 123 }, mockComm);
});
describe("public API", () => {
it("should only expose AFM-compliant interface", () => {
// Get all enumerable own properties
const ownProperties = Object.keys(model).toSorted();
// Get prototype methods (excluding constructor)
const prototypeMethods = Object.getOwnPropertyNames(
Object.getPrototypeOf(model),
)
.filter((name) => name !== "constructor")
.toSorted();
// Snapshot the public API to catch accidental leaks of internal methods
expect({ ownProperties, prototypeMethods }).toMatchInlineSnapshot(`
{
"ownProperties": [
"widget_manager",
],
"prototypeMethods": [
"get",
"off",
"on",
"save_changes",
"send",
"set",
],
}
`);
});
});
describe("get/set", () => {
it("should get values correctly", () => {
expect(model.get("foo")).toBe("test");
expect(model.get("bar")).toBe(123);
});
it("should set values and emit change events", () => {
const callback = vi.fn();
model.on("change:foo", callback);
model.set("foo", "new value");
expect(callback).toHaveBeenCalledWith("new value");
expect(model.get("foo")).toBe("new value");
});
it("should not emit change events for non-subscribed fields", () => {
const callback = vi.fn();
model.on("change:foo", callback);
model.set("bar", 456);
expect(callback).not.toHaveBeenCalled();
});
});
describe("save_changes", () => {
it("should only save dirty fields", () => {
model.set("foo", "new value");
model.set("bar", 456);
model.save_changes();
expect(mockComm.sendUpdate).toHaveBeenCalledWith({
foo: "new value",
bar: 456,
});
});
it("should clear dirty fields after save", () => {
model.set("foo", "new value");
model.save_changes();
expect(mockComm.sendUpdate).toHaveBeenCalledWith({
foo: "new value",
});
model.set("bar", 456);
model.save_changes();
// After clearing, only the newly changed field is sent
expect(mockComm.sendUpdate).toHaveBeenCalledWith({
bar: 456,
});
});
it("should not call sendUpdate when no dirty fields", () => {
model.set("foo", "new value");
model.save_changes();
model.save_changes(); // Second save should not call sendUpdate
expect(mockComm.sendUpdate).toHaveBeenCalledTimes(1);
});
});
describe("event handling", () => {
it("should add and remove event listeners", () => {
const callback = vi.fn();
model.on("change:foo", callback);
model.set("foo", "new value");
expect(callback).toHaveBeenCalledTimes(1);
model.off("change:foo", callback);
model.set("foo", "another value");
expect(callback).toHaveBeenCalledTimes(1);
});
it("should remove all listeners when no event name provided", () => {
const callback1 = vi.fn();
const callback2 = vi.fn();
model.on("change:foo", callback1);
model.on("change:bar", callback2);
model.off();
model.set("foo", "new value");
model.set("bar", 456);
expect(callback1).not.toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled();
});
it("should remove all listeners for specific event", () => {
const callback1 = vi.fn();
const callback2 = vi.fn();
model.on("change:foo", callback1);
model.on("change:foo", callback2);
model.off("change:foo");
model.set("foo", "new value");
expect(callback1).not.toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled();
});
});
describe("send", () => {
it("should send message and handle callbacks", async () => {
const callback = vi.fn();
await model.send({ test: true }, callback);
expect(mockComm.sendCustomMessage).toHaveBeenCalledWith(
{ test: true },
[],
);
expect(callback).toHaveBeenCalled();
});
it("should convert buffers to DataViews", async () => {
const buffer = new ArrayBuffer(8);
await model.send({ test: true }, undefined, [buffer]);
expect(mockComm.sendCustomMessage).toHaveBeenCalledWith({ test: true }, [
expect.any(DataView),
]);
});
});
describe("widget_manager", () => {
const childModelId = asModelId("test-id");
const childModel = new Model({ foo: "test" }, createMockComm());
const manager = new ModelManager(10);
let previousModelManager = Model._modelManager;
beforeAll(() => {
previousModelManager = Model._modelManager;
manager.set(childModelId, childModel);
Model._modelManager = manager;
});
afterAll(() => {
manager.delete(childModelId);
Model._modelManager = previousModelManager;
});
it("should throw error when accessing a model that is not registered", async () => {
await expect(
model.widget_manager.get_model(asModelId("random-id")),
).rejects.toThrow("Model not found for key: random-id");
});
it("should return the registered model", async () => {
expect(await model.widget_manager.get_model(childModelId)).toBe(
childModel,
);
});
});
describe("updateAndEmitDiffs", () => {
it("should only update and emit for changed values", () => {
const callback = vi.fn();
model.on("change:foo", callback);
getMarimoInternal(model).updateAndEmitDiffs({ foo: "test", bar: 456 });
expect(callback).not.toHaveBeenCalled(); // foo didn't change
expect(model.get("bar")).toBe(456);
});
it("should update and emit for deep changes", () => {
const modelWithObject = new Model<{ foo: { nested: string } }>(
{ foo: { nested: "test" } },
createMockComm(),
);
const callback = vi.fn();
modelWithObject.on("change:foo", callback);
getMarimoInternal(modelWithObject).updateAndEmitDiffs({
foo: { nested: "changed" },
});
expect(callback).toHaveBeenCalledTimes(1);
});
it("should emit change event for any changes", async () => {
const callback = vi.fn();
model.on("change", callback);
getMarimoInternal(model).updateAndEmitDiffs({ foo: "changed", bar: 456 });
await TestUtils.nextTick(); // flush
expect(callback).toHaveBeenCalledTimes(1);
});
});
describe("reemitState", () => {
it("should emit change events for current values without state changes", async () => {
const onFoo = vi.fn();
const onBar = vi.fn();
const onAny = vi.fn();
model.on("change:foo", onFoo);
model.on("change:bar", onBar);
model.on("change", onAny);
getMarimoInternal(model).reemitState();
await TestUtils.nextTick();
expect(onFoo).toHaveBeenCalledWith("test");
expect(onBar).toHaveBeenCalledWith(123);
expect(onAny).toHaveBeenCalledTimes(1);
});
});
describe("emitCustomMessage", () => {
it("should handle custom messages", () => {
const callback = vi.fn();
model.on("msg:custom", callback);
const content = { type: "test" };
getMarimoInternal(model).emitCustomMessage({
method: "custom",
content,
});
expect(callback).toHaveBeenCalledWith(content, []);
});
it("should handle custom messages with buffers", () => {
const callback = vi.fn();
model.on("msg:custom", callback);
const content = { type: "test" };
const buffer = new DataView(new ArrayBuffer(8));
getMarimoInternal(model).emitCustomMessage(
{
method: "custom",
content,
},
[buffer],
);
expect(callback).toHaveBeenCalledWith(content, [buffer]);
});
});
});
describe("ModelManager", () => {
let modelManager = new ModelManager(50);
const testId = asModelId("test-id");
beforeEach(() => {
// Clear the model manager before each test
modelManager = new ModelManager(50);
mockSendModelValue.mockClear();
});
it("should set and get models", async () => {
const model = new Model({ count: 0 }, createMockComm());
modelManager.set(testId, model);
const retrievedModel = await modelManager.get(testId);
expect(retrievedModel).toBe(model);
});
it("should handle model not found", async () => {
await expect(modelManager.get(asModelId("non-existent"))).rejects.toThrow(
"Model not found for key: non-existent",
);
});
it("should delete models", async () => {
const model = new Model({ count: 0 }, createMockComm());
modelManager.set(testId, model);
modelManager.delete(testId);
await expect(modelManager.get(testId)).rejects.toThrow();
});
it("should handle widget messages", async () => {
await handleWidgetMessage(modelManager, {
model_id: testId,
message: {
method: "open",
state: { count: 0 },
buffer_paths: [],
buffers: [],
},
});
const model = await modelManager.get(testId);
expect(model.get("count")).toBe(0);
await handleWidgetMessage(modelManager, {
model_id: testId,
message: {
method: "update",
state: { count: 1 },
buffer_paths: [],
buffers: [],
},
});
expect(model.get("count")).toBe(1);
});
it("should handle custom messages", async () => {
const model = new Model({ count: 0 }, createMockComm());
const callback = vi.fn();
model.on("msg:custom", callback);
modelManager.set(testId, model);
await handleWidgetMessage(modelManager, {
model_id: testId,
message: { method: "custom", content: { count: 1 }, buffers: [] },
});
expect(callback).toHaveBeenCalledWith({ count: 1 }, []);
});
it("should handle close messages", async () => {
const model = new Model({ count: 0 }, createMockComm());
modelManager.set(testId, model);
await handleWidgetMessage(modelManager, {
model_id: testId,
message: { method: "close" },
});
await expect(modelManager.get(testId)).rejects.toThrow();
});
it("should destroy binding on close message", async () => {
const model = new Model({ count: 0 }, createMockComm());
modelManager.set(testId, model);
// Create a binding for this model
BINDING_MANAGER.getOrCreate(testId);
expect(BINDING_MANAGER.has(testId)).toBe(true);
await handleWidgetMessage(modelManager, {
model_id: testId,
message: { method: "close" },
});
expect(BINDING_MANAGER.has(testId)).toBe(false);
});
describe("static mode", () => {
beforeEach(() => {
mockIsStatic.mockReturnValue(true);
});
afterAll(() => {
mockIsStatic.mockReturnValue(false);
});
it("should create model with no-op comm in static mode", async () => {
await handleWidgetMessage(modelManager, {
model_id: testId,
message: {
method: "open",
state: { count: 42 },
buffer_paths: [],
buffers: [],
},
});
const model = await modelManager.get(testId);
expect(model.get("count")).toBe(42);
// save_changes should not call the real request client
model.set("count", 100);
model.save_changes();
expect(mockSendModelValue).not.toHaveBeenCalled();
});
it("should not throw on send in static mode", async () => {
await handleWidgetMessage(modelManager, {
model_id: testId,
message: {
method: "open",
state: { count: 0 },
buffer_paths: [],
buffers: [],
},
});
const model = await modelManager.get(testId);
// send() should silently no-op
await expect(model.send({ test: true })).resolves.toBeUndefined();
expect(mockSendModelValue).not.toHaveBeenCalled();
});
});
});