Debian Codegraph @

testing/web-platform/tests/resources/chromium/mock-idle-detection.js

raw
1 import {IdleManager, IdleManagerError, IdleManagerReceiver} from '/gen/third_party/blink/public/mojom/idle/idle_manager.mojom.m.js';
2
3 /**
4 * This is a testing framework that enables us to test the user idle detection
5 * by intercepting the connection between the renderer and the browser and
6 * exposing a mocking API for tests.
7 *
8 * Usage:
9 *
10 * 1) Include <script src="mock.js"></script> in your file.
11 * 2) Set expectations
12 * expect(addMonitor).andReturn((threshold, monitorPtr, callback) => {
13 * // mock behavior
14 * })
15 * 3) Call navigator.idle.query()
16 *
17 * The mocking API is blink agnostic and is designed such that other engines
18 * could implement it too. Here are the symbols that are exposed to tests:
19 *
20 * - function addMonitor(): the main/only function that can be mocked.
21 * - function expect(): the main/only function that enables us to mock it.
22 * - function close(): disconnects the interceptor.
23 * - enum UserIdleState {IDLE, ACTIVE}: blink agnostic constants.
24 * - enum ScreenIdleState {LOCKED, UNLOCKED}: blink agnostic constants.
25 */
26
27 class FakeIdleMonitor {
28 addMonitor(threshold, monitorPtr, callback) {
29 return this.handler.addMonitor(threshold, monitorPtr);
30 }
31 setHandler(handler) {
32 this.handler = handler;
33 return this;
34 }
35 setBinding(binding) {
36 this.binding = binding;
37 return this;
38 }
39 close() {
40 this.binding.$.close();
41 }
42 }
43
44 self.IdleDetectorError = {};
45
46 self.addMonitor = function addMonitor(threshold, monitorPtr, callback) {
47 throw new Error("expected to be overriden by tests");
48 }
49
50 async function close() {
51 interceptor.close();
52 }
53
54 self.expect = function(call) {
55 return {
56 andReturn(callback) {
57 let handler = {};
58 handler[call.name] = callback;
59 interceptor.setHandler(handler);
60 }
61 };
62 };
63
64 function intercept() {
65 let result = new FakeIdleMonitor();
66
67 let binding = new IdleManagerReceiver(result);
68 let interceptor = new MojoInterfaceInterceptor(IdleManager.$interfaceName);
69 interceptor.oninterfacerequest = e => binding.$.bindHandle(e.handle);
70 interceptor.start();
71
72 self.IdleDetectorError.SUCCESS = IdleManagerError.kSuccess;
73 self.IdleDetectorError.PERMISSION_DISABLED =
74 IdleManagerError.kPermissionDisabled;
75
76 result.setBinding(binding);
77 return result;
78 }
79
80 const interceptor = intercept();