/
snapshotSerializer.ts
98 lines (86 loc) · 2.38 KB
/
snapshotSerializer.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
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
const path = require('path')
const replaceAll = require('replace-string') // sindre's replaceAll polyfill
const stripAnsi = require('strip-ansi')
const { platforms } = require('@prisma/get-platform')
const escapeString = require('escape-string-regexp')
function trimErrorPaths(str) {
const parentDir = path.dirname(path.dirname(__dirname))
return replaceAll(str, parentDir, '')
}
function normalizeToUnixPaths(str) {
return replaceAll(str, path.sep, '/')
}
const platformRegex = new RegExp(
'(' + platforms.map((p) => escapeString(p)).join('|') + ')',
'g',
)
function removePlatforms(str) {
return str.replace(platformRegex, 'TEST_PLATFORM')
}
function normalizeGithubLinks(str) {
return str.replace(
/https:\/\/github.com\/prisma\/prisma-client-js\/issues\/\S+/,
'TEST_GITHUB_LINK',
)
}
function normalizeRustError(str) {
return str
.replace(/\/rustc\/(.+)\//g, '/rustc/hash/')
.replace(/(\[.*)(:\d*:\d*)(\])/g, '[/some/rust/path:0:0$3')
}
function normalizeTmpDir(str) {
return str.replace(/\/tmp\/([a-z0-9]+)\//g, '/tmp/dir/')
}
function normalizeMs(str) {
return str.replace(/\d{1,3}ms/g, 'XXms')
}
const serializer = {
test(value) {
return typeof value === 'string' || value instanceof Error
},
serialize(value) {
const message =
typeof value === 'string'
? value
: value instanceof Error
? value.message
: ''
return prepareSchemaForSnapshot(
normalizeGithubLinks(
normalizeRustError(
normalizeMs(
normalizeTmpDir(
normalizeGithubLinks(
normalizeToUnixPaths(
removePlatforms(trimErrorPaths(stripAnsi(message))),
),
),
),
),
),
),
)
},
}
/**
* Replace dynamic variable bits of Prisma schema with static strings.
*/
export function prepareSchemaForSnapshot(schema: string): string {
const urlRegex = /url\s*=\s*.+/
const outputRegex = /output\s*=\s*.+/
return schema
.split('\n')
.map((line) => {
const urlMatch = urlRegex.exec(line)
if (urlMatch) {
return `${line.slice(0, urlMatch.index)}url = "***"`
}
const outputMatch = outputRegex.exec(line)
if (outputMatch) {
return `${line.slice(0, outputMatch.index)}output = "***"`
}
return line
})
.join('\n')
}
module.exports = serializer