From 80f207fdddb435d945e689c8fe64664b8fa552dd Mon Sep 17 00:00:00 2001
From: MeiMei <30769358+mei23@users.noreply.github.com>
Date: Sat, 12 Jun 2021 22:40:17 +0900
Subject: [PATCH] =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=81=8C=E3=81=86?=
 =?UTF-8?q?=E3=81=94=E3=81=8B=E3=81=AA=E3=81=84=E3=81=AE=E3=82=92=E4=BF=AE?=
 =?UTF-8?q?=E6=AD=A3=20(#7566)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

* startServer

* typeorm 0.2.32

* Fix: chartのテストがテストの並び順によっては正しく初期化されない

* initTestDb
---
 .mocharc.json          |  2 +-
 package.json           |  2 +-
 test/api-visibility.ts |  6 +++--
 test/chart.ts          | 54 +++++++-----------------------------------
 test/fetch-resource.ts |  7 +++---
 test/mute.ts           |  7 +++---
 test/note.ts           | 10 ++++----
 test/streaming.ts      | 14 +++++------
 test/user-notes.ts     |  7 +++---
 test/utils.ts          | 49 +++++++++++++++++++++++++++++++++++++-
 yarn.lock              |  8 +++----
 11 files changed, 91 insertions(+), 75 deletions(-)

diff --git a/.mocharc.json b/.mocharc.json
index fc7fee215..278a5b310 100644
--- a/.mocharc.json
+++ b/.mocharc.json
@@ -2,6 +2,6 @@
 	"extension": ["ts","js","cjs","mjs"],
 	"require": ["ts-node/register", "tsconfig-paths/register"],
 	"slow": 1000,
-	"timeout": 30000,
+	"timeout": 35000,
 	"exit": true
 }
diff --git a/package.json b/package.json
index 3d92c47cd..a6b0e5e66 100644
--- a/package.json
+++ b/package.json
@@ -233,7 +233,7 @@
 		"tslint": "6.1.3",
 		"tslint-sonarts": "1.9.0",
 		"twemoji-parser": "13.1.0",
-		"typeorm": "0.2.34",
+		"typeorm": "0.2.32",
 		"typescript": "4.3.2",
 		"ulid": "2.3.0",
 		"uuid": "8.3.2",
