-
Notifications
You must be signed in to change notification settings - Fork 1
/
GraphQLAssertions.php
273 lines (234 loc) · 9.39 KB
/
GraphQLAssertions.php
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
<?php declare(strict_types = 1);
namespace LastDragon_ru\LaraASP\GraphQL\Testing;
use Closure;
use Exception;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeList;
use GraphQL\Type\Definition\Argument;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\EnumValueDefinition;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\InputObjectField;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use GraphQL\Utils\BreakingChangesFinder;
use GraphQL\Utils\BuildClientSchema;
use GraphQL\Utils\BuildSchema;
use Illuminate\Contracts\Foundation\Application;
use LastDragon_ru\LaraASP\GraphQLPrinter\Contracts\Printer;
use LastDragon_ru\LaraASP\GraphQLPrinter\Contracts\Result;
use LastDragon_ru\LaraASP\GraphQLPrinter\Contracts\Settings;
use LastDragon_ru\LaraASP\GraphQLPrinter\Testing\GraphQLAssertions as PrinterGraphQLAssertions;
use LastDragon_ru\LaraASP\GraphQLPrinter\Testing\GraphQLExpected;
use LastDragon_ru\LaraASP\GraphQLPrinter\Testing\TestSettings;
use LastDragon_ru\LaraASP\Testing\Utils\Args;
use Nuwave\Lighthouse\Schema\AST\DocumentAST;
use Nuwave\Lighthouse\Schema\SchemaBuilder;
use Nuwave\Lighthouse\Testing\MocksResolvers;
use Nuwave\Lighthouse\Testing\TestSchemaProvider;
use PHPUnit\Framework\TestCase;
use SplFileInfo;
use function assert;
use function implode;
use function ksort;
use function trim;
/**
* @phpstan-import-type Change from BreakingChangesFinder
*
* @mixin TestCase
*/
trait GraphQLAssertions {
use MocksResolvers;
use PrinterGraphQLAssertions {
assertGraphQLResult as private printerAssertGraphQLResult;
}
// <editor-fold desc="Abstract">
// =========================================================================
abstract protected function app(): Application;
// </editor-fold>
// <editor-fold desc="Assertions">
// =========================================================================
/**
* Compares GraphQL schema with current (application) public (client) schema.
*/
public function assertGraphQLIntrospectionEquals(
GraphQLExpected|SplFileInfo|string $expected,
string $message = '',
): void {
// Schema
$schema = $this->getGraphQLSchema();
$schema = Introspection::fromSchema($schema);
$schema = BuildClientSchema::build($schema);
if (!($expected instanceof GraphQLExpected)) {
$expected = (new GraphQLExpected($expected))->setSchema($schema);
}
// Settings
if ($expected->getSettings() === null) {
$filter = static fn () => true;
$expected = $expected->setSettings(
(new TestSettings())
->setPrintUnusedDefinitions(true)
->setTypeDefinitionFilter($filter)
->setDirectiveDefinitionFilter($filter),
);
}
// Assert
$this->assertGraphQLPrintableEquals($expected, $schema, $message);
}
/**
* Compares GraphQL schema with current (application) schema.
*/
public function assertGraphQLSchemaEquals(
GraphQLExpected|SplFileInfo|string $expected,
string $message = '',
): void {
$this->assertGraphQLPrintableEquals(
$expected,
$this->getGraphQLSchema(),
$message,
);
}
/**
* Validates current (application) schema.
*/
public function assertGraphQLSchemaValid(?string $message = null): void {
// To perform validation, we should load all directives first. This is
// required because they can be defined inside the schema (and it is
// fine) or as a PHP class (in this case, the definition should be added
// to the schema by hand).
//
// Why do not use `lighthouse:validate-schema` command? Because it loads
// all existing directives (even not used) and thus extremely slow.
$valid = true;
$message ??= 'The schema is not valid.';
try {
BuildSchema::build($this->getGraphQLSchemaString())->assertValid();
} catch (Exception $exception) {
$valid = false;
$message = "{$message}\n\n{$exception->getMessage()}";
}
self::assertTrue($valid, $message);
}
/**
* Checks the current (application) schema has no breaking changes.
*/
public function assertGraphQLSchemaNoBreakingChanges(
SplFileInfo|string $expected,
?string $message = null,
): void {
$oldSchema = BuildSchema::build(Args::content($expected));
$newSchema = BuildSchema::build($this->getGraphQLSchemaString());
$changes = BreakingChangesFinder::findBreakingChanges($oldSchema, $newSchema);
$changes = $this->getGraphQLChanges($changes);
$message = ($message ?? 'The breaking changes found!')."\n\n{$changes}\n";
self::assertTrue($changes === '', $message);
}
/**
* Checks the current (application) schema has no dangerous changes.
*/
public function assertGraphQLSchemaNoDangerousChanges(
SplFileInfo|string $expected,
?string $message = null,
): void {
$oldSchema = BuildSchema::build(Args::content($expected));
$newSchema = BuildSchema::build($this->getGraphQLSchemaString());
$changes = BreakingChangesFinder::findDangerousChanges($oldSchema, $newSchema);
$changes = $this->getGraphQLChanges($changes);
$message = ($message ?? 'The dangerous changes found!')."\n\n{$changes}\n";
self::assertTrue($changes === '', $message);
}
/**
* @param Closure(Printer, Node|Type|Directive|FieldDefinition|Argument|EnumValueDefinition|InputObjectField|Schema): Result $print
*/
private function assertGraphQLResult(
Node|Type|Directive|FieldDefinition|Argument|EnumValueDefinition|InputObjectField|Schema|GraphQLExpected|SplFileInfo|string $expected,
Node|Type|Directive|FieldDefinition|Argument|EnumValueDefinition|InputObjectField|Schema|Result|SplFileInfo|string $actual,
string $message,
Closure $print,
): Result {
if (!($expected instanceof GraphQLExpected)) {
$expected = (new GraphQLExpected($expected))->setSchema($this->getGraphQLSchema());
}
return $this->printerAssertGraphQLResult($expected, $actual, $message, $print);
}
// </editor-fold>
// <editor-fold desc="Helpers">
// =========================================================================
/**
* Sets the current (application) schema to the given.
*/
protected function useGraphQLSchema(Schema|DocumentNode|DocumentAST|SplFileInfo|string $schema): static {
if ($schema instanceof DocumentAST) {
// We just need all definitions
$schema = new DocumentNode([
'definitions' => (new NodeList([]))
->merge($schema->types)
->merge($schema->typeExtensions)
->merge($schema->directives),
]);
}
$schema = $schema instanceof Schema || $schema instanceof DocumentNode
? (string) $this->getGraphQLPrinter()->print($schema)
: Args::content($schema);
$provider = new TestSchemaProvider($schema);
$this->getGraphQLSchemaBuilder()->setSchema($this->app(), $provider);
return $this;
}
/**
* Resets the current (application) schema to the default schema.
*/
protected function resetGraphQLSchema(): static {
$this->getGraphQLSchemaBuilder()->setSchema($this->app(), null);
return $this;
}
protected function getGraphQLSchema(): Schema {
return $this->getGraphQLSchemaBuilder()->schema();
}
protected function getGraphQLPrinter(?Settings $settings = null): Printer {
return $this->app()->make(Printer::class)->setSettings($settings ?? new TestSettings());
}
protected function getGraphQLSchemaBuilder(): SchemaBuilderWrapper {
// Wrap
$container = $this->app();
$builder = $container->resolved(SchemaBuilder::class)
? $container->make(SchemaBuilder::class)
: null;
if (!($builder instanceof SchemaBuilderWrapper)) {
$container->extend(
SchemaBuilder::class,
static function (SchemaBuilder $builder): SchemaBuilder {
return new SchemaBuilderWrapper($builder);
},
);
}
// Instance
$builder = $container->make(SchemaBuilder::class);
assert($builder instanceof SchemaBuilderWrapper);
// Return
return $builder;
}
private function getGraphQLSchemaString(): string {
return (string) $this
->getGraphQLPrinter(new TestSettings())
->print($this->getGraphQLSchema());
}
/**
* @param array<array-key, Change> $changes
*/
private function getGraphQLChanges(array $changes): string {
$message = '';
$groups = [];
foreach ($changes as $change) {
$groups[$change['type']] ??= [];
$groups[$change['type']][] = $change['description'];
}
ksort($groups);
foreach ($groups as $type => $descriptions) {
$message .= "{$type}:\n\n* ".implode('* ', $descriptions)."\n\n";
}
return trim($message);
}
// </editor-fold>
}