-
-
Notifications
You must be signed in to change notification settings - Fork 575
Expand file tree
/
Copy pathEnumTypeTest.php
More file actions
726 lines (647 loc) · 24.2 KB
/
Copy pathEnumTypeTest.php
File metadata and controls
726 lines (647 loc) · 24.2 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
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
716
717
718
719
720
721
722
723
724
725
726
<?php declare(strict_types=1);
namespace GraphQL\Tests\Type;
use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
use GraphQL\Error\DebugFlag;
use GraphQL\GraphQL;
use GraphQL\Language\Parser;
use GraphQL\Language\SourceLocation;
use GraphQL\Tests\Type\PhpEnumType\BackedPhpEnum;
use GraphQL\Tests\Type\PhpEnumType\PhpEnum;
use GraphQL\Tests\Type\TestClasses\OtherEnumType;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\EnumValueDefinition;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use GraphQL\Utils\BuildSchema;
use PHPUnit\Framework\TestCase;
final class EnumTypeTest extends TestCase
{
use ArraySubsetAsserts;
private Schema $schema;
private EnumType $ComplexEnum;
/** @var array{someRandomFunction: callable(): void} */
private array $Complex1;
/** @var \ArrayObject<string, int> */
private \ArrayObject $Complex2;
protected function setUp(): void
{
$ColorType = new EnumType([
'name' => 'Color',
'values' => [
'RED' => ['value' => 0],
'GREEN' => ['value' => 1],
'BLUE' => ['value' => 2],
],
]);
$simpleEnum = new EnumType([
'name' => 'SimpleEnum',
'values' => [
'ONE',
'TWO',
'THREE',
],
]);
$otherEnum = new OtherEnumType();
$Complex1 = [
'someRandomFunction' => static function (): void {},
];
$Complex2 = new \ArrayObject(['someRandomValue' => 123]);
$ComplexEnum = new EnumType([
'name' => 'Complex',
'values' => [
'ONE' => ['value' => $Complex1],
'TWO' => ['value' => $Complex2],
],
]);
$Array1 = ['one', 'ONE'];
$ArrayValuesEnum = new EnumType([
'name' => 'ArrayValuesEnum',
'values' => [
'ONE' => ['value' => $Array1],
'TWO' => ['value' => ['two', 'TWO']],
],
]);
$QueryType = new ObjectType([
'name' => 'Query',
'fields' => [
'colorEnum' => [
'type' => $ColorType,
'args' => [
'fromEnum' => ['type' => $ColorType],
'fromInt' => ['type' => Type::int()],
'fromString' => ['type' => Type::string()],
],
'resolve' => static function ($rootValue, array $args) {
if (isset($args['fromInt'])) {
return $args['fromInt'];
}
if (isset($args['fromString'])) {
return $args['fromString'];
}
if (isset($args['fromEnum'])) {
return $args['fromEnum'];
}
return null;
},
],
'simpleEnum' => [
'type' => $simpleEnum,
'args' => [
'fromName' => ['type' => Type::string()],
'fromValue' => ['type' => Type::string()],
],
'resolve' => static function ($rootValue, array $args) {
if (isset($args['fromName'])) {
return $args['fromName'];
}
if (isset($args['fromValue'])) {
return $args['fromValue'];
}
return null;
},
],
'otherEnumReturn' => [
'type' => $otherEnum,
'resolve' => static fn (): string => 'does not matter, enum serializes anything to a constant result',
],
'otherEnumArg' => [
'type' => Type::string(),
'args' => [
'from' => ['type' => $otherEnum],
],
'resolve' => static fn ($rootValue, array $args): string => $args['from'],
],
'colorInt' => [
'type' => Type::int(),
'args' => [
'fromEnum' => ['type' => $ColorType],
'fromInt' => ['type' => Type::int()],
],
'resolve' => static function ($rootValue, $args) {
if (isset($args['fromInt'])) {
return $args['fromInt'];
}
if (isset($args['fromEnum'])) {
return $args['fromEnum'];
}
},
],
'complexEnum' => [
'type' => $ComplexEnum,
'args' => [
'fromEnum' => [
'type' => $ComplexEnum,
// Note: defaultValue is provided an *internal* representation for
// Enums, rather than the string name.
'defaultValue' => $Complex1,
],
'provideGoodValue' => [
'type' => Type::boolean(),
],
'provideBadValue' => [
'type' => Type::boolean(),
],
],
'resolve' => static function ($rootValue, $args) use ($Complex2) {
if ($args['provideGoodValue'] ?? false) {
// Note: this is one of the references of the internal values which
// ComplexEnum allows.
return $Complex2;
}
if ($args['provideBadValue'] ?? false) {
// Note: similar shape, but not the same *reference*
// as Complex2 above. Enum internal values require === equality.
return new \ArrayObject(['someRandomValue' => 123]);
}
return $args['fromEnum'];
},
],
'arrayValuesEnum' => [
'type' => $ArrayValuesEnum,
'args' => [
'fromEnum' => [
'type' => $ArrayValuesEnum,
// Note: defaultValue is provided an *internal* representation for
// Enums, rather than the string name.
'defaultValue' => $Array1,
],
'provideOneByReference' => [
'type' => Type::boolean(),
],
'provideTwo' => [
'type' => Type::boolean(),
],
],
'resolve' => static function ($rootValue, $args) use (&$Array1) {
if ($args['provideOneByReference'] ?? false) {
return $Array1;
}
if ($args['provideTwo'] ?? false) {
return [
'two',
'TWO',
];
}
return $args['fromEnum'];
},
],
],
]);
$MutationType = new ObjectType([
'name' => 'Mutation',
'fields' => [
'favoriteEnum' => [
'type' => $ColorType,
'args' => [
'color' => [
'type' => $ColorType,
],
],
'resolve' => static fn ($rootValue, array $args) => $args['color'] ?? null,
],
],
]);
$SubscriptionType = new ObjectType([
'name' => 'Subscription',
'fields' => [
'subscribeToEnum' => [
'type' => $ColorType,
'args' => ['color' => ['type' => $ColorType]],
'resolve' => static fn ($rootValue, $args) => $args['color'] ?? null,
],
],
]);
$this->Complex1 = $Complex1;
$this->Complex2 = $Complex2;
$this->ComplexEnum = $ComplexEnum;
$this->schema = new Schema([
'query' => $QueryType,
'mutation' => $MutationType,
'subscription' => $SubscriptionType,
]);
}
// Describe: Type System: Enum Values
/** @see it('accepts enum literals as input') */
public function testAcceptsEnumLiteralsAsInput(): void
{
self::assertSame(
['data' => ['colorInt' => 1]],
GraphQL::executeQuery($this->schema, '{ colorInt(fromEnum: GREEN) }')->toArray()
);
}
/** @see it('enum may be output type') */
public function testEnumMayBeOutputType(): void
{
self::assertSame(
['data' => ['colorEnum' => 'GREEN']],
GraphQL::executeQuery($this->schema, '{ colorEnum(fromInt: 1) }')->toArray()
);
}
/** @see it('enum may be both input and output type') */
public function testEnumMayBeBothInputAndOutputType(): void
{
self::assertSame(
['data' => ['colorEnum' => 'GREEN']],
GraphQL::executeQuery($this->schema, '{ colorEnum(fromEnum: GREEN) }')->toArray()
);
}
/** @see it('does not accept string literals') */
public function testDoesNotAcceptStringLiterals(): void
{
$this->expectFailure(
'{ colorEnum(fromEnum: "GREEN") }',
null,
[
'message' => 'Enum "Color" cannot represent non-enum value: "GREEN". Did you mean the enum value "GREEN"?',
'locations' => [new SourceLocation(1, 23)],
]
);
}
/**
* @param array<string, mixed>|null $vars
* @param array{message: string, locations: array<int, SourceLocation>}|string $err
*
* @throws \Exception
*/
private function expectFailure(string $query, ?array $vars, $err): void
{
$result = GraphQL::executeQuery($this->schema, $query, null, null, $vars);
self::assertCount(1, $result->errors);
if (is_array($err)) {
self::assertSame(
$err['message'],
$result->errors[0]->getMessage()
);
self::assertEquals(
$err['locations'],
$result->errors[0]->getLocations()
);
} else {
self::assertSame(
$err,
$result->errors[0]->getMessage()
);
}
}
/** @see it('does not accept values not in the enum') */
public function testDoesNotAcceptValuesNotInTheEnum(): void
{
$this->expectFailure(
'{ colorEnum(fromEnum: GREENISH) }',
null,
[
'message' => 'Value "GREENISH" does not exist in "Color" enum. Did you mean the enum value "GREEN"?',
'locations' => [new SourceLocation(1, 23)],
]
);
}
/** @see it('does not accept values with incorrect casing') */
public function testDoesNotAcceptValuesWithIncorrectCasing(): void
{
$this->expectFailure(
'{ colorEnum(fromEnum: green) }',
null,
[
'message' => 'Value "green" does not exist in "Color" enum. Did you mean the enum value "GREEN" or "RED"?',
'locations' => [new SourceLocation(1, 23)],
]
);
}
/** @see it('does not accept incorrect internal value') */
public function testDoesNotAcceptIncorrectInternalValue(): void
{
$this->expectFailure(
'{ colorEnum(fromString: "GREEN") }',
null,
[
'message' => 'Expected a value of type Color but received: "GREEN". Cannot serialize value as enum: "GREEN"',
'locations' => [new SourceLocation(1, 3)],
'path' => ['colorEnum'],
]
);
}
/** @see it('does not accept internal value in place of enum literal') */
public function testDoesNotAcceptInternalValueInPlaceOfEnumLiteral(): void
{
$this->expectFailure(
'{ colorEnum(fromEnum: 1) }',
null,
'Enum "Color" cannot represent non-enum value: 1.'
);
}
/** @see it('does not accept enum literal in place of int') */
public function testDoesNotAcceptEnumLiteralInPlaceOfInt(): void
{
$this->expectFailure(
'{ colorEnum(fromInt: GREEN) }',
null,
'Int cannot represent non-integer value: GREEN'
);
}
/** @see it('accepts JSON string as enum variable') */
public function testAcceptsJSONStringAsEnumVariable(): void
{
self::assertSame(
['data' => ['colorEnum' => 'BLUE']],
GraphQL::executeQuery(
$this->schema,
'query test($color: Color!) { colorEnum(fromEnum: $color) }',
null,
null,
['color' => 'BLUE']
)->toArray()
);
}
/** @see it('accepts enum literals as input arguments to mutations') */
public function testAcceptsEnumLiteralsAsInputArgumentsToMutations(): void
{
self::assertSame(
['data' => ['favoriteEnum' => 'GREEN']],
GraphQL::executeQuery(
$this->schema,
'mutation x($color: Color!) { favoriteEnum(color: $color) }',
null,
null,
['color' => 'GREEN']
)->toArray()
);
}
/**
* @see it('accepts enum literals as input arguments to subscriptions')
*
* @todo
*/
public function testAcceptsEnumLiteralsAsInputArgumentsToSubscriptions(): void
{
self::assertSame(
['data' => ['subscribeToEnum' => 'GREEN']],
GraphQL::executeQuery(
$this->schema,
'subscription x($color: Color!) { subscribeToEnum(color: $color) }',
null,
null,
['color' => 'GREEN']
)->toArray()
);
}
/** @see it('does not accept internal value as enum variable') */
public function testDoesNotAcceptInternalValueAsEnumVariable(): void
{
$this->expectFailure(
'query test($color: Color!) { colorEnum(fromEnum: $color) }',
['color' => 2],
'Variable "$color" got invalid value 2; Enum "Color" cannot represent non-string value: 2.'
);
}
/** @see it('does not accept string variables as enum input') */
public function testDoesNotAcceptStringVariablesAsEnumInput(): void
{
$this->expectFailure(
'query test($color: String!) { colorEnum(fromEnum: $color) }',
['color' => 'BLUE'],
'Variable "$color" of type "String!" used in position expecting type "Color".'
);
}
/** @see it('does not accept internal value variable as enum input') */
public function testDoesNotAcceptInternalValueVariableSsEnumInput(): void
{
$this->expectFailure(
'query test($color: Int!) { colorEnum(fromEnum: $color) }',
['color' => 2],
'Variable "$color" of type "Int!" used in position expecting type "Color".'
);
}
/** @see it('enum value may have an internal value of 0') */
public function testEnumValueMayHaveAnInternalValueOf0(): void
{
self::assertSame(
['data' => ['colorEnum' => 'RED', 'colorInt' => 0]],
GraphQL::executeQuery(
$this->schema,
'{
colorEnum(fromEnum: RED)
colorInt(fromEnum: RED)
}'
)->toArray()
);
}
/** @see it('enum inputs may be nullable') */
public function testEnumInputsMayBeNullable(): void
{
self::assertEquals(
['data' => ['colorEnum' => null, 'colorInt' => null]],
GraphQL::executeQuery(
$this->schema,
'{
colorEnum
colorInt
}'
)->toArray()
);
}
/** @see it('presents a getValues() API for complex enums') */
public function testPresentsGetValuesAPIForComplexEnums(): void
{
$ComplexEnum = $this->ComplexEnum;
$values = $ComplexEnum->getValues();
self::assertCount(2, $values);
self::assertSame('ONE', $values[0]->name);
self::assertEquals($this->Complex1, $values[0]->value);
self::assertSame('TWO', $values[1]->name);
self::assertEquals($this->Complex2, $values[1]->value);
}
/** @see it('presents a getValue() API for complex enums') */
public function testPresentsGetValueAPIForComplexEnums(): void
{
$oneValue = $this->ComplexEnum->getValue('ONE');
self::assertInstanceOf(EnumValueDefinition::class, $oneValue);
self::assertSame('ONE', $oneValue->name);
self::assertEquals($this->Complex1, $oneValue->value);
}
/** @see it('may be internally represented with complex values') */
public function testMayBeInternallyRepresentedWithComplexValues(): void
{
$result = GraphQL::executeQuery(
$this->schema,
'{
first: complexEnum
second: complexEnum(fromEnum: TWO)
good: complexEnum(provideGoodValue: true)
bad: complexEnum(provideBadValue: true)
}'
)->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE);
$expected = [
'data' => [
'first' => 'ONE',
'second' => 'TWO',
'good' => 'TWO',
'bad' => null,
],
'errors' => [
[
'locations' => [['line' => 5, 'column' => 9]],
'extensions' => ['debugMessage' => 'Expected a value of type Complex but received: instance of ArrayObject. Cannot serialize value as enum: instance of ArrayObject'],
],
],
];
self::assertArraySubset($expected, $result);
}
public function testMayBeInternallyRepresentedWithArrayValues(): void
{
$result = GraphQL::executeQuery(
$this->schema,
'{
defaultValue: arrayValuesEnum
fromName: arrayValuesEnum(fromEnum: TWO)
oneRef: arrayValuesEnum(provideOneByReference: true)
two: arrayValuesEnum(provideTwo: true)
}'
)->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE);
$expected = [
'data' => [
'defaultValue' => 'ONE',
'fromName' => 'TWO',
'oneRef' => 'ONE',
'two' => 'TWO',
],
];
self::assertSame($expected, $result);
}
/** @see it('can be introspected without error') */
public function testCanBeIntrospectedWithoutError(): void
{
$result = GraphQL::executeQuery($this->schema, Introspection::getIntrospectionQuery())->toArray();
self::assertArrayNotHasKey('errors', $result);
}
public function testAllowsSimpleArrayAsValues(): void
{
$q = '{
first: simpleEnum(fromName: "ONE")
second: simpleEnum(fromValue: "TWO")
third: simpleEnum(fromValue: "WRONG")
}';
self::assertArraySubset(
[
'data' => ['first' => 'ONE', 'second' => 'TWO', 'third' => null],
'errors' => [
[
'locations' => [['line' => 4, 'column' => 13]],
'extensions' => [
'debugMessage' => 'Expected a value of type SimpleEnum but received: "WRONG". Cannot serialize value as enum: "WRONG"',
'trace' => [
['call' => 'GraphQL\Type\Definition\EnumType::serialize(\'WRONG\')'],
],
],
],
],
],
GraphQL::executeQuery($this->schema, $q)->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE)
);
}
public function testCallsOverwrittenEnumTypeMethods(): void
{
$query = '
query ($from: OtherEnum!) {
serialize: otherEnumReturn
parseValue: otherEnumArg(from: $from)
parseLiteral: otherEnumArg(from: ONE)
}
';
$variables = ['from' => 'ONE'];
self::assertArraySubset(
[
'data' => [
'serialize' => OtherEnumType::SERIALIZE_RESULT,
'parseValue' => OtherEnumType::PARSE_VALUE_RESULT,
'parseLiteral' => OtherEnumType::PARSE_LITERAL_RESULT,
],
],
GraphQL::executeQuery($this->schema, $query, null, null, $variables)->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE)
);
}
public function testLazilyDefineValuesAsCallable(): void
{
$called = 0;
$ColorType = new EnumType([
'name' => 'Color',
'values' => static function () use (&$called): iterable {
++$called;
yield 'RED' => ['value' => 0];
},
]);
$QueryType = new ObjectType([
'name' => 'Query',
'fields' => [
'colorEnum' => [
'type' => $ColorType,
'args' => [
'fromEnum' => [
'type' => $ColorType,
],
],
'resolve' => static fn ($rootValue, array $args) => $args['fromEnum'],
],
],
]);
$schema = new Schema(['query' => $QueryType]);
self::assertSame(0, $called, 'Should not eagerly call enum values during schema construction');
$query = '{ colorEnum(fromEnum: RED) }';
self::assertSame(
['data' => ['colorEnum' => 'RED']],
GraphQL::executeQuery($schema, $query)->toArray()
);
GraphQL::executeQuery($schema, $query);
// @phpstan-ignore-next-line $called is mutated
self::assertSame(1, $called, 'Should call enum values callable exactly once');
}
public function testSerializesNativeBackedEnums(): void
{
if (version_compare(phpversion(), '8.1', '<')) {
self::markTestSkipped('Native PHP enums are only available with PHP 8.1');
}
$documentNode = Parser::parse(<<<'SDL'
type Query {
phpEnum(fromEnum: PhpEnum!): PhpEnum!
}
enum PhpEnum {
A
B
C
}
SDL);
$this->schema = BuildSchema::build($documentNode);
$resolvers = [
'phpEnum' => fn (): BackedPhpEnum => BackedPhpEnum::A,
];
self::assertSame(
['data' => ['phpEnum' => 'A']],
GraphQL::executeQuery($this->schema, '{ phpEnum(fromEnum: A) }', $resolvers)->toArray()
);
}
public function testSerializesNativeUnitEnums(): void
{
if (version_compare(phpversion(), '8.1', '<')) {
self::markTestSkipped('Native PHP enums are only available with PHP 8.1');
}
$documentNode = Parser::parse(<<<'SDL'
type Query {
phpEnum(fromEnum: PhpEnum!): PhpEnum!
}
enum PhpEnum {
A
B
C
}
SDL);
$this->schema = BuildSchema::build($documentNode);
$resolvers = [
'phpEnum' => fn (): PhpEnum => PhpEnum::B,
];
self::assertSame(
['data' => ['phpEnum' => 'B']],
GraphQL::executeQuery($this->schema, '{ phpEnum(fromEnum: B) }', $resolvers)->toArray()
);
}
}