diff --git a/test/api-visibility.ts b/test/api-visibility.ts
index c4ec32193..6548146c7 100644
--- a/test/api-visibility.ts
+++ b/test/api-visibility.ts
@@ -12,12 +12,14 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { async, signup, request, post, launchServer, shutdownServer } from './utils';
+import { async, signup, request, post, startServer, shutdownServer } from './utils';
 
 describe('API visibility', () => {
 	let p: childProcess.ChildProcess;
 
-	before(launchServer(g => p = g));
+	before(async () => {
+		p = await startServer();
+	});
 
 	after(async () => {
 		await shutdownServer(p);
diff --git a/test/chart.ts b/test/chart.ts
index 55f6bd696..4a40b2553 100644
--- a/test/chart.ts
+++ b/test/chart.ts
@@ -12,61 +12,28 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as lolex from '@sinonjs/fake-timers';
-import { async } from './utils';
+import { async, initTestDb } from './utils';
 import TestChart from '../src/services/chart/charts/classes/test';
 import TestGroupedChart from '../src/services/chart/charts/classes/test-grouped';
 import TestUniqueChart from '../src/services/chart/charts/classes/test-unique';
 import * as _TestChart from '../src/services/chart/charts/schemas/test';
 import * as _TestGroupedChart from '../src/services/chart/charts/schemas/test-grouped';
 import * as _TestUniqueChart from '../src/services/chart/charts/schemas/test-unique';
-import { Connection, getConnection, createConnection } from 'typeorm';
-import config from '../src/config';
 import Chart from '../src/services/chart/core';
-import { initDb } from '../src/db/postgre';
-
-function initChartDb() {
-	try {
-		const conn = getConnection();
-		return Promise.resolve(conn);
-	} catch (e) {}
-
-	return createConnection({
-		type: 'postgres',
-		host: config.db.host,
-		port: config.db.port,
-		username: config.db.user,
-		password: config.db.pass,
-		database: config.db.db,
-		synchronize: true,
-		dropSchema: true,
-		entities: [
-			Chart.schemaToEntity(_TestChart.name, _TestChart.schema),
-			Chart.schemaToEntity(_TestGroupedChart.name, _TestGroupedChart.schema),
-			Chart.schemaToEntity(_TestUniqueChart.name, _TestUniqueChart.schema)
-		]
-	});
-}
 
 describe('Chart', () => {
 	let testChart: TestChart;
 	let testGroupedChart: TestGroupedChart;
 	let testUniqueChart: TestUniqueChart;
-	let clock: lolex.InstalledClock;
-	let connection: Connection;
+	let clock: lolex.Clock;
 
-	before(done => {
-		initChartDb().then(c => {
-			connection = c;
-			done();
-		});
-	});
+	beforeEach(async(async () => {
+		await initTestDb(false, [
+			Chart.schemaToEntity(_TestChart.name, _TestChart.schema),
+			Chart.schemaToEntity(_TestGroupedChart.name, _TestGroupedChart.schema),
+			Chart.schemaToEntity(_TestUniqueChart.name, _TestUniqueChart.schema)
+		]);
 
-	after(async(async () => {
-		await connection.close();
-		await initDb(true, undefined, true);
-	}));
-
-	beforeEach(done => {
 		testChart = new TestChart();
 		testGroupedChart = new TestGroupedChart();
 		testUniqueChart = new TestUniqueChart();
@@ -74,13 +41,10 @@ describe('Chart', () => {
 		clock = lolex.install({
 			now: new Date(Date.UTC(2000, 0, 1, 0, 0, 0))
 		});
-		done();
-	});
+	}));
 
 	afterEach(async(async () => {
 		clock.uninstall();
-		await connection.dropDatabase();
-		await connection.synchronize();
 	}));
 
 	it('Can updates', async(async () => {
diff --git a/test/fetch-resource.ts b/test/fetch-resource.ts
index e9d10d1ab..31308b08f 100644
--- a/test/fetch-resource.ts
+++ b/test/fetch-resource.ts
@@ -12,7 +12,7 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { async, launchServer, signup, post, request, simpleGet, port, shutdownServer } from './utils';
+import { async, startServer, signup, post, request, simpleGet, port, shutdownServer } from './utils';
 import * as openapi from '@redocly/openapi-core';
 
 // Request Accept
@@ -32,12 +32,13 @@ describe('Fetch resource', () => {
 	let alice: any;
 	let alicesPost: any;
 
-	before(launchServer(g => p = g, async () => {
+	before(async () => {
+		p = await startServer();
 		alice = await signup({ username: 'alice' });
 		alicesPost = await post(alice, {
 			text: 'test'
 		});
-	}));
+	});
 
 	after(async () => {
 		await shutdownServer(p);
diff --git a/test/mute.ts b/test/mute.ts
index 38911b6e1..632f60fa4 100644
--- a/test/mute.ts
+++ b/test/mute.ts
@@ -12,7 +12,7 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { async, signup, request, post, react, connectStream, launchServer, shutdownServer } from './utils';
+import { async, signup, request, post, react, connectStream, startServer, shutdownServer } from './utils';
 
 describe('Mute', () => {
 	let p: childProcess.ChildProcess;
@@ -22,11 +22,12 @@ describe('Mute', () => {
 	let bob: any;
 	let carol: any;
 
-	before(launchServer(g => p = g, async () => {
+	before(async () => {
+		p = await startServer();
 		alice = await signup({ username: 'alice' });
 		bob = await signup({ username: 'bob' });
 		carol = await signup({ username: 'carol' });
-	}));
+	});
 
 	after(async () => {
 		await shutdownServer(p);
diff --git a/test/note.ts b/test/note.ts
index 3f1700577..31aaf00da 100644
--- a/test/note.ts
+++ b/test/note.ts
@@ -12,9 +12,8 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { async, signup, request, post, uploadFile, launchServer, shutdownServer } from './utils';
+import { async, signup, request, post, uploadFile, startServer, shutdownServer, initTestDb } from './utils';
 import { Note } from '../src/models/entities/note';
-import { initDb } from '../src/db/postgre';
 
 describe('Note', () => {
 	let p: childProcess.ChildProcess;
@@ -23,12 +22,13 @@ describe('Note', () => {
 	let alice: any;
 	let bob: any;
 
-	before(launchServer(g => p = g, async () => {
-		const connection = await initDb(true);
+	before(async () => {
+		p = await startServer();
+		const connection = await initTestDb(true);
 		Notes = connection.getRepository(Note);
 		alice = await signup({ username: 'alice' });
 		bob = await signup({ username: 'bob' });
-	}));
+	});
 
 	after(async () => {
 		await shutdownServer(p);
diff --git a/test/streaming.ts b/test/streaming.ts
index 214fdeb1f..cc3168e98 100644
--- a/test/streaming.ts
+++ b/test/streaming.ts
@@ -12,21 +12,21 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { connectStream, signup, request, post, launchServer } from './utils';
+import { connectStream, signup, request, post, startServer, shutdownServer, initTestDb } from './utils';
 import { Following } from '../src/models/entities/following';
-import { initDb } from '../src/db/postgre';
 
 describe('Streaming', () => {
 	let p: childProcess.ChildProcess;
 	let Followings: any;
 
-	beforeEach(launchServer(g => p = g, async () => {
-		const connection = await initDb(true);
+	beforeEach(async () => {
+		p = await startServer();
+		const connection = await initTestDb(true);
 		Followings = connection.getRepository(Following);
-	}));
+	});
 
-	afterEach(() => {
-		p.kill();
+	afterEach(async () => {
+		await shutdownServer(p);
 	});
 
 	const follow = async (follower: any, followee: any) => {
diff --git a/test/user-notes.ts b/test/user-notes.ts
index 4af8ce0cc..30589f814 100644
--- a/test/user-notes.ts
+++ b/test/user-notes.ts
@@ -12,7 +12,7 @@ process.env.NODE_ENV = 'test';
 
 import * as assert from 'assert';
 import * as childProcess from 'child_process';
-import { async, signup, request, post, uploadFile, launchServer, shutdownServer } from './utils';
+import { async, signup, request, post, uploadFile, startServer, shutdownServer } from './utils';
 
 describe('users/notes', () => {
 	let p: childProcess.ChildProcess;
@@ -22,7 +22,8 @@ describe('users/notes', () => {
 	let pngNote: any;
 	let jpgPngNote: any;
 
-	before(launchServer(g => p = g, async () => {
+	before(async () => {
+		p = await startServer();
 		alice = await signup({ username: 'alice' });
 		const jpg = await uploadFile(alice, __dirname + '/resources/Lenna.jpg');
 		const png = await uploadFile(alice, __dirname + '/resources/Lenna.png');
@@ -35,7 +36,7 @@ describe('users/notes', () => {
 		jpgPngNote = await post(alice, {
 			fileIds: [jpg.id, png.id]
 		});
-	}));
+	});
 
 	after(async() => {
 		await shutdownServer(p);
diff --git a/test/utils.ts b/test/utils.ts
index e4c96d0e1..1a0c54463 100644
--- a/test/utils.ts
+++ b/test/utils.ts
@@ -6,8 +6,11 @@ import * as childProcess from 'child_process';
 import * as http from 'http';
 import loadConfig from '../src/config/load';
 import { SIGKILL } from 'constants';
+import { createConnection, getConnection } from 'typeorm';
+import { entities } from '../src/db/postgre';
 
-export const port = loadConfig().port;
+const config = loadConfig();
+export const port = config.port;
 
 export const async = (fn: Function) => (done: Function) => {
 	fn().then(() => {
@@ -147,6 +150,50 @@ export function launchServer(callbackSpawnedProcess: (p: childProcess.ChildProce
 	};
 }
 
+export async function initTestDb(justBorrow = false, initEntities?: any[]) {
+	if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test';
+
+	try {
+		const conn = await getConnection();
+		await conn.close();
+	} catch (e) {}
+
+	return await createConnection({
+		type: 'postgres',
+		host: config.db.host,
+		port: config.db.port,
+		username: config.db.user,
+		password: config.db.pass,
+		database: config.db.db,
+		synchronize: true && !justBorrow,
+		dropSchema: true && !justBorrow,
+		entities: initEntities || entities
+	});
+}
+
+export function startServer(timeout = 30 * 1000): Promise<childProcess.ChildProcess> {
+	return new Promise((res, rej) => {
+		const t = setTimeout(() => {
+			p.kill(SIGKILL);
+			rej('timeout to start');
+		}, timeout);
+
+		const p = childProcess.spawn('node', [__dirname + '/../index.js'], {
+			stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
+			env: { NODE_ENV: 'test', PATH: process.env.PATH }
+		});
+
+		p.on('error', e => rej(e));
+
+		p.on('message', message => {
+			if (message === 'ok') {
+				clearTimeout(t);
+				res(p);
+			}
+		});
+	});
+}
+
 export function shutdownServer(p: childProcess.ChildProcess, timeout = 20 * 1000) {
 	return new Promise((res, rej) => {
 		const t = setTimeout(() => {
diff --git a/yarn.lock b/yarn.lock
index 58ce75ada..3c471bd1b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -10973,10 +10973,10 @@ typedarray@^0.0.6:
   resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777"
   integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=
 
-typeorm@0.2.34:
-  version "0.2.34"
-  resolved "https://registry.yarnpkg.com/typeorm/-/typeorm-0.2.34.tgz#637b3cec2de54ee7f423012b813a2022c0aacc8b"
-  integrity sha512-FZAeEGGdSGq7uTH3FWRQq67JjKu0mgANsSZ04j3kvDYNgy9KwBl/6RFgMVgiSgjf7Rqd7NrhC2KxVT7I80qf7w==
+typeorm@0.2.32:
+  version "0.2.32"
+  resolved "https://registry.yarnpkg.com/typeorm/-/typeorm-0.2.32.tgz#544dbfdfe0cd0887548d9bcbd28527ea4f4b3c9b"
+  integrity sha512-LOBZKZ9As3f8KRMPCUT2H0JZbZfWfkcUnO3w/1BFAbL/X9+cADTF6bczDGGaKVENJ3P8SaKheKmBgpt5h1x+EQ==
   dependencies:
     "@sqltools/formatter" "^1.2.2"
     app-root-path "^3.0.0"