-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathrunQuery.test.ts
More file actions
653 lines (585 loc) · 18.1 KB
/
Copy pathrunQuery.test.ts
File metadata and controls
653 lines (585 loc) · 18.1 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/* tslint:disable:no-unused-expression */
import MockReq = require('mock-req');
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLNonNull,
parse,
DocumentNode,
} from 'graphql';
import {
GraphQLExtensionStack,
GraphQLExtension,
GraphQLResponse,
} from 'graphql-extensions';
import { processGraphQLRequest, GraphQLRequest } from '../requestPipeline';
import { Request } from 'apollo-server-env';
import { GraphQLOptions, Context as GraphQLContext } from 'apollo-server-core';
import {
ApolloServerPlugin,
GraphQLRequestListener,
} from 'apollo-server-plugin-base';
import { InMemoryLRUCache } from 'apollo-server-caching';
// This is a temporary kludge to ensure we preserve runQuery behavior with the
// GraphQLRequestProcessor refactoring.
// These tests will be rewritten as GraphQLRequestProcessor tests after the
// refactoring is complete.
function runQuery(options: QueryOptions): Promise<GraphQLResponse> {
const request: GraphQLRequest = {
query: options.queryString,
operationName: options.operationName,
variables: options.variables,
extensions: options.extensions,
http: options.request,
};
return processGraphQLRequest(options, {
request,
context: options.context || {},
debug: options.debug,
cache: {} as any,
});
}
interface QueryOptions
extends Pick<
GraphQLOptions<GraphQLContext<any>>,
| 'cacheControl'
| 'context'
| 'debug'
| 'documentStore'
| 'extensions'
| 'fieldResolver'
| 'formatError'
| 'formatResponse'
| 'plugins'
| 'rootValue'
| 'schema'
| 'tracing'
| 'validationRules'
> {
queryString?: string;
parsedQuery?: DocumentNode;
variables?: { [key: string]: any };
operationName?: string;
request: Pick<Request, 'url' | 'method' | 'headers'>;
}
const queryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
testString: {
type: GraphQLString,
resolve() {
return 'it works';
},
},
testObject: {
type: new GraphQLObjectType({
name: 'TestObject',
fields: {
testString: {
type: GraphQLString,
},
},
}),
resolve() {
return {
testString: 'a very test string',
};
},
},
testRootValue: {
type: GraphQLString,
resolve(root) {
return root + ' works';
},
},
testContextValue: {
type: GraphQLString,
resolve(_parent, _args, context) {
return context.s + ' works';
},
},
testArgumentValue: {
type: GraphQLInt,
resolve(_parent, args) {
return args['base'] + 5;
},
args: {
base: { type: new GraphQLNonNull(GraphQLInt) },
},
},
testAwaitedValue: {
type: GraphQLString,
async resolve() {
return 'it ' + (await 'works');
},
},
testError: {
type: GraphQLString,
resolve() {
throw new Error('Secret error message');
},
},
},
});
const schema = new GraphQLSchema({
query: queryType,
});
describe('runQuery', () => {
it('returns the right result when query is a string', () => {
const query = `{ testString }`;
const expected = { testString: 'it works' };
return runQuery({
schema,
queryString: query,
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it.skip('returns the right result when query is a document', () => {
const query = parse(`{ testString }`);
const expected = { testString: 'it works' };
return runQuery({
schema,
parsedQuery: query,
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('returns a syntax error if the query string contains one', () => {
const query = `query { test `;
const expected = /Syntax Error/;
return runQuery({
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
}).then(res => {
expect(res.data).toBeUndefined();
expect(res.errors!.length).toEqual(1);
expect(res.errors![0].message).toMatch(expected);
});
});
it('does not call console.error if in an error occurs and debug mode is set', () => {
const query = `query { testError }`;
const logStub = jest.spyOn(console, 'error');
return runQuery({
schema,
queryString: query,
debug: true,
request: new MockReq(),
}).then(() => {
logStub.mockRestore();
expect(logStub.mock.calls.length).toEqual(0);
});
});
it('does not call console.error if in an error occurs and not in debug mode', () => {
const query = `query { testError }`;
const logStub = jest.spyOn(console, 'error');
return runQuery({
schema,
queryString: query,
debug: false,
request: new MockReq(),
}).then(() => {
logStub.mockRestore();
expect(logStub.mock.calls.length).toEqual(0);
});
});
it('returns a validation error if the query string does not pass validation', () => {
const query = `query TestVar($base: String){ testArgumentValue(base: $base) }`;
const expected =
'Variable "$base" of type "String" used in position expecting type "Int!".';
return runQuery({
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
}).then(res => {
expect(res.data).toBeUndefined();
expect(res.errors!.length).toEqual(1);
expect(res.errors![0].message).toEqual(expected);
});
});
it('correctly passes in the rootValue', () => {
const query = `{ testRootValue }`;
const expected = { testRootValue: 'it also works' };
return runQuery({
schema,
queryString: query,
rootValue: 'it also',
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('correctly evaluates a rootValue function', () => {
const query = `{ testRootValue }`;
const expected = { testRootValue: 'it also works' };
return runQuery({
schema,
queryString: query,
rootValue: (doc: DocumentNode) => {
expect(doc.kind).toEqual('Document');
return 'it also';
},
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('correctly passes in the context', () => {
const query = `{ testContextValue }`;
const expected = { testContextValue: 'it still works' };
return runQuery({
schema,
queryString: query,
context: { s: 'it still' },
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('passes the options to formatResponse', () => {
const query = `{ testContextValue }`;
const expected = { testContextValue: 'it still works' };
return runQuery({
schema,
queryString: query,
context: { s: 'it still' },
formatResponse: (response: any, { context }: { context: any }) => {
response['extensions'] = context.s;
return response;
},
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
expect(res['extensions']).toEqual('it still');
});
});
it('correctly passes in variables (and arguments)', () => {
const query = `query TestVar($base: Int!){ testArgumentValue(base: $base) }`;
const expected = { testArgumentValue: 6 };
return runQuery({
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('throws an error if there are missing variables', () => {
const query = `query TestVar($base: Int!){ testArgumentValue(base: $base) }`;
const expected =
'Variable "$base" of required type "Int!" was not provided.';
return runQuery({
schema,
queryString: query,
request: new MockReq(),
}).then(res => {
expect(res.errors![0].message).toEqual(expected);
});
});
it('supports yielding resolver functions', () => {
return runQuery({
schema,
queryString: `{ testAwaitedValue }`,
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual({
testAwaitedValue: 'it works',
});
});
});
it('runs the correct operation when operationName is specified', () => {
const query = `
query Q1 {
testString
}
query Q2 {
testRootValue
}`;
const expected = {
testString: 'it works',
};
return runQuery({
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
it('uses custom field resolver', async () => {
const query = `
query Q1 {
testObject {
testString
}
}
`;
const result1 = await runQuery({
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
});
expect(result1.data).toEqual({
testObject: {
testString: 'a very test string',
},
});
const result2 = await runQuery({
schema,
queryString: query,
operationName: 'Q1',
fieldResolver: () => 'a very testful field resolver string',
request: new MockReq(),
});
expect(result2.data).toEqual({
testObject: {
testString: 'a very testful field resolver string',
},
});
});
describe('graphql extensions', () => {
class CustomExtension implements GraphQLExtension<any> {
format(): [string, any] {
return ['customExtension', { foo: 'bar' }];
}
}
it('creates the extension stack', async () => {
const queryString = `{ testString }`;
const extensions = [() => new CustomExtension()];
return runQuery({
schema: new GraphQLSchema({
query: new GraphQLObjectType({
name: 'QueryType',
fields: {
testString: {
type: GraphQLString,
resolve(_parent, _args, context) {
expect(context._extensionStack).toBeInstanceOf(
GraphQLExtensionStack,
);
expect(context._extensionStack.extensions[0]).toBeInstanceOf(
CustomExtension,
);
},
},
},
}),
}),
queryString,
extensions,
request: new MockReq(),
});
});
it('runs format response from extensions', async () => {
const queryString = `{ testString }`;
const expected = { testString: 'it works' };
const extensions = [() => new CustomExtension()];
return runQuery({
schema,
queryString,
extensions,
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
expect(res.extensions).toEqual({
customExtension: { foo: 'bar' },
});
});
});
it('runs willSendResponse with extensions context', async () => {
class CustomExtension implements GraphQLExtension<any> {
willSendResponse(o: any) {
expect(o).toHaveProperty('context.baz', 'always here');
return o;
}
}
const queryString = `{ testString }`;
const expected = { testString: 'it works' };
const extensions = [() => new CustomExtension()];
return runQuery({
schema,
queryString,
context: { baz: 'always here' },
extensions,
request: new MockReq(),
}).then(res => {
expect(res.data).toEqual(expected);
});
});
});
describe('parsing and validation cache', () => {
function createLifecyclePluginMocks() {
const validationDidStart = jest.fn();
const parsingDidStart = jest.fn();
const plugins: ApolloServerPlugin[] = [
{
requestDidStart() {
return {
validationDidStart,
parsingDidStart,
} as GraphQLRequestListener;
},
},
];
return {
plugins,
events: { validationDidStart, parsingDidStart },
};
}
function runRequest({
queryString = '{ testString }',
plugins = [],
documentStore,
}: {
queryString?: string;
plugins?: ApolloServerPlugin[];
documentStore?: QueryOptions['documentStore'];
}) {
return runQuery({
schema,
documentStore,
queryString,
plugins,
request: new MockReq(),
});
}
function forgeLargerTestQuery(
count: number,
prefix: string = 'prefix',
): string {
if (count <= 0) {
count = 1;
}
let query: string = '';
for (let q = 0; q < count; q++) {
query += ` ${prefix}_${count}: testString\n`;
}
return '{\n' + query + '}';
}
it('validates each time when the documentStore is not present', async () => {
expect.assertions(4);
const {
plugins,
events: { parsingDidStart, validationDidStart },
} = createLifecyclePluginMocks();
// The first request will do a parse and validate. (1/1)
await runRequest({ plugins });
expect(parsingDidStart.mock.calls.length).toBe(1);
expect(validationDidStart.mock.calls.length).toBe(1);
// The second request should ALSO do a parse and validate. (2/2)
await runRequest({ plugins });
expect(parsingDidStart.mock.calls.length).toBe(2);
expect(validationDidStart.mock.calls.length).toBe(2);
});
it('caches the DocumentNode in the documentStore when instrumented', async () => {
expect.assertions(4);
const documentStore = new InMemoryLRUCache<DocumentNode>();
const {
plugins,
events: { parsingDidStart, validationDidStart },
} = createLifecyclePluginMocks();
// An uncached request will have 1 parse and 1 validate call.
await runRequest({ plugins, documentStore });
expect(parsingDidStart.mock.calls.length).toBe(1);
expect(validationDidStart.mock.calls.length).toBe(1);
// The second request should still only have a 1 validate and 1 parse.
await runRequest({ plugins, documentStore });
expect(parsingDidStart.mock.calls.length).toBe(1);
expect(validationDidStart.mock.calls.length).toBe(1);
console.log(documentStore);
});
it("the documentStore calculates the DocumentNode's length by its JSON.stringify'd representation", async () => {
expect.assertions(14);
const {
plugins,
events: { parsingDidStart, validationDidStart },
} = createLifecyclePluginMocks();
const queryLarge = forgeLargerTestQuery(3, 'large');
const querySmall1 = forgeLargerTestQuery(1, 'small1');
const querySmall2 = forgeLargerTestQuery(1, 'small2');
// We're going to create a smaller-than-default cache which will be the
// size of the two smaller queries. All three of these queries will never
// fit into this cache, so we'll roll through them all.
const maxSize =
JSON.stringify(parse(querySmall1)).length +
JSON.stringify(parse(querySmall2)).length;
const documentStore = new InMemoryLRUCache<DocumentNode>({ maxSize });
await runRequest({ plugins, documentStore, queryString: querySmall1 });
expect(parsingDidStart.mock.calls.length).toBe(1);
expect(validationDidStart.mock.calls.length).toBe(1);
await runRequest({ plugins, documentStore, queryString: querySmall2 });
expect(parsingDidStart.mock.calls.length).toBe(2);
expect(validationDidStart.mock.calls.length).toBe(2);
// This query should be large enough to evict both of the previous
// from the LRU cache since it's larger than the TOTAL limit of the cache
// (which is capped at the length of small1 + small2) — though this will
// still fit (barely).
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(3);
expect(validationDidStart.mock.calls.length).toBe(3);
// Make sure the large query is still cached (No incr. to parse/validate.)
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(3);
expect(validationDidStart.mock.calls.length).toBe(3);
// This small (and the other) should both trigger parse/validate since
// the cache had to have evicted them both after accommodating the larger.
await runRequest({ plugins, documentStore, queryString: querySmall1 });
expect(parsingDidStart.mock.calls.length).toBe(4);
expect(validationDidStart.mock.calls.length).toBe(4);
await runRequest({ plugins, documentStore, queryString: querySmall2 });
expect(parsingDidStart.mock.calls.length).toBe(5);
expect(validationDidStart.mock.calls.length).toBe(5);
// Finally, make sure that the large query is gone (it should be, after
// the last two have take its spot again.)
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(6);
expect(validationDidStart.mock.calls.length).toBe(6);
});
});
describe('async_hooks', () => {
let asyncHooks: typeof import('async_hooks');
let asyncHook: import('async_hooks').AsyncHook;
const ids: number[] = [];
try {
asyncHooks = require('async_hooks');
} catch (err) {
return; // async_hooks not present, give up
}
beforeAll(() => {
asyncHook = asyncHooks.createHook({
init: (asyncId: number) => ids.push(asyncId),
});
asyncHook.enable();
});
afterAll(() => {
asyncHook.disable();
});
it('does not break async_hook call stack', async () => {
const query = `
query Q1 {
testObject {
testString
}
}
`;
await runQuery({
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
});
// Expect there to be several async ids provided
expect(ids.length).toBeGreaterThanOrEqual(2);
});
});
});