-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathfakes.js
120 lines (100 loc) · 2.31 KB
/
fakes.js
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
import {Listener} from './utils.js';
async function asyncify(func) {
return new Promise(resolve => setTimeout(() => resolve(func())));
}
class FakeDisk extends Map {
constructor() {
super(...arguments);
this.getter = super.get.bind(this);
this.setter = super.set.bind(this);
this.deleter = super.delete.bind(this);
}
async get(key, cb) {
return asyncify(() => cb(this.getter(key)));
}
async set(key, value, cb) {
return asyncify(() => cb(this.setter(key, value)));
}
async delete(key, cb) {
return asyncify(() => cb(this.deleter(key)));
}
async remove(key, cb) {
return this.delete(key, cb);
}
}
class FakeMessages {
constructor() {
this.funcs = [];
this.messages = [];
}
clear() {
this.funcs = [];
this.messages = [];
}
addListener(func) {
this.funcs.push(func);
}
async sendMessage() {
this.messages.push(Array.from(arguments).slice(0, arguments.length))
for (let func of this.funcs) {
await func(...arguments);
}
}
}
class Port {
constructor(name) {
this.name = name;
this.onMessage = new Listener();
this.onDisconnect = new Listener();
}
setOther(other) {
this.otherPort = other;
}
async disconnect() {
for (let func of this.otherPort.onDisconnect.funcs) {
await func(...arguments);
}
}
async postMessage() {
for (let func of this.otherPort.onMessage.funcs) {
await func(...arguments);
}
}
}
// this should be cleaned up, and probably moved into shim.js or testing_utils.js
function fakePort(name) {
let a = new Port(name), b = new Port(name);
a.setOther(b);
b.setOther(a);
return [a, b];
}
class Connects extends Function {
// returs fake [connect, onConnect]
static create() {
let onConnect = new Connects();
let connect = new Proxy(onConnect, {
apply: function(target, thisArg, argList) {
return target.connect.apply(target, argList);
}
});
return [connect, onConnect];
}
constructor() {
super();
this.funcs = [];
}
addListener(func) {
this.funcs.push(func);
}
clear() {
this.funcs = []
}
connect({name}) {
let [port, otherPort] = fakePort(name);
for (let func of this.funcs) {
func(otherPort);
}
return port;
}
}
export {FakeDisk, FakeMessages, fakePort, Connects};