-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
hooks.ts
73 lines (60 loc) · 1.95 KB
/
hooks.ts
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
import * as FS from 'fs'
import got, { Got } from 'got'
import { Context, RootHookObject } from 'mocha'
import { beforeEachSuite } from 'mocha-suite-hooks'
import { startNginx, NginxServer } from 'nginx-testing'
const certificate = FS.readFileSync(`${__dirname}/fixtures/server.crt`)
const host = '127.0.0.1'
const nginxConfig = `${__dirname}/nginx.conf`
const nginxVersion = process.env.NGINX_VERSION || '1.24.x'
declare module 'mocha' {
export interface Context {
client: Got
nginx: NginxServer
}
}
export const mochaHooks: RootHookObject = {
async beforeAll (this: Context) {
this.timeout(30_000)
this.nginx = await startNginx({ version: nginxVersion, bindAddress: host, configPath: nginxConfig })
const errors = (await this.nginx.readErrorLog())
.split('\n')
.filter(line => line.includes('[error]'))
if (errors) {
console.error(errors.join('\n'))
}
this.client = got.extend({
https: {
certificateAuthority: certificate,
},
prefixUrl: `https://${host}:${this.nginx.port}`,
retry: 0,
throwHttpErrors: false,
})
beforeEachSuite (async function () {
// Read the logs to consume (discard) them before running next test suite
// (describe block).
await this.nginx.readErrorLog()
await this.nginx.readAccessLog()
})
},
async afterAll (this: Context) {
if (this.nginx) {
await this.nginx.stop()
}
},
async afterEach (this: Context) {
const { currentTest, nginx } = this
if (currentTest?.state === 'failed' && currentTest.err) {
const errorLog = await nginx.readErrorLog()
const accessLog = await nginx.readAccessLog()
const logs = [
errorLog && '----- Error Log -----\n' + errorLog,
accessLog && '----- Access Log -----\n' + accessLog,
].filter(Boolean)
if (logs.length > 0) {
currentTest.err.stack += '\n\n' + logs.join('\n\n').replace(/^/gm, ' ')
}
}
}
}