forked from graphql/graphql-js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
coerceInputValue-test.ts
715 lines (627 loc) · 21 KB
/
coerceInputValue-test.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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { identityFunc } from '../../jsutils/identityFunc.js';
import { invariant } from '../../jsutils/invariant.js';
import type { ObjMap } from '../../jsutils/ObjMap.js';
import { Kind } from '../../language/kinds.js';
import { parseValue } from '../../language/parser.js';
import { print } from '../../language/printer.js';
import type { GraphQLInputType } from '../../type/definition.js';
import {
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
} from '../../type/definition.js';
import {
GraphQLBoolean,
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLString,
} from '../../type/scalars.js';
import {
coerceDefaultValue,
coerceInputLiteral,
coerceInputValue,
} from '../coerceInputValue.js';
interface CoerceResult {
value: unknown;
errors: ReadonlyArray<CoerceError>;
}
interface CoerceError {
path: ReadonlyArray<string | number>;
value: unknown;
error: string;
}
function coerceValue(
inputValue: unknown,
type: GraphQLInputType,
): CoerceResult {
const errors: Array<CoerceError> = [];
const value = coerceInputValue(
inputValue,
type,
(path, invalidValue, error) => {
errors.push({ path, value: invalidValue, error: error.message });
},
);
return { errors, value };
}
function expectValue(result: CoerceResult) {
expect(result.errors).to.deep.equal([]);
return expect(result.value);
}
function expectErrors(result: CoerceResult) {
return expect(result.errors);
}
describe('coerceInputValue', () => {
describe('for GraphQLNonNull', () => {
const TestNonNull = new GraphQLNonNull(GraphQLInt);
it('returns no error for non-null value', () => {
const result = coerceValue(1, TestNonNull);
expectValue(result).to.equal(1);
});
it('returns an error for undefined value', () => {
const result = coerceValue(undefined, TestNonNull);
expectErrors(result).to.deep.equal([
{
error: 'Expected non-nullable type "Int!" not to be null.',
path: [],
value: undefined,
},
]);
});
it('returns an error for null value', () => {
const result = coerceValue(null, TestNonNull);
expectErrors(result).to.deep.equal([
{
error: 'Expected non-nullable type "Int!" not to be null.',
path: [],
value: null,
},
]);
});
});
describe('for GraphQLScalar', () => {
const TestScalar = new GraphQLScalarType({
name: 'TestScalar',
parseValue(input: any) {
if (input.error != null) {
throw new Error(input.error);
}
return input.value;
},
});
it('returns no error for valid input', () => {
const result = coerceValue({ value: 1 }, TestScalar);
expectValue(result).to.equal(1);
});
it('returns no error for null result', () => {
const result = coerceValue({ value: null }, TestScalar);
expectValue(result).to.equal(null);
});
it('returns no error for NaN result', () => {
const result = coerceValue({ value: NaN }, TestScalar);
expectValue(result).to.satisfy(Number.isNaN);
});
it('returns an error for undefined result', () => {
const result = coerceValue({ value: undefined }, TestScalar);
expectErrors(result).to.deep.equal([
{
error: 'Expected type "TestScalar".',
path: [],
value: { value: undefined },
},
]);
});
it('returns a thrown error', () => {
const inputValue = { error: 'Some error message' };
const result = coerceValue(inputValue, TestScalar);
expectErrors(result).to.deep.equal([
{
error: 'Expected type "TestScalar". Some error message',
path: [],
value: { error: 'Some error message' },
},
]);
});
});
describe('for GraphQLEnum', () => {
const TestEnum = new GraphQLEnumType({
name: 'TestEnum',
values: {
FOO: { value: 'InternalFoo' },
BAR: { value: 123456789 },
},
});
it('returns no error for a known enum name', () => {
const fooResult = coerceValue('FOO', TestEnum);
expectValue(fooResult).to.equal('InternalFoo');
const barResult = coerceValue('BAR', TestEnum);
expectValue(barResult).to.equal(123456789);
});
it('returns an error for misspelled enum value', () => {
const result = coerceValue('foo', TestEnum);
expectErrors(result).to.deep.equal([
{
error:
'Value "foo" does not exist in "TestEnum" enum. Did you mean the enum value "FOO"?',
path: [],
value: 'foo',
},
]);
});
it('returns an error for incorrect value type', () => {
const result1 = coerceValue(123, TestEnum);
expectErrors(result1).to.deep.equal([
{
error: 'Enum "TestEnum" cannot represent non-string value: 123.',
path: [],
value: 123,
},
]);
const result2 = coerceValue({ field: 'value' }, TestEnum);
expectErrors(result2).to.deep.equal([
{
error:
'Enum "TestEnum" cannot represent non-string value: { field: "value" }.',
path: [],
value: { field: 'value' },
},
]);
});
});
describe('for GraphQLInputObject', () => {
const TestInputObject = new GraphQLInputObjectType({
name: 'TestInputObject',
fields: {
foo: { type: new GraphQLNonNull(GraphQLInt) },
bar: { type: GraphQLInt },
},
});
it('returns no error for a valid input', () => {
const result = coerceValue({ foo: 123 }, TestInputObject);
expectValue(result).to.deep.equal({ foo: 123 });
});
it('returns an error for a non-object type', () => {
const result = coerceValue(123, TestInputObject);
expectErrors(result).to.deep.equal([
{
error: 'Expected type "TestInputObject" to be an object.',
path: [],
value: 123,
},
]);
});
it('returns an error for an invalid field', () => {
const result = coerceValue({ foo: NaN }, TestInputObject);
expectErrors(result).to.deep.equal([
{
error: 'Int cannot represent non-integer value: NaN',
path: ['foo'],
value: NaN,
},
]);
});
it('returns multiple errors for multiple invalid fields', () => {
const result = coerceValue({ foo: 'abc', bar: 'def' }, TestInputObject);
expectErrors(result).to.deep.equal([
{
error: 'Int cannot represent non-integer value: "abc"',
path: ['foo'],
value: 'abc',
},
{
error: 'Int cannot represent non-integer value: "def"',
path: ['bar'],
value: 'def',
},
]);
});
it('returns error for a missing required field', () => {
const result = coerceValue({ bar: 123 }, TestInputObject);
expectErrors(result).to.deep.equal([
{
error: 'Field "foo" of required type "Int!" was not provided.',
path: [],
value: { bar: 123 },
},
]);
});
it('returns error for an unknown field', () => {
const result = coerceValue(
{ foo: 123, unknownField: 123 },
TestInputObject,
);
expectErrors(result).to.deep.equal([
{
error:
'Field "unknownField" is not defined by type "TestInputObject".',
path: [],
value: { foo: 123, unknownField: 123 },
},
]);
});
it('returns error for a misspelled field', () => {
const result = coerceValue({ foo: 123, bart: 123 }, TestInputObject);
expectErrors(result).to.deep.equal([
{
error:
'Field "bart" is not defined by type "TestInputObject". Did you mean "bar"?',
path: [],
value: { foo: 123, bart: 123 },
},
]);
});
});
describe('for GraphQLInputObject with default value', () => {
const makeTestInputObject = (defaultValue: any) =>
new GraphQLInputObjectType({
name: 'TestInputObject',
fields: {
foo: {
type: new GraphQLScalarType({ name: 'TestScalar' }),
defaultValue,
},
},
});
it('returns no errors for valid input value', () => {
const result = coerceValue({ foo: 5 }, makeTestInputObject(7));
expectValue(result).to.deep.equal({ foo: 5 });
});
it('returns object with default value', () => {
const result = coerceValue({}, makeTestInputObject(7));
expectValue(result).to.deep.equal({ foo: 7 });
});
it('returns null as value', () => {
const result = coerceValue({}, makeTestInputObject(null));
expectValue(result).to.deep.equal({ foo: null });
});
it('returns NaN as value', () => {
const result = coerceValue({}, makeTestInputObject(NaN));
expectValue(result).to.have.property('foo').that.satisfy(Number.isNaN);
});
});
describe('for GraphQLList', () => {
const TestList = new GraphQLList(GraphQLInt);
it('returns no error for a valid input', () => {
const result = coerceValue([1, 2, 3], TestList);
expectValue(result).to.deep.equal([1, 2, 3]);
});
it('returns no error for a valid iterable input', () => {
function* listGenerator() {
yield 1;
yield 2;
yield 3;
}
const result = coerceValue(listGenerator(), TestList);
expectValue(result).to.deep.equal([1, 2, 3]);
});
it('returns an error for an invalid input', () => {
const result = coerceValue([1, 'b', true, 4], TestList);
expectErrors(result).to.deep.equal([
{
error: 'Int cannot represent non-integer value: "b"',
path: [1],
value: 'b',
},
{
error: 'Int cannot represent non-integer value: true',
path: [2],
value: true,
},
]);
});
it('returns a list for a non-list value', () => {
const result = coerceValue(42, TestList);
expectValue(result).to.deep.equal([42]);
});
it('returns a list for a non-list object value', () => {
const TestListOfObjects = new GraphQLList(
new GraphQLInputObjectType({
name: 'TestObject',
fields: {
length: { type: GraphQLInt },
},
}),
);
const result = coerceValue({ length: 100500 }, TestListOfObjects);
expectValue(result).to.deep.equal([{ length: 100500 }]);
});
it('returns an error for a non-list invalid value', () => {
const result = coerceValue('INVALID', TestList);
expectErrors(result).to.deep.equal([
{
error: 'Int cannot represent non-integer value: "INVALID"',
path: [],
value: 'INVALID',
},
]);
});
it('returns null for a null value', () => {
const result = coerceValue(null, TestList);
expectValue(result).to.deep.equal(null);
});
});
describe('for nested GraphQLList', () => {
const TestNestedList = new GraphQLList(new GraphQLList(GraphQLInt));
it('returns no error for a valid input', () => {
const result = coerceValue([[1], [2, 3]], TestNestedList);
expectValue(result).to.deep.equal([[1], [2, 3]]);
});
it('returns a list for a non-list value', () => {
const result = coerceValue(42, TestNestedList);
expectValue(result).to.deep.equal([[42]]);
});
it('returns null for a null value', () => {
const result = coerceValue(null, TestNestedList);
expectValue(result).to.deep.equal(null);
});
it('returns nested lists for nested non-list values', () => {
const result = coerceValue([1, 2, 3], TestNestedList);
expectValue(result).to.deep.equal([[1], [2], [3]]);
});
it('returns nested null for nested null values', () => {
const result = coerceValue([42, [null], null], TestNestedList);
expectValue(result).to.deep.equal([[42], [null], null]);
});
});
describe('with default onError', () => {
it('throw error without path', () => {
expect(() =>
coerceInputValue(null, new GraphQLNonNull(GraphQLInt)),
).to.throw(
'Invalid value null: Expected non-nullable type "Int!" not to be null.',
);
});
it('throw error with path', () => {
expect(() =>
coerceInputValue(
[null],
new GraphQLList(new GraphQLNonNull(GraphQLInt)),
),
).to.throw(
'Invalid value null at "value[0]": Expected non-nullable type "Int!" not to be null.',
);
});
});
});
describe('coerceInputLiteral', () => {
function test(
valueText: string,
type: GraphQLInputType,
expected: unknown,
variables?: ObjMap<unknown>,
) {
const ast = parseValue(valueText);
const value = coerceInputLiteral(ast, type, variables);
expect(value).to.deep.equal(expected);
}
function testWithVariables(
variables: ObjMap<unknown>,
valueText: string,
type: GraphQLInputType,
expected: unknown,
) {
test(valueText, type, expected, variables);
}
it('converts according to input coercion rules', () => {
test('true', GraphQLBoolean, true);
test('false', GraphQLBoolean, false);
test('123', GraphQLInt, 123);
test('123', GraphQLFloat, 123);
test('123.456', GraphQLFloat, 123.456);
test('"abc123"', GraphQLString, 'abc123');
test('123456', GraphQLID, '123456');
test('"123456"', GraphQLID, '123456');
});
it('does not convert when input coercion rules reject a value', () => {
test('123', GraphQLBoolean, undefined);
test('123.456', GraphQLInt, undefined);
test('true', GraphQLInt, undefined);
test('"123"', GraphQLInt, undefined);
test('"123"', GraphQLFloat, undefined);
test('123', GraphQLString, undefined);
test('true', GraphQLString, undefined);
test('123.456', GraphQLString, undefined);
test('123.456', GraphQLID, undefined);
});
it('convert using parseLiteral from a custom scalar type', () => {
const passthroughScalar = new GraphQLScalarType({
name: 'PassthroughScalar',
parseLiteral(node) {
invariant(node.kind === 'StringValue');
return node.value;
},
parseValue: identityFunc,
});
test('"value"', passthroughScalar, 'value');
const printScalar = new GraphQLScalarType({
name: 'PrintScalar',
parseLiteral(node) {
return `~~~${print(node)}~~~`;
},
parseValue: identityFunc,
});
test('"value"', printScalar, '~~~"value"~~~');
const throwScalar = new GraphQLScalarType({
name: 'ThrowScalar',
parseLiteral() {
throw new Error('Test');
},
parseValue: identityFunc,
});
test('value', throwScalar, undefined);
const returnUndefinedScalar = new GraphQLScalarType({
name: 'ReturnUndefinedScalar',
parseLiteral() {
return undefined;
},
parseValue: identityFunc,
});
test('value', returnUndefinedScalar, undefined);
});
it('converts enum values according to input coercion rules', () => {
const testEnum = new GraphQLEnumType({
name: 'TestColor',
values: {
RED: { value: 1 },
GREEN: { value: 2 },
BLUE: { value: 3 },
NULL: { value: null },
NAN: { value: NaN },
NO_CUSTOM_VALUE: { value: undefined },
},
});
test('RED', testEnum, 1);
test('BLUE', testEnum, 3);
test('3', testEnum, undefined);
test('"BLUE"', testEnum, undefined);
test('null', testEnum, null);
test('NULL', testEnum, null);
test('NULL', new GraphQLNonNull(testEnum), null);
test('NAN', testEnum, NaN);
test('NO_CUSTOM_VALUE', testEnum, 'NO_CUSTOM_VALUE');
});
// Boolean!
const nonNullBool = new GraphQLNonNull(GraphQLBoolean);
// [Boolean]
const listOfBool = new GraphQLList(GraphQLBoolean);
// [Boolean!]
const listOfNonNullBool = new GraphQLList(nonNullBool);
// [Boolean]!
const nonNullListOfBool = new GraphQLNonNull(listOfBool);
// [Boolean!]!
const nonNullListOfNonNullBool = new GraphQLNonNull(listOfNonNullBool);
it('coerces to null unless non-null', () => {
test('null', GraphQLBoolean, null);
test('null', nonNullBool, undefined);
});
it('coerces lists of values', () => {
test('true', listOfBool, [true]);
test('123', listOfBool, undefined);
test('null', listOfBool, null);
test('[true, false]', listOfBool, [true, false]);
test('[true, 123]', listOfBool, undefined);
test('[true, null]', listOfBool, [true, null]);
test('{ true: true }', listOfBool, undefined);
});
it('coerces non-null lists of values', () => {
test('true', nonNullListOfBool, [true]);
test('123', nonNullListOfBool, undefined);
test('null', nonNullListOfBool, undefined);
test('[true, false]', nonNullListOfBool, [true, false]);
test('[true, 123]', nonNullListOfBool, undefined);
test('[true, null]', nonNullListOfBool, [true, null]);
});
it('coerces lists of non-null values', () => {
test('true', listOfNonNullBool, [true]);
test('123', listOfNonNullBool, undefined);
test('null', listOfNonNullBool, null);
test('[true, false]', listOfNonNullBool, [true, false]);
test('[true, 123]', listOfNonNullBool, undefined);
test('[true, null]', listOfNonNullBool, undefined);
});
it('coerces non-null lists of non-null values', () => {
test('true', nonNullListOfNonNullBool, [true]);
test('123', nonNullListOfNonNullBool, undefined);
test('null', nonNullListOfNonNullBool, undefined);
test('[true, false]', nonNullListOfNonNullBool, [true, false]);
test('[true, 123]', nonNullListOfNonNullBool, undefined);
test('[true, null]', nonNullListOfNonNullBool, undefined);
});
it('uses default values for unprovided fields', () => {
const type = new GraphQLInputObjectType({
name: 'TestInput',
fields: {
int: { type: GraphQLInt, defaultValue: 42 },
float: {
type: GraphQLFloat,
defaultValueLiteral: { kind: Kind.FLOAT, value: '3.14' },
},
},
});
test('{}', type, { int: 42, float: 3.14 });
});
const testInputObj = new GraphQLInputObjectType({
name: 'TestInput',
fields: {
int: { type: GraphQLInt, defaultValue: 42 },
bool: { type: GraphQLBoolean },
requiredBool: { type: nonNullBool },
},
});
it('coerces input objects according to input coercion rules', () => {
test('null', testInputObj, null);
test('123', testInputObj, undefined);
test('[]', testInputObj, undefined);
test('{ requiredBool: true }', testInputObj, {
int: 42,
requiredBool: true,
});
test('{ int: null, requiredBool: true }', testInputObj, {
int: null,
requiredBool: true,
});
test('{ int: 123, requiredBool: false }', testInputObj, {
int: 123,
requiredBool: false,
});
test('{ bool: true, requiredBool: false }', testInputObj, {
int: 42,
bool: true,
requiredBool: false,
});
test('{ int: true, requiredBool: true }', testInputObj, undefined);
test('{ requiredBool: null }', testInputObj, undefined);
test('{ bool: true }', testInputObj, undefined);
test('{ requiredBool: true, unknown: 123 }', testInputObj, undefined);
});
it('accepts variable values assuming already coerced', () => {
test('$var', GraphQLBoolean, undefined);
testWithVariables({ var: true }, '$var', GraphQLBoolean, true);
testWithVariables({ var: null }, '$var', GraphQLBoolean, null);
testWithVariables({ var: null }, '$var', nonNullBool, undefined);
});
it('asserts variables are provided as items in lists', () => {
test('[ $foo ]', listOfBool, [null]);
test('[ $foo ]', listOfNonNullBool, undefined);
testWithVariables({ foo: true }, '[ $foo ]', listOfNonNullBool, [true]);
// Note: variables are expected to have already been coerced, so we
// do not expect the singleton wrapping behavior for variables.
testWithVariables({ foo: true }, '$foo', listOfNonNullBool, true);
testWithVariables({ foo: [true] }, '$foo', listOfNonNullBool, [true]);
});
it('omits input object fields for unprovided variables', () => {
test('{ int: $foo, bool: $foo, requiredBool: true }', testInputObj, {
int: 42,
requiredBool: true,
});
test('{ requiredBool: $foo }', testInputObj, undefined);
testWithVariables({ foo: true }, '{ requiredBool: $foo }', testInputObj, {
int: 42,
requiredBool: true,
});
});
});
describe('coerceDefaultValue', () => {
it('memoizes coercion', () => {
const parseValueCalls: any = [];
const spyScalar = new GraphQLScalarType({
name: 'SpyScalar',
parseValue(value) {
parseValueCalls.push(value);
return value;
},
});
const defaultValueUsage = {
literal: { kind: Kind.STRING, value: 'hello' },
} as const;
expect(coerceDefaultValue(defaultValueUsage, spyScalar)).to.equal('hello');
// Call a second time
expect(coerceDefaultValue(defaultValueUsage, spyScalar)).to.equal('hello');
expect(parseValueCalls).to.deep.equal(['hello']);
});
});