fix broken mocha tests v2

see also https://github.com/misskey-dev/misskey/pull/8892
This commit is contained in:
MeiMei 2022-06-26 19:16:32 +09:00 committed by Johann150
parent 45b36e8059
commit 5ac94cc268
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
6 changed files with 157 additions and 74 deletions

View file

@ -5,6 +5,6 @@
"loader=./test/loader.js" "loader=./test/loader.js"
], ],
"slow": 1000, "slow": 1000,
"timeout": 10000, "timeout": 30000,
"exit": true "exit": true
} }

View file

@ -6,6 +6,8 @@ import { IEndpointMeta } from './endpoints.js';
const logger = new Logger('limiter'); const logger = new Logger('limiter');
export const limiter = (limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string) => new Promise<void>((ok, reject) => { export const limiter = (limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string) => new Promise<void>((ok, reject) => {
if (process.env.NODE_ENV === 'test') ok();
const hasShortTermLimit = typeof limitation.minInterval === 'number'; const hasShortTermLimit = typeof limitation.minInterval === 'number';
const hasLongTermLimit = const hasLongTermLimit =

View file

@ -2,7 +2,7 @@ process.env.NODE_ENV = 'test';
import * as assert from 'assert'; import * as assert from 'assert';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import { async, signup, request, post, react, connectStream, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, react, startServer, shutdownServer, waitFire } from './utils.js';
describe('Mute', () => { describe('Mute', () => {
let p: childProcess.ChildProcess; let p: childProcess.ChildProcess;
@ -55,48 +55,24 @@ describe('Mute', () => {
assert.strictEqual(res.body.hasUnreadMentions, false); assert.strictEqual(res.body.hasUnreadMentions, false);
})); }));
it('ミュートしているユーザーからメンションされても、ストリームに unreadMention イベントが流れてこない', () => new Promise(async done => { it('ミュートしているユーザーからメンションされても、ストリームに unreadMention イベントが流れてこない', async () => {
// 状態リセット // 状態リセット
await request('/i/read-all-unread-notes', {}, alice); await request('/i/read-all-unread-notes', {}, alice);
let fired = false; const fired = await waitFire(alice, 'main', () => post(carol, { text: '@alice hi' }), msg => msg.type === 'unreadMention');
const ws = await connectStream(alice, 'main', ({ type }) => { assert.strictEqual(fired, false);
if (type == 'unreadMention') {
fired = true;
}
}); });
post(carol, { text: '@alice hi' }); it('ミュートしているユーザーからメンションされても、ストリームに unreadNotification イベントが流れてこない', async () => {
setTimeout(() => {
assert.strictEqual(fired, false);
ws.close();
done();
}, 5000);
}));
it('ミュートしているユーザーからメンションされても、ストリームに unreadNotification イベントが流れてこない', () => new Promise(async done => {
// 状態リセット // 状態リセット
await request('/i/read-all-unread-notes', {}, alice); await request('/i/read-all-unread-notes', {}, alice);
await request('/notifications/mark-all-as-read', {}, alice); await request('/notifications/mark-all-as-read', {}, alice);
let fired = false; const fired = await waitFire(alice, 'main', () => post(carol, { text: '@alice hi' }), msg => msg.type === 'unreadNotification');
const ws = await connectStream(alice, 'main', ({ type }) => {
if (type == 'unreadNotification') {
fired = true;
}
});
post(carol, { text: '@alice hi' });
setTimeout(() => {
assert.strictEqual(fired, false); assert.strictEqual(fired, false);
ws.close(); });
done();
}, 5000);
}));
describe('Timeline', () => { describe('Timeline', () => {
it('タイムラインにミュートしているユーザーの投稿が含まれない', async(async () => { it('タイムラインにミュートしているユーザーの投稿が含まれない', async(async () => {

View file

@ -3,7 +3,7 @@ process.env.NODE_ENV = 'test';
import * as assert from 'assert'; import * as assert from 'assert';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import { Note } from '../src/models/entities/note.js'; import { Note } from '../src/models/entities/note.js';
import { async, signup, request, post, uploadFile, startServer, shutdownServer, initTestDb } from './utils.js'; import { async, signup, request, post, uploadUrl, startServer, shutdownServer, initTestDb, api } from './utils.js';
describe('Note', () => { describe('Note', () => {
let p: childProcess.ChildProcess; let p: childProcess.ChildProcess;
@ -37,7 +37,7 @@ describe('Note', () => {
})); }));
it('ファイルを添付できる', async(async () => { it('ファイルを添付できる', async(async () => {
const file = await uploadFile(alice); const file = await uploadUrl(alice, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg');
const res = await request('/notes/create', { const res = await request('/notes/create', {
fileIds: [file.id], fileIds: [file.id],
@ -49,7 +49,7 @@ describe('Note', () => {
})); }));
it('他人のファイルは無視', async(async () => { it('他人のファイルは無視', async(async () => {
const file = await uploadFile(bob); const file = await uploadUrl(bob, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg');
const res = await request('/notes/create', { const res = await request('/notes/create', {
text: 'test', text: 'test',
@ -72,11 +72,13 @@ describe('Note', () => {
assert.deepStrictEqual(res.body.createdNote.fileIds, []); assert.deepStrictEqual(res.body.createdNote.fileIds, []);
})); }));
it('不正なファイルIDで怒られる', async(async () => { it('不正なファイルIDは無視', async(async () => {
const res = await request('/notes/create', { const res = await request('/notes/create', {
fileIds: ['kyoppie'], fileIds: ['kyoppie'],
}, alice); }, alice);
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 200);
assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
assert.deepStrictEqual(res.body.createdNote.fileIds, []);
})); }));
it('返信できる', async(async () => { it('返信できる', async(async () => {
@ -136,7 +138,7 @@ describe('Note', () => {
it('文字数ぎりぎりで怒られない', async(async () => { it('文字数ぎりぎりで怒られない', async(async () => {
const post = { const post = {
text: '!'.repeat(500), text: '!'.repeat(3000),
}; };
const res = await request('/notes/create', post, alice); const res = await request('/notes/create', post, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
@ -144,7 +146,7 @@ describe('Note', () => {
it('文字数オーバーで怒られる', async(async () => { it('文字数オーバーで怒られる', async(async () => {
const post = { const post = {
text: '!'.repeat(501), text: '!'.repeat(3001),
}; };
const res = await request('/notes/create', post, alice); const res = await request('/notes/create', post, alice);
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
@ -207,7 +209,7 @@ describe('Note', () => {
assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
assert.strictEqual(res.body.createdNote.text, post.text); assert.strictEqual(res.body.createdNote.text, post.text);
const noteDoc = await Notes.findOne(res.body.createdNote.id); const noteDoc = await Notes.findOneBy({ id: res.body.createdNote.id });
assert.deepStrictEqual(noteDoc.mentions, [bob.id]); assert.deepStrictEqual(noteDoc.mentions, [bob.id]);
})); }));
@ -336,32 +338,32 @@ describe('Note', () => {
describe('notes/delete', () => { describe('notes/delete', () => {
it('delete a reply', async(async () => { it('delete a reply', async(async () => {
const mainNoteRes = await request('/notes/create', { const mainNoteRes = await api('notes/create', {
text: 'main post', text: 'main post',
}, alice); }, alice);
const replyOneRes = await request('/notes/create', { const replyOneRes = await api('notes/create', {
text: 'reply one', text: 'reply one',
replyId: mainNoteRes.body.createdNote.id, replyId: mainNoteRes.body.createdNote.id,
}, alice); }, alice);
const replyTwoRes = await request('/notes/create', { const replyTwoRes = await api('notes/create', {
text: 'reply two', text: 'reply two',
replyId: mainNoteRes.body.createdNote.id, replyId: mainNoteRes.body.createdNote.id,
}, alice); }, alice);
const deleteOneRes = await request('/notes/delete', { const deleteOneRes = await api('notes/delete', {
noteId: replyOneRes.body.createdNote.id, noteId: replyOneRes.body.createdNote.id,
}, alice); }, alice);
assert.strictEqual(deleteOneRes.status, 204); assert.strictEqual(deleteOneRes.status, 204);
let mainNote = await Notes.findOne({ id: mainNoteRes.body.createdNote.id }); let mainNote = await Notes.findOneBy({ id: mainNoteRes.body.createdNote.id });
assert.strictEqual(mainNote.repliesCount, 1); assert.strictEqual(mainNote.repliesCount, 1);
const deleteTwoRes = await request('/notes/delete', { const deleteTwoRes = await api('notes/delete', {
noteId: replyTwoRes.body.createdNote.id, noteId: replyTwoRes.body.createdNote.id,
}, alice); }, alice);
assert.strictEqual(deleteTwoRes.status, 204); assert.strictEqual(deleteTwoRes.status, 204);
mainNote = await Notes.findOne({ id: mainNoteRes.body.createdNote.id }); mainNote = await Notes.findOneBy({ id: mainNoteRes.body.createdNote.id });
assert.strictEqual(mainNote.repliesCount, 0); assert.strictEqual(mainNote.repliesCount, 0);
})); }));
}); });

View file

@ -2,12 +2,7 @@ process.env.NODE_ENV = 'test';
import * as assert from 'assert'; import * as assert from 'assert';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import { dirname } from 'node:path'; import { async, signup, request, post, uploadUrl, startServer, shutdownServer } from './utils.js';
import { fileURLToPath } from 'node:url';
import { async, signup, request, post, uploadFile, startServer, shutdownServer } from './utils.js';
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
describe('users/notes', () => { describe('users/notes', () => {
let p: childProcess.ChildProcess; let p: childProcess.ChildProcess;
@ -20,8 +15,8 @@ describe('users/notes', () => {
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
alice = await signup({ username: 'alice' }); alice = await signup({ username: 'alice' });
const jpg = await uploadFile(alice, _dirname + '/resources/Lenna.jpg'); const jpg = await uploadUrl(alice, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg');
const png = await uploadFile(alice, _dirname + '/resources/Lenna.png'); const png = await uploadUrl(alice, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.png');
jpgNote = await post(alice, { jpgNote = await post(alice, {
fileIds: [jpg.id], fileIds: [jpg.id],
}); });

View file

@ -1,16 +1,18 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path'; import { dirname } from 'node:path';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as http from 'node:http'; import * as http from 'node:http';
import { SIGKILL } from 'constants'; import { SIGKILL } from 'constants';
import * as WebSocket from 'ws'; import WebSocket from 'ws';
import * as misskey from 'misskey-js'; import * as misskey from 'misskey-js';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import FormData from 'form-data'; import FormData from 'form-data';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import loadConfig from '../src/config/load.js'; import loadConfig from '../src/config/load.js';
import { entities } from '../src/db/postgre.js'; import { entities } from '../src/db/postgre.js';
import got from 'got';
const _filename = fileURLToPath(import.meta.url); const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename); const _dirname = dirname(_filename);
@ -26,6 +28,42 @@ export const async = (fn: Function) => (done: Function) => {
}); });
}; };
export const api = async (endpoint: string, params: any, me?: any) => {
endpoint = endpoint.replace(/^\//, '');
const auth = me ? {
i: me.token
} : {};
const res = await got<string>(`http://localhost:${port}/api/${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(Object.assign(auth, params)),
retry: {
limit: 0,
},
hooks: {
beforeError: [
error => {
const { response } = error;
if (response && response.body) console.warn(response.body);
return error;
}
]
},
});
const status = res.statusCode;
const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null;
return {
status,
body
};
};
export const request = async (endpoint: string, params: any, me?: any): Promise<{ body: any, status: number }> => { export const request = async (endpoint: string, params: any, me?: any): Promise<{ body: any, status: number }> => {
const auth = me ? { const auth = me ? {
i: me.token, i: me.token,
@ -53,7 +91,7 @@ export const signup = async (params?: any): Promise<any> => {
password: 'test', password: 'test',
}, params); }, params);
const res = await request('/signup', q); const res = await api('signup', q);
return res.body; return res.body;
}; };
@ -63,34 +101,62 @@ export const post = async (user: any, params?: misskey.Endpoints['notes/create']
text: 'test', text: 'test',
}, params); }, params);
const res = await request('/notes/create', q, user); const res = await api('notes/create', q, user);
return res.body ? res.body.createdNote : null; return res.body ? res.body.createdNote : null;
}; };
export const react = async (user: any, note: any, reaction: string): Promise<any> => { export const react = async (user: any, note: any, reaction: string): Promise<any> => {
await request('/notes/reactions/create', { await api('notes/reactions/create', {
noteId: note.id, noteId: note.id,
reaction: reaction, reaction: reaction,
}, user); }, user);
}; };
export const uploadFile = (user: any, path?: string): Promise<any> => { /**
const formData = new FormData(); * Upload file
formData.append('i', user.token); * @param user User
formData.append('file', fs.createReadStream(path || _dirname + '/resources/Lenna.png')); * @param _path Optional, absolute path or relative from ./resources/
*/
export const uploadFile = async (user: any, _path?: string): Promise<any> => {
const absPath = _path == null ? `${_dirname}/resources/Lenna.jpg` : path.isAbsolute(_path) ? _path : `${_dirname}/resources/${_path}`;
return fetch(`http://localhost:${port}/api/drive/files/create`, { const formData = new FormData() as any;
method: 'post', formData.append('i', user.token);
formData.append('file', fs.createReadStream(absPath));
formData.append('force', 'true');
const res = await got<string>(`http://localhost:${port}/api/drive/files/create`, {
method: 'POST',
body: formData, body: formData,
timeout: 30 * 1000, retry: {
}).then(res => { limit: 0,
if (!res.ok) { },
throw `${res.status} ${res.statusText}`; });
} else {
return res.json(); const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null;
return body;
};
export const uploadUrl = async (user: any, url: string) => {
let file: any;
const ws = await connectStream(user, 'main', (msg) => {
if (msg.type === 'driveFileCreated') {
file = msg.body;
} }
}); });
await api('drive/files/upload-from-url', {
url,
force: true,
}, user);
await sleep(5000);
ws.close();
return file;
}; };
export function connectStream(user: any, channel: string, listener: (message: Record<string, any>) => any, params?: any): Promise<WebSocket> { export function connectStream(user: any, channel: string, listener: (message: Record<string, any>) => any, params?: any): Promise<WebSocket> {
@ -120,6 +186,40 @@ export function connectStream(user: any, channel: string, listener: (message: Re
}); });
} }
export const waitFire = async (user: any, channel: string, trgr: () => any, cond: (msg: Record<string, any>) => boolean) => {
return new Promise<boolean>(async (res, rej) => {
let timer: NodeJS.Timeout;
let ws: WebSocket;
try {
ws = await connectStream(user, channel, msg => {
if (cond(msg)) {
ws.close();
if (timer) clearTimeout(timer);
res(true);
}
});
} catch (e) {
rej(e);
}
if (!ws!) return;
timer = setTimeout(() => {
ws.close();
res(false);
}, 5000);
try {
await trgr();
} catch (e) {
ws.close();
if (timer) clearTimeout(timer);
rej(e);
}
})
};
export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?: number, type?: string, location?: string }> => { export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?: number, type?: string, location?: string }> => {
// node-fetchだと3xxを取れない // node-fetchだと3xxを取れない
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
@ -176,7 +276,7 @@ export async function initTestDb(justBorrow = false, initEntities?: any[]) {
return db; return db;
} }
export function startServer(timeout = 30 * 1000): Promise<childProcess.ChildProcess> { export function startServer(timeout = 60 * 1000): Promise<childProcess.ChildProcess> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const t = setTimeout(() => { const t = setTimeout(() => {
p.kill(SIGKILL); p.kill(SIGKILL);
@ -214,3 +314,11 @@ export function shutdownServer(p: childProcess.ChildProcess, timeout = 20 * 1000
p.kill(); p.kill();
}); });
} }
export function sleep(msec: number) {
return new Promise<void>(res => {
setTimeout(() => {
res();
}, msec);
});
}