-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
helpers-v5.js
484 lines (456 loc) · 14.6 KB
/
helpers-v5.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// It's helpful to see the full error stack
Error.stackTraceLimit = Infinity;
if (process.env.DEBUG) {
// When debug is set, outputting the console logs makes the tests slow.
jest.setTimeout(30000);
}
import { readFile as readFileRaw, writeFile as writeFileRaw } from "fs";
import { formatSQLForDebugging } from "graphile-build-pg";
import {
getOperationAST,
parse,
validate,
validateSchema,
execute,
subscribe,
lexicographicSortSchema,
printSchema,
} from "graphql";
import { isAsyncIterable } from "iterall";
import JSON5 from "json5";
import { withPgClient, getServerVersionNum } from "./helpers";
import jsonwebtoken from "jsonwebtoken";
import { createPostGraphileSchema } from "..";
import { makeExtendSchemaPlugin, gql } from "graphile-utils";
import ToyCategoriesPlugin from "./integration/ToyCategoriesPlugin";
/**
* We go beyond what Jest snapshots allow; so we have to manage it ourselves.
* If UPDATE_SNAPSHOTS is set then we'll write updated snapshots, otherwise
* we'll do the default behaviour of comparing to existing snapshots.
*/
export const UPDATE_SNAPSHOTS = process.env.UPDATE_SNAPSHOTS === "1";
const SHARED_JWT_SECRET =
"This is static for the tests, use a better one if you set one!";
function readFile(filename, encoding) {
return new Promise((resolve, reject) => {
readFileRaw(filename, encoding, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
}
function writeFile(filename, data) {
return new Promise((resolve, reject) => {
writeFileRaw(filename, data, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
}
/** Sorts two GraphQLError paths. */
const pathCompare = (path1, path2) => {
const l = Math.min(path1.length, path2.length);
for (let i = 0; i < l; i++) {
const a = path1[i];
const z = path2[i];
if (typeof a === "number") {
if (typeof z !== "number") {
throw new Error("Type mismatch; expected number");
}
const v = a - z;
if (v !== 0) {
return v;
}
} else if (typeof a === "string") {
if (typeof z !== "string") {
throw new Error("Type mismatch; expected string");
}
const v = a.localeCompare(z);
if (v !== 0) {
return v;
}
} else {
throw new Error("Unexpected type");
}
}
return path1.length - path2.length;
};
export async function runTestQuery(
schema,
source,
config,
options = Object.create(null)
) {
const schemaValidationErrors = validateSchema(schema);
if (schemaValidationErrors.length > 0) {
throw new Error(
`Invalid schema: ${schemaValidationErrors.map(e => String(e)).join(",")}`
);
}
const { variableValues } = config;
const { path } = options;
return withPgClient(async pgClient => {
if (options.onConnect) {
await options.onConnect(pgClient);
}
const queries = [];
const oldQuery = pgClient.query;
pgClient.query = function (...args) {
queries.push(args[0].text ? args[0] : { text: args[0], values: args[1] });
return oldQuery.apply(this, args);
};
try {
// Return the result of our GraphQL query.
const document = parse(source);
const operationAST = getOperationAST(document, undefined);
const operationType = operationAST.operation;
const validationErrors = validate(schema, document);
if (validationErrors.length > 0) {
throw new Error(
`Invalid operation document: ${validationErrors
.map(e => String(e))
.join(",")}`
);
}
const contextValue = {
pgClient,
};
const result =
operationType === "subscription"
? await subscribe({
schema,
document,
variableValues,
contextValue,
})
: await execute({
schema,
document,
variableValues,
contextValue,
});
if (isAsyncIterable(result)) {
let errors = undefined;
// hasNext changes based on payload order; remove it.
const originalPayloads = [];
// Start collecting the payloads
const promise = (async () => {
for await (const entry of result) {
const { hasNext, ...rest } = entry;
if (Object.keys(rest).length > 0 || hasNext) {
// Do not add the trailing `{hasNext: false}` entry to the snapshot
originalPayloads.push(rest);
}
if (entry.errors) {
if (!errors) {
errors = [];
}
errors.push(...entry.errors);
}
}
})();
// In parallel to collecting the payloads, run the callback
if (options.callback) {
throw new Error("Unsupported in V4");
}
if (operationType === "subscription") {
const iterator = result[Symbol.asyncIterator]();
// Terminate the subscription
iterator.return?.();
}
// Now wait for all payloads to have been collected
await promise;
// Now we're going to reorder the payloads so that they're always in a
// consistent order for the snapshots.
const sortPayloads = (payload1, payload2) => {
const ONE_AFTER_TWO = 1;
const ONE_BEFORE_TWO = -1;
if (!payload1.path) {
return 0;
}
if (!payload2.path) {
return 0;
}
// Make it so we can assume payload1 has the longer (or equal) path
if (payload2.path.length > payload1.path.length) {
return -sortPayloads(payload2, payload1);
}
for (let i = 0, l = payload1.path.length; i < l; i++) {
let key1 = payload1.path[i];
let key2 = payload2.path[i];
if (key2 === undefined) {
return ONE_AFTER_TWO;
}
if (key1 === key2) {
/* continue */
} else if (typeof key1 === "number" && typeof key2 === "number") {
const res = key1 - key2;
if (res !== 0) {
return res;
}
} else if (typeof key1 === "string" && typeof key2 === "string") {
const res = key1.localeCompare(key2);
if (res !== 0) {
return res;
}
} else {
throw new Error("Type mismatch");
}
}
// We should do canonical JSON... but whatever.
return JSON.stringify(payload1).localeCompare(
JSON.stringify(payload2)
);
};
const payloads = [
originalPayloads[0],
...originalPayloads.slice(1).sort(sortPayloads),
];
return {
payloads,
errors,
queries,
extensions: payloads[0].extensions,
};
} else {
// Throw away symbol keys/etc
const { data, errors, extensions } = JSON.parse(JSON.stringify(result));
if (errors) {
console.error(errors[0].originalError || errors[0]);
}
if (options.callback) {
throw new Error(
"Callback is only appropriate when operation returns an async iterable" +
String(errors ? errors[0].originalError || errors[0] : "")
);
}
return { data, errors, queries, extensions };
}
} finally {
//eslint-disable-next-line require-atomic-updates
pgClient.query = oldQuery;
}
});
}
/**
* If UPDATE_SNAPSHOTS is set then wrotes the given snapshot to the given
* filePath, otherwise it asserts that the snapshot matches the previous
* snapshot.
*/
async function snapshot(actual, filePath) {
let expected = null;
try {
expected = await readFile(filePath, "utf8");
} catch (e) {
/* noop */
}
if (expected == null || UPDATE_SNAPSHOTS) {
if (expected !== actual) {
console.warn(`Updated snapshot in '${filePath}'`);
await writeFile(filePath, actual);
}
} else {
expect(actual).toEqual(expected);
}
}
const sqlSnapshotAliases = new Map();
let sqlSnapshotAliasCount = 0;
beforeEach(() => {
sqlSnapshotAliases.clear();
sqlSnapshotAliasCount = 0;
});
afterAll(() => {
sqlSnapshotAliases.clear();
});
/**
* Replace non-deterministic parts of the query with more deterministic
* equivalents.
*/
function makeSQLSnapshotSafe(sql) {
return sql.replace(/__cursor_[0-9]+__/g, t => {
const substitute = sqlSnapshotAliases.get(t);
if (substitute != null) {
return substitute;
} else {
const sub = `__SNAPSHOT_CURSOR_${sqlSnapshotAliasCount++}__`;
sqlSnapshotAliases.set(t, sub);
return sub;
}
});
}
const UUID_REGEXP = /^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
/**
* Replaces non-deterministic parts of the response with more deterministic
* equivalents.
*/
function makeResultSnapshotSafe(data, replacements) {
if (Array.isArray(data)) {
return data.map(entry => makeResultSnapshotSafe(entry, replacements));
} else if (typeof data === "object") {
if (data == null) {
return data;
}
const keys = Object.keys(data);
return keys.reduce((memo, key) => {
if (key.startsWith("jwt") && typeof data[key] === "string") {
try {
const content = jsonwebtoken.decode(data[key]);
if (typeof content.iat === "number") {
content.iat = "<number>";
}
memo[key] = `JWT<${JSON5.stringify(content)} (unverified)>`;
return memo;
} catch (e) {
// ignore
}
}
memo[key] = makeResultSnapshotSafe(data[key], replacements);
return memo;
}, {});
} else if (
typeof data === "string" &&
UUID_REGEXP.test(data) &&
!data.includes("-0000-0000-")
) {
const uuidNumber = replacements.uuid.has(data)
? replacements.uuid.get(data)
: replacements.uuidCounter++;
if (!replacements.uuid.has(data)) {
replacements.uuid.set(data, uuidNumber);
}
return `<UUID ${uuidNumber}>`;
} else {
return data;
}
}
function makePayloadSnapshotSafe(payload, replacements) {
const p = { ...payload };
delete p.extensions;
return makeResultSnapshotSafe(p, replacements);
}
// This regexp extracted from https://github.com/chalk/ansi-regex MIT license
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
// Copyright (c) Benjie (https://twitter.com/benjie)
export const ANSI_REGEXP =
// eslint-disable-next-line no-control-regex, no-useless-escape
/[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;
function stripAnsi(str) {
return str.replace(ANSI_REGEXP, "");
}
/**
* Build the snapshot for the given mode ('only') and then assert it matches
* (or store it).
*/
export const assertSnapshotsMatch = async (only, props) => {
const { path, result, ext } = props;
const basePath = path.replace(/\.test\.graphql$/, "");
if (basePath === path) {
throw new Error(`Failed to trim .test.graphql from '${path}'`);
}
const resultValue = await result;
if (resultValue === null) {
return;
}
const { data, payloads, queries, errors, extensions } = resultValue;
const replacements = { uuid: new Map(), uuidCounter: 1 };
if (only === "result") {
const resultFileName = basePath + (ext || "") + ".json5";
const processedResults = payloads
? payloads.map(payload => makePayloadSnapshotSafe(payload, replacements))
: makePayloadSnapshotSafe(data, replacements);
const formattedData =
//prettier.format(
JSON5.stringify(processedResults, {
space: 2,
quote: '"',
}) + "\n";
// , {
// parser: "json5",
// printWidth: 120,
// });
await snapshot(formattedData, resultFileName);
} else if (only === "errors") {
const errorsFileName = basePath + (ext || "") + ".errors.json5";
const processedErrors = errors
? makeResultSnapshotSafe(errors, replacements).sort((e1, e2) => {
return pathCompare(e1.path, e2.path);
})
: null;
const formattedErrors = processedErrors //prettier.format(
? JSON5.stringify(processedErrors, null, 2)
: "null";
// {
// parser: "json5",
// printWidth: 120,
// },
// );
await snapshot(formattedErrors, errorsFileName);
} else if (only === "sql") {
const sqlFileName = basePath + (ext || "") + ".sql";
const formattedQueries = queries
.map(q => makeSQLSnapshotSafe(stripAnsi(formatSQLForDebugging(q.text))))
.join("\n\n");
await snapshot(formattedQueries, sqlFileName);
} else {
throw new Error(
`Unexpected argument to assertSnapshotsMatch; expected result|sql, received '${only}'`
);
}
};
const ExtendedPlugin = makeExtendSchemaPlugin({
typeDefs: gql`
extend type Query {
extended: Boolean
}
`,
resolvers: {
Query: {
extended: () => true,
},
},
});
const dSchemaComments = () =>
readFile(`${__dirname}/kitchen-sink-d-schema-comments.sql`, "utf8");
const isNotNullish = t => t != null;
const makeSchema = config => {
return withPgClient(async pgClient => {
// A selection of omit/rename comments on the d schema
const serverVersionNum = await getServerVersionNum(pgClient);
if (config.requiresPg && serverVersionNum < config.requiresPg) {
return null;
}
await pgClient.query(await dSchemaComments());
if (config.ignoreRBAC === false) {
await pgClient.query("set role postgraphile_test_authenticator");
}
return createPostGraphileSchema(
pgClient,
config.schema ?? ["a", "b", "c"],
{
subscriptions: config.subscriptions,
classicIds: config.classicIds,
dynamicJson: config.dynamicJson,
setofFunctionsContainNulls: config.setofFunctionsContainNulls,
simpleCollections: config.simpleCollections,
graphileBuildOptions: config.graphileBuildOptions,
ignoreRBAC: config.ignoreRBAC,
jwtPgTypeIdentifier: config.jwtPgTypeIdentifier,
viewUniqueKey: config.viewUniqueKey,
jwtSecret:
config.jwtSecret === true ? SHARED_JWT_SECRET : config.jwtSecret,
appendPlugins: [
ExtendedPlugin,
config.ToyCategoriesPlugin ? ToyCategoriesPlugin : null,
].filter(isNotNullish),
}
);
});
};
exports.makeSchema = makeSchema;
exports.testSchema = async (path, config) => {
const schema = await makeSchema(config);
const sortedSchema = lexicographicSortSchema(schema);
const basePath = path.replace(/\.test\.js/, "");
const filePath = basePath + ".schema.graphql";
await snapshot(printSchema(sortedSchema), filePath);
};