transform tests from ts to js

This allows to get rid of the special loader for ts files. There is
no need for the test files to be written in TypeScript, plain
JavaScript should be fine for this purpose.
This commit is contained in:
Johann150 2023-06-01 23:21:03 +02:00
parent 680d1f1459
commit 38786b6999
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
27 changed files with 175 additions and 382 deletions

View file

@ -1,8 +1,6 @@
{ {
"extension": ["ts","js","cjs","mjs"],
"node-option": [ "node-option": [
"experimental-specifier-resolution=node", "experimental-specifier-resolution=node"
"loader=./test/loader.js"
], ],
"slow": 1000, "slow": 1000,
"timeout": 30000, "timeout": 30000,

View file

@ -8,10 +8,10 @@
"build": "tsc -p tsconfig.json || echo done. && tsc-alias -p tsconfig.json", "build": "tsc -p tsconfig.json || echo done. && tsc-alias -p tsconfig.json",
"watch": "node watch.mjs", "watch": "node watch.mjs",
"lint": "tsc --noEmit --skipLibCheck && eslint src --ext .ts", "lint": "tsc --noEmit --skipLibCheck && eslint src --ext .ts",
"mocha": "cross-env NODE_ENV=test TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT=\"./test/tsconfig.json\" mocha", "mocha": "NODE_ENV=test mocha",
"migrate": "npx typeorm migration:run -d ormconfig.js", "migrate": "npx typeorm migration:run -d ormconfig.js",
"start": "node --experimental-json-modules ./built/index.js", "start": "node --experimental-json-modules ./built/index.js",
"start:test": "cross-env NODE_ENV=test node --experimental-json-modules ./built/index.js", "start:test": "NODE_ENV=test node --experimental-json-modules ./built/index.js",
"test": "npm run mocha" "test": "npm run mocha"
}, },
"dependencies": { "dependencies": {
@ -164,7 +164,6 @@
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@typescript-eslint/eslint-plugin": "^5.46.1", "@typescript-eslint/eslint-plugin": "^5.46.1",
"@typescript-eslint/parser": "^5.46.1", "@typescript-eslint/parser": "^5.46.1",
"cross-env": "7.0.3",
"eslint": "^8.29.0", "eslint": "^8.29.0",
"eslint-plugin-foundkey-custom-rules": "file:../shared/custom-rules", "eslint-plugin-foundkey-custom-rules": "file:../shared/custom-rules",
"eslint-plugin-import": "^2.26.0", "eslint-plugin-import": "^2.26.0",

View file

@ -1,11 +1,11 @@
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = 'test';
import * as assert from 'assert'; import * as assert from 'assert';
import { initDb } from '../src/db/postgre.js'; import { initDb } from '../built/db/postgre.js';
import { initTestDb } from './utils.js'; import { initTestDb } from './utils.mjs';
function rndstr(length): string { function rndstr(length) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const chars_len = 62; const chars_len = 62;
@ -52,8 +52,8 @@ describe('ActivityPub', () => {
}; };
it('Minimum Actor', async () => { it('Minimum Actor', async () => {
const { MockResolver } = await import('./misc/mock-resolver.js'); const { MockResolver } = await import('./misc/mock-resolver.mjs');
const { createPerson } = await import('../src/remote/activitypub/models/person.js'); const { createPerson } = await import('../built/remote/activitypub/models/person.js');
const resolver = new MockResolver(); const resolver = new MockResolver();
resolver._register(actor.id, actor); resolver._register(actor.id, actor);
@ -66,8 +66,8 @@ describe('ActivityPub', () => {
}); });
it('Minimum Note', async () => { it('Minimum Note', async () => {
const { MockResolver } = await import('./misc/mock-resolver.js'); const { MockResolver } = await import('./misc/mock-resolver.mjs');
const { createNote } = await import('../src/remote/activitypub/models/note.js'); const { createNote } = await import('../built/remote/activitypub/models/note.js');
const resolver = new MockResolver(); const resolver = new MockResolver();
resolver._register(actor.id, actor); resolver._register(actor.id, actor);
@ -99,8 +99,8 @@ describe('ActivityPub', () => {
}; };
it('Actor', async () => { it('Actor', async () => {
const { MockResolver } = await import('./misc/mock-resolver.js'); const { MockResolver } = await import('./misc/mock-resolver.mjs');
const { createPerson } = await import('../src/remote/activitypub/models/person.js'); const { createPerson } = await import('../built/remote/activitypub/models/person.js');
const resolver = new MockResolver(); const resolver = new MockResolver();
resolver._register(actor.id, actor); resolver._register(actor.id, actor);

View file

@ -1,9 +1,9 @@
import * as assert from 'assert'; import * as assert from 'assert';
import httpSignature from '@peertube/http-signature'; import httpSignature from '@peertube/http-signature';
import { genRsaKeyPair } from '../src/misc/gen-key-pair.js'; import { genRsaKeyPair } from '../built/misc/gen-key-pair.js';
import { createSignedPost, createSignedGet } from '../src/remote/activitypub/ap-request.js'; import { createSignedPost, createSignedGet } from '../built/remote/activitypub/ap-request.js';
export const buildParsedSignature = (signingString: string, signature: string, algorithm: string) => { export const buildParsedSignature = (signingString, signature, algorithm) => {
return { return {
scheme: 'Signature', scheme: 'Signature',
params: { params: {

View file

@ -2,12 +2,12 @@ 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, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, startServer, shutdownServer } from './utils.mjs';
describe('API visibility', function() { describe('API visibility', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -20,48 +20,48 @@ describe('API visibility', function() {
describe('Note visibility', async () => { describe('Note visibility', async () => {
//#region vars //#region vars
/** protagonist */ /** protagonist */
let alice: any; let alice;
/** follower */ /** follower */
let follower: any; let follower;
/** non-follower */ /** non-follower */
let other: any; let other;
/** non-follower who has been replied to or mentioned */ /** non-follower who has been replied to or mentioned */
let target: any; let target;
/** actor for which a specified visibility was set */ /** actor for which a specified visibility was set */
let target2: any; let target2;
/** public-post */ /** public-post */
let pub: any; let pub;
/** home-post */ /** home-post */
let home: any; let home;
/** followers-post */ /** followers-post */
let fol: any; let fol;
/** specified-post */ /** specified-post */
let spe: any; let spe;
/** public-reply to target's post */ /** public-reply to target's post */
let pubR: any; let pubR;
/** home-reply to target's post */ /** home-reply to target's post */
let homeR: any; let homeR;
/** followers-reply to target's post */ /** followers-reply to target's post */
let folR: any; let folR;
/** specified-reply to target's post */ /** specified-reply to target's post */
let speR: any; let speR;
/** public-mention to target */ /** public-mention to target */
let pubM: any; let pubM;
/** home-mention to target */ /** home-mention to target */
let homeM: any; let homeM;
/** followers-mention to target */ /** followers-mention to target */
let folM: any; let folM;
/** specified-mention to target */ /** specified-mention to target */
let speM: any; let speM;
/** reply target post */ /** reply target post */
let tgt: any; let tgt;
//#endregion //#endregion
const show = async (noteId: any, by: any) => { const show = async (noteId, by) => {
return await request('/notes/show', { return await request('/notes/show', {
noteId, noteId,
}, by); }, by);
@ -412,21 +412,21 @@ describe('API visibility', function() {
it('[TL] public post on author home TL', async(async () => { it('[TL] public post on author home TL', async(async () => {
const res = await request('/notes/timeline', { limit: 100 }, alice); const res = await request('/notes/timeline', { limit: 100 }, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == pub.id); const notes = res.body.filter((n) => n.id == pub.id);
assert.strictEqual(notes[0].text, 'x'); assert.strictEqual(notes[0].text, 'x');
})); }));
it('[TL] public post absent from non-follower home TL', async(async () => { it('[TL] public post absent from non-follower home TL', async(async () => {
const res = await request('/notes/timeline', { limit: 100 }, other); const res = await request('/notes/timeline', { limit: 100 }, other);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == pub.id); const notes = res.body.filter((n) => n.id == pub.id);
assert.strictEqual(notes.length, 0); assert.strictEqual(notes.length, 0);
})); }));
it('[TL] followers post on follower home TL', async(async () => { it('[TL] followers post on follower home TL', async(async () => {
const res = await request('/notes/timeline', { limit: 100 }, follower); const res = await request('/notes/timeline', { limit: 100 }, follower);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == fol.id); const notes = res.body.filter((n) => n.id == fol.id);
assert.strictEqual(notes[0].text, 'x'); assert.strictEqual(notes[0].text, 'x');
})); }));
//#endregion //#endregion
@ -435,21 +435,21 @@ describe('API visibility', function() {
it('[TL] followers reply on follower reply TL', async(async () => { it('[TL] followers reply on follower reply TL', async(async () => {
const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, follower); const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, follower);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == folR.id); const notes = res.body.filter((n) => n.id == folR.id);
assert.strictEqual(notes[0].text, 'x'); assert.strictEqual(notes[0].text, 'x');
})); }));
it('[TL] followers reply absent from not replied to non-follower reply TL', async(async () => { it('[TL] followers reply absent from not replied to non-follower reply TL', async(async () => {
const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, other); const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, other);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == folR.id); const notes = res.body.filter((n) => n.id == folR.id);
assert.strictEqual(notes.length, 0); assert.strictEqual(notes.length, 0);
})); }));
it('[TL] followers reply on replied to actor reply TL', async(async () => { it('[TL] followers reply on replied to actor reply TL', async(async () => {
const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, target); const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, target);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == folR.id); const notes = res.body.filter((n) => n.id == folR.id);
assert.strictEqual(notes[0].text, 'x'); assert.strictEqual(notes[0].text, 'x');
})); }));
//#endregion //#endregion
@ -458,14 +458,14 @@ describe('API visibility', function() {
it('[TL] followers reply on replied to non-follower mention TL', async(async () => { it('[TL] followers reply on replied to non-follower mention TL', async(async () => {
const res = await request('/notes/mentions', { limit: 100 }, target); const res = await request('/notes/mentions', { limit: 100 }, target);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == folR.id); const notes = res.body.filter((n) => n.id == folR.id);
assert.strictEqual(notes[0].text, 'x'); assert.strictEqual(notes[0].text, 'x');
})); }));
it('[TL] followers mention on mentioned non-follower mention TL', async(async () => { it('[TL] followers mention on mentioned non-follower mention TL', async(async () => {
const res = await request('/notes/mentions', { limit: 100 }, target); const res = await request('/notes/mentions', { limit: 100 }, target);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const notes = res.body.filter((n: any) => n.id == folM.id); const notes = res.body.filter((n) => n.id == folM.id);
assert.strictEqual(notes[0].text, '@target x'); assert.strictEqual(notes[0].text, '@target x');
})); }));
//#endregion //#endregion

View file

@ -2,15 +2,13 @@ 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, uploadFile, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, react, uploadFile, startServer, shutdownServer } from './utils.mjs';
describe('API', function() { describe('API', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let alice: any; let alice, bob, carol;
let bob: any;
let carol: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();

View file

@ -2,17 +2,15 @@ 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, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, startServer, shutdownServer } from './utils.mjs';
describe('Block', function() { describe('Block', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
// alice blocks bob // alice blocks bob
let alice: any; let alice, bob, carol;
let bob: any;
let carol: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -80,8 +78,8 @@ describe('Block', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), false); assert.strictEqual(res.body.some((note) => note.id === aliceNote.id), false);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note) => note.id === bobNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); assert.strictEqual(res.body.some((note) => note.id === carolNote.id), true);
})); }));
}); });

View file

@ -2,18 +2,14 @@ process.env.NODE_ENV = 'test';
import * as assert from 'assert'; import * as assert from 'assert';
import * as lolex from '@sinonjs/fake-timers'; import * as lolex from '@sinonjs/fake-timers';
import TestChart from '../src/services/chart/charts/test.js'; import TestChart from '../built/services/chart/charts/test.js';
import TestGroupedChart from '../src/services/chart/charts/test-grouped.js'; import TestGroupedChart from '../built/services/chart/charts/test-grouped.js';
import TestUniqueChart from '../src/services/chart/charts/test-unique.js'; import TestUniqueChart from '../built/services/chart/charts/test-unique.js';
import TestIntersectionChart from '../src/services/chart/charts/test-intersection.js'; import TestIntersectionChart from '../built/services/chart/charts/test-intersection.js';
import { initDb } from '../src/db/postgre.js'; import { initDb } from '../built/db/postgre.js';
describe('Chart', () => { describe('Chart', () => {
let testChart: TestChart; let testChart, testGroupedChart, testUniqueChart, testIntersectionChart, clock;
let testGroupedChart: TestGroupedChart;
let testUniqueChart: TestUniqueChart;
let testIntersectionChart: TestIntersectionChart;
let clock: lolex.InstalledClock;
beforeEach(async () => { beforeEach(async () => {
await initDb(true); await initDb(true);

View file

@ -1,15 +0,0 @@
version: "3"
services:
redistest:
image: redis:6
ports:
- "127.0.0.1:56312:6379"
dbtest:
image: postgres:13
ports:
- "127.0.0.1:54312:5432"
environment:
POSTGRES_DB: "test-misskey"
POSTGRES_HOST_AUTH_METHOD: trust

View file

@ -3,13 +3,12 @@ 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, uploadFile, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, react, uploadFile, startServer, shutdownServer } from './utils.mjs';
describe('API: Endpoints', () => { describe('API: Endpoints', () => {
let p: childProcess.ChildProcess; let p;
let alice: any;
let bob: any; let alice, bob, carol;
let carol: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();

View file

@ -1,11 +1,11 @@
import * as assert from 'assert'; import * as assert from 'assert';
import { parse } from 'mfm-js'; import { parse } from 'mfm-js';
import { extractMentions } from '../src/misc/extract-mentions.js'; import { extractMentions } from '../built/misc/extract-mentions.js';
describe('Extract mentions', () => { describe('Extract mentions', () => {
it('simple', () => { it('simple', () => {
const ast = parse('@foo @bar @baz')!; const ast = parse('@foo @bar @baz');
const mentions = extractMentions(ast); const mentions = extractMentions(ast);
assert.deepStrictEqual(mentions, [{ assert.deepStrictEqual(mentions, [{
username: 'foo', username: 'foo',
@ -23,7 +23,7 @@ describe('Extract mentions', () => {
}); });
it('nested', () => { it('nested', () => {
const ast = parse('@foo **@bar** @baz')!; const ast = parse('@foo **@bar** @baz');
const mentions = extractMentions(ast); const mentions = extractMentions(ast);
assert.deepStrictEqual(mentions, [{ assert.deepStrictEqual(mentions, [{
username: 'foo', username: 'foo',

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 * as openapi from '@redocly/openapi-core'; import * as openapi from '@redocly/openapi-core';
import { async, startServer, signup, post, request, simpleGet, port, shutdownServer } from './utils.js'; import { async, startServer, signup, post, request, simpleGet, port, shutdownServer } from './utils.mjs';
// Request Accept // Request Accept
const ONLY_AP = 'application/activity+json'; const ONLY_AP = 'application/activity+json';
@ -19,10 +19,9 @@ const HTML = 'text/html; charset=utf-8';
describe('Fetch resource', function() { describe('Fetch resource', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let alice: any; let alice, alicesPost;
let alicesPost: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();

View file

@ -2,16 +2,14 @@ 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, simpleGet } from './utils.js'; import { async, signup, request, post, react, connectStream, startServer, shutdownServer, simpleGet } from './utils.mjs';
describe('FF visibility', function() { describe('FF visibility', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let alice: any; let alice, bob, follower;
let bob: any;
let follower: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();

View file

@ -1,8 +1,8 @@
import * as assert from 'assert'; import * as assert from 'assert';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path'; import { dirname } from 'node:path';
import { getFileInfo } from '../src/misc/get-file-info.js'; import { getFileInfo } from '../built/misc/get-file-info.js';
import { async } from './utils.js'; import { async } from './utils.mjs';
const _filename = fileURLToPath(import.meta.url); const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename); const _dirname = dirname(_filename);
@ -10,7 +10,7 @@ const _dirname = dirname(_filename);
describe('Get file info', () => { describe('Get file info', () => {
it('Empty file', async (async () => { it('Empty file', async (async () => {
const path = `${_dirname}/resources/emptyfile`; const path = `${_dirname}/resources/emptyfile`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -28,7 +28,7 @@ describe('Get file info', () => {
it('Generic JPEG', async (async () => { it('Generic JPEG', async (async () => {
const path = `${_dirname}/resources/Lenna.jpg`; const path = `${_dirname}/resources/Lenna.jpg`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -46,7 +46,7 @@ describe('Get file info', () => {
it('Generic APNG', async (async () => { it('Generic APNG', async (async () => {
const path = `${_dirname}/resources/anime.png`; const path = `${_dirname}/resources/anime.png`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -64,7 +64,7 @@ describe('Get file info', () => {
it('Generic AGIF', async (async () => { it('Generic AGIF', async (async () => {
const path = `${_dirname}/resources/anime.gif`; const path = `${_dirname}/resources/anime.gif`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -82,7 +82,7 @@ describe('Get file info', () => {
it('PNG with alpha', async (async () => { it('PNG with alpha', async (async () => {
const path = `${_dirname}/resources/with-alpha.png`; const path = `${_dirname}/resources/with-alpha.png`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -100,7 +100,7 @@ describe('Get file info', () => {
it('Generic SVG', async (async () => { it('Generic SVG', async (async () => {
const path = `${_dirname}/resources/image.svg`; const path = `${_dirname}/resources/image.svg`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -119,7 +119,7 @@ describe('Get file info', () => {
it('SVG with XML definition', async (async () => { it('SVG with XML definition', async (async () => {
// https://github.com/misskey-dev/misskey/issues/4413 // https://github.com/misskey-dev/misskey/issues/4413
const path = `${_dirname}/resources/with-xml-def.svg`; const path = `${_dirname}/resources/with-xml-def.svg`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -137,7 +137,7 @@ describe('Get file info', () => {
it('Dimension limit', async (async () => { it('Dimension limit', async (async () => {
const path = `${_dirname}/resources/25000x25000.png`; const path = `${_dirname}/resources/25000x25000.png`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {
@ -155,7 +155,7 @@ describe('Get file info', () => {
it('Rotate JPEG', async (async () => { it('Rotate JPEG', async (async () => {
const path = `${_dirname}/resources/rotate.jpg`; const path = `${_dirname}/resources/rotate.jpg`;
const info = await getFileInfo(path) as any; const info = await getFileInfo(path);
delete info.warnings; delete info.warnings;
delete info.blurhash; delete info.blurhash;
assert.deepStrictEqual(info, { assert.deepStrictEqual(info, {

View file

@ -1,34 +0,0 @@
/**
* ts-node/esmローダーに投げる前にpath mappingを解決する
* 参考
* - https://github.com/TypeStrong/ts-node/discussions/1450#discussioncomment-1806115
* - https://nodejs.org/api/esm.html#loaders
* https://github.com/TypeStrong/ts-node/pull/1585 が取り込まれたらこのカスタムローダーは必要なくなる
*/
import { resolve as resolveTs, load } from 'ts-node/esm';
import { loadConfig, createMatchPath } from 'tsconfig-paths';
import { pathToFileURL } from 'url';
const tsconfig = loadConfig();
const matchPath = createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths);
export function resolve(specifier, ctx, defaultResolve) {
let resolvedSpecifier;
if (specifier.endsWith('.js')) {
// maybe transpiled
const specifierWithoutExtension = specifier.substring(0, specifier.length - '.js'.length);
const matchedSpecifier = matchPath(specifierWithoutExtension);
if (matchedSpecifier) {
resolvedSpecifier = pathToFileURL(`${matchedSpecifier}.js`).href;
}
} else {
const matchedSpecifier = matchPath(specifier);
if (matchedSpecifier) {
resolvedSpecifier = pathToFileURL(matchedSpecifier).href;
}
}
return resolveTs(resolvedSpecifier ?? specifier, ctx, defaultResolve);
}
export { load };

View file

@ -1,7 +1,7 @@
import * as assert from 'assert'; import * as assert from 'assert';
import { toHtml } from '../src/mfm/to-html.js'; import { toHtml } from '../built/mfm/to-html.js';
import { fromHtml } from '../src/mfm/from-html.js'; import { fromHtml } from '../built/mfm/from-html.js';
describe('toHtml', () => { describe('toHtml', () => {
it('br', async () => { it('br', async () => {

View file

@ -1,21 +1,16 @@
import { Resolver } from '../../src/remote/activitypub/resolver.js'; import { Resolver } from '../../built/remote/activitypub/resolver.js';
import { IObject } from '../../src/remote/activitypub/type.js';
type MockResponse = {
type: string;
content: string;
};
export class MockResolver extends Resolver { export class MockResolver extends Resolver {
private _rs = new Map<string, MockResponse>(); _rs = new Map();
public async _register(uri: string, content: string | Record<string, any>, type = 'application/activity+json') {
async _register(uri, content, type = 'application/activity+json') {
this._rs.set(uri, { this._rs.set(uri, {
type, type,
content: typeof content === 'string' ? content : JSON.stringify(content), content: typeof content === 'string' ? content : JSON.stringify(content),
}); });
} }
public async resolve(value: string | IObject): Promise<IObject> { async resolve(value) {
if (typeof value !== 'string') return value; if (typeof value !== 'string') return value;
const r = this._rs.get(value); const r = this._rs.get(value);

View file

@ -2,17 +2,15 @@ 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, startServer, shutdownServer, waitFire } from './utils.js'; import { async, signup, request, post, react, startServer, shutdownServer, waitFire } from './utils.mjs';
describe('Mute', function() { describe('Mute', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
// alice mutes carol // alice mutes carol
let alice: any; let alice, bob, carol;
let bob: any;
let carol: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -41,8 +39,8 @@ describe('Mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note) => note.id === bobNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); assert.strictEqual(res.body.some((note) => note.id === carolNote.id), false);
})); }));
it('ミュートしているユーザーからメンションされても、hasUnreadMentions が true にならない', async(async () => { it('ミュートしているユーザーからメンションされても、hasUnreadMentions が true にならない', async(async () => {
@ -86,9 +84,9 @@ describe('Mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.some((note) => note.id === aliceNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note) => note.id === bobNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); assert.strictEqual(res.body.some((note) => note.id === carolNote.id), false);
})); }));
it('タイムラインにミュートしているユーザーの投稿のRenoteが含まれない', async(async () => { it('タイムラインにミュートしているユーザーの投稿のRenoteが含まれない', async(async () => {
@ -102,9 +100,9 @@ describe('Mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.some((note) => note.id === aliceNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note) => note.id === bobNote.id), false);
assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); assert.strictEqual(res.body.some((note) => note.id === carolNote.id), false);
})); }));
}); });
@ -118,8 +116,8 @@ describe('Mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((notification: any) => notification.userId === bob.id), true); assert.strictEqual(res.body.some((notification) => notification.userId === bob.id), true);
assert.strictEqual(res.body.some((notification: any) => notification.userId === carol.id), false); assert.strictEqual(res.body.some((notification) => notification.userId === carol.id), false);
})); }));
}); });
}); });

View file

@ -2,17 +2,16 @@ 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 '../built/models/entities/note.js';
import { async, signup, request, post, uploadUrl, startServer, shutdownServer, initTestDb, api } from './utils.js'; import { async, signup, request, post, uploadUrl, startServer, shutdownServer, initTestDb, api } from './utils.mjs';
describe('Note', function() { describe('Note', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let Notes: any; let Notes;
let alice: any; let alice, bob;
let bob: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();

View file

@ -1,5 +1,5 @@
import * as assert from 'assert'; import * as assert from 'assert';
import { query } from '../../src/prelude/url.js'; import { query } from '../../built/prelude/url.js';
describe('url', () => { describe('url', () => {
it('query', () => { it('query', () => {

View file

@ -1,83 +0,0 @@
/*
import * as assert from 'assert';
import { toDbReaction } from '../src/misc/reaction-lib.js';
describe('toDbReaction', async () => {
it('既存の文字列リアクションはそのまま', async () => {
assert.strictEqual(await toDbReaction('like'), 'like');
});
it('Unicodeプリンは寿司化不能とするため文字列化しない', async () => {
assert.strictEqual(await toDbReaction('🍮'), '🍮');
});
it('プリン以外の既存のリアクションは文字列化する like', async () => {
assert.strictEqual(await toDbReaction('👍'), 'like');
});
it('プリン以外の既存のリアクションは文字列化する love', async () => {
assert.strictEqual(await toDbReaction('❤️'), 'love');
});
it('プリン以外の既存のリアクションは文字列化する love 異体字セレクタなし', async () => {
assert.strictEqual(await toDbReaction('❤'), 'love');
});
it('プリン以外の既存のリアクションは文字列化する laugh', async () => {
assert.strictEqual(await toDbReaction('😆'), 'laugh');
});
it('プリン以外の既存のリアクションは文字列化する hmm', async () => {
assert.strictEqual(await toDbReaction('🤔'), 'hmm');
});
it('プリン以外の既存のリアクションは文字列化する surprise', async () => {
assert.strictEqual(await toDbReaction('😮'), 'surprise');
});
it('プリン以外の既存のリアクションは文字列化する congrats', async () => {
assert.strictEqual(await toDbReaction('🎉'), 'congrats');
});
it('プリン以外の既存のリアクションは文字列化する angry', async () => {
assert.strictEqual(await toDbReaction('💢'), 'angry');
});
it('プリン以外の既存のリアクションは文字列化する confused', async () => {
assert.strictEqual(await toDbReaction('😥'), 'confused');
});
it('プリン以外の既存のリアクションは文字列化する rip', async () => {
assert.strictEqual(await toDbReaction('😇'), 'rip');
});
it('それ以外はUnicodeのまま', async () => {
assert.strictEqual(await toDbReaction('🍅'), '🍅');
});
it('異体字セレクタ除去', async () => {
assert.strictEqual(await toDbReaction('㊗️'), '㊗');
});
it('異体字セレクタ除去 必要なし', async () => {
assert.strictEqual(await toDbReaction('㊗'), '㊗');
});
it('fallback - undefined', async () => {
assert.strictEqual(await toDbReaction(undefined), 'like');
});
it('fallback - null', async () => {
assert.strictEqual(await toDbReaction(null), 'like');
});
it('fallback - empty', async () => {
assert.strictEqual(await toDbReaction(''), 'like');
});
it('fallback - unknown', async () => {
assert.strictEqual(await toDbReaction('unknown'), 'like');
});
});
*/

View file

@ -3,17 +3,15 @@ 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 * as sinon from 'sinon'; import * as sinon from 'sinon';
import { async, signup, startServer, shutdownServer, initTestDb } from '../utils.js'; import { async, signup, startServer, shutdownServer, initTestDb } from '../utils.mjs';
describe('Creating a block activity', function() { describe('Creating a block activity', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
// alice blocks bob // alice blocks bob
let alice: any; let alice, bob, carol;
let bob: any;
let carol: any;
before(async () => { before(async () => {
await initTestDb(); await initTestDb();
@ -34,10 +32,10 @@ describe('Creating a block activity', function() {
}); });
it('Should federate blocks normally', async(async () => { it('Should federate blocks normally', async(async () => {
const createBlock = (await import('../../src/services/blocking/create')).default; const createBlock = (await import('../../built/services/blocking/create')).default;
const deleteBlock = (await import('../../src/services/blocking/delete')).default; const deleteBlock = (await import('../../built/services/blocking/delete')).default;
const queues = await import('../../src/queue/index'); const queues = await import('../../built/queue/index');
const spy = sinon.spy(queues, 'deliver'); const spy = sinon.spy(queues, 'deliver');
await createBlock(alice, bob); await createBlock(alice, bob);
assert(spy.calledOnce); assert(spy.calledOnce);
@ -46,12 +44,12 @@ describe('Creating a block activity', function() {
})); }));
it('Should not federate blocks if federateBlocks is false', async () => { it('Should not federate blocks if federateBlocks is false', async () => {
const createBlock = (await import('../../src/services/blocking/create')).default; const createBlock = (await import('../../built/services/blocking/create')).default;
const deleteBlock = (await import('../../src/services/blocking/delete')).default; const deleteBlock = (await import('../../built/services/blocking/delete')).default;
alice.federateBlocks = true; alice.federateBlocks = true;
const queues = await import('../../src/queue/index'); const queues = await import('../../built/queue/index');
const spy = sinon.spy(queues, 'deliver'); const spy = sinon.spy(queues, 'deliver');
await createBlock(alice, carol); await createBlock(alice, carol);
await deleteBlock(alice, carol); await deleteBlock(alice, carol);

View file

@ -2,14 +2,14 @@ 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 { Following } from '../src/models/entities/following.js'; import { Following } from '../built/models/entities/following.js';
import { connectStream, signup, api, post, startServer, shutdownServer, initTestDb, waitFire } from './utils.js'; import { connectStream, signup, api, post, startServer, shutdownServer, initTestDb, waitFire } from './utils.mjs';
describe('Streaming', () => { describe('Streaming', () => {
let p: childProcess.ChildProcess; let p;
let Followings: any; let Followings;
const follow = async (follower: any, followee: any) => { const follow = async (follower, followee) => {
await Followings.save({ await Followings.save({
id: 'a', id: 'a',
createdAt: new Date(), createdAt: new Date(),
@ -28,16 +28,12 @@ describe('Streaming', () => {
this.timeout(20*60*1000); this.timeout(20*60*1000);
// Local users // Local users
let ayano: any; let ayano, kyoko, chitose;
let kyoko: any;
let chitose: any;
// Remote users // Remote users
let akari: any; let akari, chinatsu;
let chinatsu: any;
let kyokoNote: any; let kyokoNote, list;
let list: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -388,7 +384,7 @@ describe('Streaming', () => {
}); });
describe('Hashtag Timeline', () => { describe('Hashtag Timeline', () => {
it('指定したハッシュタグの投稿が流れる', () => new Promise<void>(async done => { it('指定したハッシュタグの投稿が流れる', () => new Promise(async done => {
const ws = await connectStream(chitose, 'hashtag', ({ type, body }) => { const ws = await connectStream(chitose, 'hashtag', ({ type, body }) => {
if (type == 'note') { if (type == 'note') {
assert.deepStrictEqual(body.text, '#foo'); assert.deepStrictEqual(body.text, '#foo');
@ -406,7 +402,7 @@ describe('Streaming', () => {
}); });
})); }));
it('指定したハッシュタグの投稿が流れる (AND)', () => new Promise<void>(async done => { it('指定したハッシュタグの投稿が流れる (AND)', () => new Promise(async done => {
let fooCount = 0; let fooCount = 0;
let barCount = 0; let barCount = 0;
let fooBarCount = 0; let fooBarCount = 0;
@ -444,7 +440,7 @@ describe('Streaming', () => {
}, 3000); }, 3000);
})); }));
it('指定したハッシュタグの投稿が流れる (OR)', () => new Promise<void>(async done => { it('指定したハッシュタグの投稿が流れる (OR)', () => new Promise(async done => {
let fooCount = 0; let fooCount = 0;
let barCount = 0; let barCount = 0;
let fooBarCount = 0; let fooBarCount = 0;
@ -490,7 +486,7 @@ describe('Streaming', () => {
}, 3000); }, 3000);
})); }));
it('指定したハッシュタグの投稿が流れる (AND + OR)', () => new Promise<void>(async done => { it('指定したハッシュタグの投稿が流れる (AND + OR)', () => new Promise(async done => {
let fooCount = 0; let fooCount = 0;
let barCount = 0; let barCount = 0;
let fooBarCount = 0; let fooBarCount = 0;

View file

@ -2,16 +2,14 @@ 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, connectStream, startServer, shutdownServer } from './utils.mjs';
describe('Note thread mute', function() { describe('Note thread mute', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let alice: any; let alice, bob, carol;
let bob: any;
let carol: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -37,9 +35,9 @@ describe('Note thread mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note) => note.id === bobNote.id), false);
assert.strictEqual(res.body.some((note: any) => note.id === carolReply.id), false); assert.strictEqual(res.body.some((note) => note.id === carolReply.id), false);
assert.strictEqual(res.body.some((note: any) => note.id === carolReplyWithoutMention.id), false); assert.strictEqual(res.body.some((note) => note.id === carolReplyWithoutMention.id), false);
})); }));
it('ミュートしているスレッドからメンションされても、hasUnreadMentions が true にならない', async(async () => { it('ミュートしているスレッドからメンションされても、hasUnreadMentions が true にならない', async(async () => {
@ -97,8 +95,8 @@ describe('Note thread mute', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.some((notification: any) => notification.note.id === carolReply.id), false); assert.strictEqual(res.body.some((notification) => notification.note.id === carolReply.id), false);
assert.strictEqual(res.body.some((notification: any) => notification.note.id === carolReplyWithoutMention.id), false); assert.strictEqual(res.body.some((notification) => notification.note.id === carolReplyWithoutMention.id), false);
// NOTE: bobの投稿はスレッドミュート前に行われたため通知に含まれていてもよい // NOTE: bobの投稿はスレッドミュート前に行われたため通知に含まれていてもよい
})); }));

View file

@ -1,41 +0,0 @@
{
"compilerOptions": {
"allowJs": true,
"noEmitOnError": false,
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedParameters": false,
"noUnusedLocals": true,
"noFallthroughCasesInSwitch": true,
"declaration": false,
"sourceMap": true,
"target": "es2017",
"module": "es2020",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"removeComments": false,
"noLib": false,
"strict": true,
"strictNullChecks": true,
"strictPropertyInitialization": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": "./",
"paths": {
"@/*": ["../src/*"]
},
"typeRoots": [
"../node_modules/@types",
"../src/@types"
],
"lib": [
"esnext"
]
},
"compileOnSave": false,
"include": [
"./**/*.ts"
]
}

View file

@ -2,17 +2,14 @@ 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, uploadUrl, startServer, shutdownServer } from './utils.js'; import { async, signup, request, post, uploadUrl, startServer, shutdownServer } from './utils.mjs';
describe('users/notes', function() { describe('users/notes', function() {
this.timeout(20*60*1000); this.timeout(20*60*1000);
let p: childProcess.ChildProcess; let p;
let alice: any; let alice, jpgNote, pngNote, jpgPngNote;
let jpgNote: any;
let pngNote: any;
let jpgPngNote: any;
before(async () => { before(async () => {
p = await startServer(); p = await startServer();
@ -43,8 +40,8 @@ describe('users/notes', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.length, 2); assert.strictEqual(res.body.length, 2);
assert.strictEqual(res.body.some((note: any) => note.id === jpgNote.id), true); assert.strictEqual(res.body.some((note) => note.id === jpgNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === jpgPngNote.id), true); assert.strictEqual(res.body.some((note) => note.id === jpgPngNote.id), true);
})); }));
it('ファイルタイプ指定 (jpg or png)', async(async () => { it('ファイルタイプ指定 (jpg or png)', async(async () => {
@ -56,8 +53,8 @@ describe('users/notes', function() {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(Array.isArray(res.body), true);
assert.strictEqual(res.body.length, 3); assert.strictEqual(res.body.length, 3);
assert.strictEqual(res.body.some((note: any) => note.id === jpgNote.id), true); assert.strictEqual(res.body.some((note) => note.id === jpgNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === pngNote.id), true); assert.strictEqual(res.body.some((note) => note.id === pngNote.id), true);
assert.strictEqual(res.body.some((note: any) => note.id === jpgPngNote.id), true); assert.strictEqual(res.body.some((note) => note.id === jpgPngNote.id), true);
})); }));
}); });

View file

@ -10,8 +10,8 @@ import * as foundkey from 'foundkey-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 '../built/config/load.js';
import { entities } from '../src/db/postgre.js'; import { entities } from '../built/db/postgre.js';
import got from 'got'; import got from 'got';
const _filename = fileURLToPath(import.meta.url); const _filename = fileURLToPath(import.meta.url);
@ -20,20 +20,20 @@ const _dirname = dirname(_filename);
const config = loadConfig(); const config = loadConfig();
export const port = config.port; export const port = config.port;
export const async = (fn: Function) => (done: Function) => { export const async = (fn) => (done) => {
fn().then(() => { fn().then(() => {
done(); done();
}, (err: Error) => { }, (err) => {
done(err); done(err);
}); });
}; };
export const api = async (endpoint: string, params: any, me?: any) => { export const api = async (endpoint, params, me) => {
endpoint = endpoint.replace(/^\//, ''); endpoint = endpoint.replace(/^\//, '');
const auth = me ? { authorization: `Bearer ${me.token}` } : {}; const auth = me ? { authorization: `Bearer ${me.token}` } : {};
const res = await got<string>(`http://localhost:${port}/api/${endpoint}`, { const res = await got(`http://localhost:${port}/api/${endpoint}`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -63,7 +63,7 @@ export const api = async (endpoint: string, params: any, me?: any) => {
}; };
}; };
export const request = async (endpoint: string, params: any, me?: any): Promise<{ body: any, status: number }> => { export const request = async (endpoint, params, me) => {
const auth = me ? { authorization: `Bearer ${me.token}` } : {}; const auth = me ? { authorization: `Bearer ${me.token}` } : {};
const res = await fetch(`http://localhost:${port}/api${endpoint}`, { const res = await fetch(`http://localhost:${port}/api${endpoint}`, {
@ -83,7 +83,7 @@ export const request = async (endpoint: string, params: any, me?: any): Promise<
}; };
}; };
export const signup = async (params?: any): Promise<any> => { export const signup = async (params) => {
const q = Object.assign({ const q = Object.assign({
username: 'test', username: 'test',
password: 'test', password: 'test',
@ -94,7 +94,7 @@ export const signup = async (params?: any): Promise<any> => {
return res.body; return res.body;
}; };
export const post = async (user: any, params?: foundkey.Endpoints['notes/create']['req']): Promise<foundkey.entities.Note> => { export const post = async (user, params) => {
const q = Object.assign({ const q = Object.assign({
text: 'test', text: 'test',
}, params); }, params);
@ -104,7 +104,7 @@ export const post = async (user: any, params?: foundkey.Endpoints['notes/create'
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, note, reaction) => {
await api('notes/reactions/create', { await api('notes/reactions/create', {
noteId: note.id, noteId: note.id,
reaction: reaction, reaction: reaction,
@ -116,10 +116,10 @@ export const react = async (user: any, note: any, reaction: string): Promise<any
* @param user User * @param user User
* @param _path Optional, absolute path or relative from ./resources/ * @param _path Optional, absolute path or relative from ./resources/
*/ */
export const uploadFile = async (user: any, _path?: string): Promise<any> => { export const uploadFile = async (user, _path) => {
const absPath = _path == null ? `${_dirname}/resources/Lenna.jpg` : path.isAbsolute(_path) ? _path : `${_dirname}/resources/${_path}`; const absPath = _path == null ? `${_dirname}/resources/Lenna.jpg` : path.isAbsolute(_path) ? _path : `${_dirname}/resources/${_path}`;
const formData = new FormData() as any; const formData = new FormData();
formData.append('i', user.token); formData.append('i', user.token);
formData.append('file', fs.createReadStream(absPath)); formData.append('file', fs.createReadStream(absPath));
formData.append('force', 'true'); formData.append('force', 'true');
@ -137,8 +137,8 @@ export const uploadFile = async (user: any, _path?: string): Promise<any> => {
return body; return body;
}; };
export const uploadUrl = async (user: any, url: string) => { export const uploadUrl = async (user, url) => {
let file: any; let file;
const ws = await connectStream(user, 'main', (msg) => { const ws = await connectStream(user, 'main', (msg) => {
if (msg.type === 'driveFileCreated') { if (msg.type === 'driveFileCreated') {
@ -157,7 +157,7 @@ export const uploadUrl = async (user: any, url: string) => {
return file; return file;
}; };
export function connectStream(user: any, channel: string, listener: (message: Record<string, any>) => any, params?: any): Promise<WebSocket> { export function connectStream(user, channel, listener, params) {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const ws = new WebSocket(`ws://localhost:${port}/streaming?i=${user.token}`); const ws = new WebSocket(`ws://localhost:${port}/streaming?i=${user.token}`);
@ -184,11 +184,11 @@ 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, params?: any) => { export const waitFire = async (user, channel, trgr, cond, params) => {
return new Promise<boolean>(async (res, rej) => { return new Promise(async (res, rej) => {
let timer: NodeJS.Timeout; let timer;
let ws: WebSocket; let ws;
try { try {
ws = await connectStream(user, channel, msg => { ws = await connectStream(user, channel, msg => {
if (cond(msg)) { if (cond(msg)) {
@ -201,7 +201,7 @@ export const waitFire = async (user: any, channel: string, trgr: () => any, cond
rej(e); rej(e);
} }
if (!ws!) return; if (!ws) return;
timer = setTimeout(() => { timer = setTimeout(() => {
ws.close(); ws.close();
@ -218,7 +218,7 @@ export const waitFire = async (user: any, channel: string, trgr: () => any, cond
}) })
}; };
export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?: number, type?: string, location?: string }> => { export const simpleGet = async (path, accept = '*/*') => {
// node-fetchだと3xxを取れない // node-fetchだと3xxを取れない
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
const req = http.request(`http://localhost:${port}${path}`, { const req = http.request(`http://localhost:${port}${path}`, {
@ -226,7 +226,7 @@ export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?
Accept: accept, Accept: accept,
}, },
}, res => { }, res => {
if (res.statusCode! >= 400) { if (res.statusCode >= 400) {
reject(res); reject(res);
} else { } else {
resolve({ resolve({
@ -241,8 +241,8 @@ export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?
}); });
}; };
export function launchServer(callbackSpawnedProcess: (p: childProcess.ChildProcess) => void, moreProcess: () => Promise<void> = async () => {}) { export function launchServer(callbackSpawnedProcess, moreProcess = async () => {}) {
return (done: (err?: Error) => any) => { return (done) => {
const p = childProcess.spawn('node', [_dirname + '/../index.js'], { const p = childProcess.spawn('node', [_dirname + '/../index.js'], {
stdio: ['inherit', 'inherit', 'inherit', 'ipc'], stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
env: { NODE_ENV: 'test', PATH: process.env.PATH }, env: { NODE_ENV: 'test', PATH: process.env.PATH },
@ -254,7 +254,7 @@ export function launchServer(callbackSpawnedProcess: (p: childProcess.ChildProce
}; };
} }
export async function initTestDb(justBorrow = false, initEntities?: any[]) { export async function initTestDb(justBorrow = false, initEntities) {
if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test'; if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test';
const db = new DataSource({ const db = new DataSource({
@ -274,7 +274,7 @@ export async function initTestDb(justBorrow = false, initEntities?: any[]) {
return db; return db;
} }
export function startServer(timeout = 60 * 1000): Promise<childProcess.ChildProcess> { export function startServer(timeout = 60 * 1000) {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const t = setTimeout(() => { const t = setTimeout(() => {
p.kill(SIGKILL); p.kill(SIGKILL);
@ -297,7 +297,7 @@ export function startServer(timeout = 60 * 1000): Promise<childProcess.ChildProc
}); });
} }
export function shutdownServer(p: childProcess.ChildProcess, timeout = 20 * 1000) { export function shutdownServer(p, timeout = 20 * 1000) {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const t = setTimeout(() => { const t = setTimeout(() => {
p.kill(SIGKILL); p.kill(SIGKILL);
@ -313,8 +313,8 @@ export function shutdownServer(p: childProcess.ChildProcess, timeout = 20 * 1000
}); });
} }
export function sleep(msec: number) { export function sleep(msec) {
return new Promise<void>(res => { return new Promise(res => {
setTimeout(() => { setTimeout(() => {
res(); res();
}, msec); }, msec);