Repository navigation
Expand file tree
/
Copy pathscript.test.js
More file actions
212 lines (201 loc) · 7.73 KB
/
Copy pathscript.test.js
File metadata and controls
212 lines (201 loc) · 7.73 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
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const vm = require('node:vm');
const script = fs.readFileSync(path.join(__dirname, 'script.js'), 'utf8');
function uiElement() {
return {
children: [],
style: {},
listeners: {},
append(...items) { this.children.push(...items); },
addEventListener(name, callback) { this.listeners[name] = callback; },
setAttribute() {},
focus() {},
remove() {}
};
}
async function fixture(variant, options = {}) {
const id = '12345';
const location = {
pathname: '/' + variant.toLowerCase() + '/',
href: 'https://web.telegram.org/' + variant.toLowerCase() + '/#' + id,
hash: options.initialOtherChat ? '#999' : '#' + id
};
const messages = [message('1', false, 'Привет', variant)];
let rowPresent = options.initialRows !== false;
let rowSelected = !options.initialOtherChat;
let mousedowns = 0;
let tickCallback = null;
if (options.mediaLast) {
const media = message('2', false, '', variant);
media.querySelector = () => null;
messages.push(media);
}
const input = {
textContent: options.draft || '',
focus() {}
};
let sends = 0;
let requests = 0;
const link = {
getAttribute(name) { return name === 'href' ? '#' + id : null; },
click() { location.hash = '#' + id; rowSelected = true; },
dispatchEvent() { mousedowns++; location.hash = '#' + id; rowSelected = true; }
};
const row = {
classList: { contains(name) { return name === 'private' || (name === 'selected' && rowSelected); } },
matches() { return false; },
getAttribute() { return null; },
querySelector(selector) {
if (selector === 'a[href]') return link;
if (selector.includes('chat-badge-transition') || selector.includes('dialog-subtitle-badge.unread')) {
return options.unread ? { textContent: '1' } : null;
}
if (selector.includes('last-message-summary') || selector.includes('dialog-subtitle-span-last')) return { textContent: 'Привет' };
return null;
}
};
const sendButton = {
disabled: false,
click() {
sends++;
messages.push(message('2', true, input.textContent, variant));
input.textContent = '';
}
};
const document = {
createElement: uiElement,
body: {
append(panel) {
const all = [];
function visit(node) {
all.push(node);
for (const child of node.children) visit(child);
}
visit(panel);
const keyInput = all.find(node => node.type === 'password');
keyInput.value = 'test-key';
const submit = all.find(node => node.textContent === 'Запустить');
queueMicrotask(() => submit.listeners.click());
}
},
querySelectorAll(selector) {
if (selector.includes('chat-item-clickable') || selector.includes('row-clickable')) return rowPresent ? [row] : [];
if (selector.includes('message-list-item') || selector.includes('.bubble[')) return messages;
return [];
},
querySelector(selector) {
if (selector.includes('editable-message-text') || selector.includes('input-message-input')) return input;
if (selector.includes('Send Message') || selector.includes('.btn-send')) return sendButton;
return null;
},
execCommand(command, _, text) {
assert.equal(command, 'insertText');
input.textContent = text;
return true;
}
};
const window = {
prompt() { return 'test-key'; },
TelegramWebOpenAIIntegration: null
};
const context = {
window, document, location, AbortController, MouseEvent: class MouseEvent {},
console: { log() {}, warn() {}, error() {} },
setTimeout(callback, ms) {
if (ms < 1000) queueMicrotask(callback);
if (ms === 2000) tickCallback = callback;
return 1;
},
clearTimeout() {},
fetch: async () => {
requests++;
return options.apiError
? { ok: false, status: 401, statusText: 'Unauthorized', json: async () => ({ error: { message: 'bad key' } }) }
: { ok: true, json: async () => ({ choices: [{ message: { content: 'Здравствуйте!' } }] }) };
}
};
await vm.runInNewContext(script, context);
return {
bot: window.TelegramWebOpenAIIntegration, messages, input,
showRow() { rowPresent = true; },
async runTick() { await tickCallback(); },
get sends() { return sends; },
get requests() { return requests; },
get mousedowns() { return mousedowns; }
};
}
function message(id, own, text, variant) {
return {
id: variant === 'A' ? 'message-' + id : '',
classList: { contains(name) { return own && (name === 'own' || name === 'is-out'); } },
getAttribute(name) {
if (name === 'data-message-id' || name === 'data-mid') return id;
return null;
},
querySelector() {
return {
cloneNode() {
return { textContent: text, querySelectorAll() { return []; } };
}
};
}
};
}
for (const variant of ['A', 'K']) {
test('Web ' + variant + ' replies once and verifies outgoing text', async () => {
const app = await fixture(variant);
assert.equal(await app.bot.processCurrent(), true);
assert.equal(app.sends, 1);
assert.equal(app.requests, 1);
assert.equal(await app.bot.processCurrent(), true);
assert.equal(app.sends, 1);
app.bot.stop();
});
}
test('API error releases busy state and sends nothing', async () => {
const app = await fixture('A', { apiError: true });
await assert.rejects(app.bot.processCurrent(), /OpenAI HTTP 401/);
assert.equal(app.sends, 0);
assert.equal(app.bot.status().busy, false);
app.bot.stop();
});
test('existing draft is never overwritten or sent', async () => {
const app = await fixture('A', { draft: 'Мой черновик' });
assert.equal(await app.bot.processCurrent(), false);
assert.equal(app.input.textContent, 'Мой черновик');
assert.equal(app.sends, 0);
app.bot.stop();
});
test('a media message after text does not trigger an answer to stale text', async () => {
const app = await fixture('A', { mediaLast: true });
assert.equal(await app.bot.processCurrent(), true);
assert.equal(app.requests, 0);
assert.equal(app.sends, 0);
app.bot.stop();
});
test('a new private chat without an unread badge is processed automatically', async () => {
const app = await fixture('A', { initialRows: false });
app.showRow();
await app.runTick();
assert.equal(app.requests, 1);
assert.equal(app.sends, 1);
app.bot.stop();
});
test('opening another Web A chat uses mousedown and verifies fresh selection', async () => {
const app = await fixture('A', { initialRows: false, initialOtherChat: true });
app.showRow();
await app.runTick();
assert.equal(app.mousedowns, 1);
assert.equal(app.sends, 1);
app.bot.stop();
});
test('an unread private chat already present at startup is processed', async () => {
const app = await fixture('A', { unread: true, initialOtherChat: true });
await app.runTick();
assert.equal(app.sends, 1);
assert.equal(app.requests, 1);
app.bot.stop();
});