Completed
Push — master ( 39bfaa...9e787e )
by Vladimir
15s queued 14s
created

QueryComplexityTest::testGetQueryComplexity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
dl 0
loc 13
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Tests\Validator;
6
7
use GraphQL\Error\Error;
8
use GraphQL\Language\AST\NodeKind;
9
use GraphQL\Language\Parser;
10
use GraphQL\Validator\DocumentValidator;
11
use GraphQL\Validator\Rules\CustomValidationRule;
12
use GraphQL\Validator\Rules\QueryComplexity;
13
use GraphQL\Validator\ValidationContext;
14
use function count;
15
16
class QueryComplexityTest extends QuerySecurityTestCase
17
{
18
    /** @var QueryComplexity */
19
    private static $rule;
20
21
    public function testSimpleQueries() : void
22
    {
23
        $query = 'query MyQuery { human { firstName } }';
24
25
        $this->assertDocumentValidators($query, 2, 3);
26
    }
27
28
    public function testGetQueryComplexity() : void
29
    {
30
        $query = 'query MyQuery { human { firstName } }';
31
32
        $rule = $this->getRule(5);
33
34
        DocumentValidator::validate(
35
            QuerySecuritySchema::buildSchema(),
36
            Parser::parse($query),
37
            [$rule]
38
        );
39
40
        self::assertEquals(2, $rule->getQueryComplexity(), $query);
41
    }
42
43
    private function assertDocumentValidators($query, $queryComplexity, $startComplexity)
44
    {
45
        for ($maxComplexity = $startComplexity; $maxComplexity >= 0; --$maxComplexity) {
46
            $positions = [];
47
48
            if ($maxComplexity < $queryComplexity && $maxComplexity !== QueryComplexity::DISABLED) {
49
                $positions = [$this->createFormattedError($maxComplexity, $queryComplexity)];
50
            }
51
52
            $this->assertDocumentValidator($query, $maxComplexity, $positions);
53
        }
54
    }
55
56
    public function testInlineFragmentQueries() : void
57
    {
58
        $query = 'query MyQuery { human { ... on Human { firstName } } }';
59
60
        $this->assertDocumentValidators($query, 2, 3);
61
    }
62
63
    public function testFragmentQueries() : void
64
    {
65
        $query = 'query MyQuery { human { ...F1 } } fragment F1 on Human { firstName}';
66
67
        $this->assertDocumentValidators($query, 2, 3);
68
    }
69
70
    public function testAliasesQueries() : void
71
    {
72
        $query = 'query MyQuery { thomas: human(name: "Thomas") { firstName } jeremy: human(name: "Jeremy") { firstName } }';
73
74
        $this->assertDocumentValidators($query, 4, 5);
75
    }
76
77
    public function testCustomComplexityQueries() : void
78
    {
79
        $query = 'query MyQuery { human { dogs { name } } }';
80
81
        $this->assertDocumentValidators($query, 12, 13);
82
    }
83
84
    public function testCustomComplexityWithArgsQueries() : void
85
    {
86
        $query = 'query MyQuery { human { dogs(name: "Root") { name } } }';
87
88
        $this->assertDocumentValidators($query, 3, 4);
89
    }
90
91
    public function testCustomComplexityWithVariablesQueries() : void
92
    {
93
        $query = 'query MyQuery($dog: String!) { human { dogs(name: $dog) { name } } }';
94
95
        $this->getRule()->setRawVariableValues(['dog' => 'Roots']);
96
97
        $this->assertDocumentValidators($query, 3, 4);
98
    }
99
100
    /**
101
     * @param int $maxDepth
102
     *
103
     * @return QueryComplexity
104
     */
105
    protected function getRule($maxDepth = null)
106
    {
107
        if (self::$rule === null) {
108
            self::$rule = new QueryComplexity($maxDepth);
109
        } elseif ($maxDepth !== null) {
110
            self::$rule->setMaxQueryComplexity($maxDepth);
111
        }
112
113
        return self::$rule;
114
    }
115
116
    public function testQueryWithEnabledIncludeDirectives() : void
117
    {
118
        $query = 'query MyQuery($withDogs: Boolean!) { human { dogs(name: "Root") @include(if:$withDogs) { name } } }';
119
120
        $this->getRule()->setRawVariableValues(['withDogs' => true]);
121
122
        $this->assertDocumentValidators($query, 3, 4);
123
    }
124
125
    public function testQueryWithDisabledIncludeDirectives() : void
126
    {
127
        $query = 'query MyQuery($withDogs: Boolean!) { human { dogs(name: "Root") @include(if:$withDogs) { name } } }';
128
129
        $this->getRule()->setRawVariableValues(['withDogs' => false]);
130
131
        $this->assertDocumentValidators($query, 1, 2);
132
    }
133
134
    public function testQueryWithEnabledSkipDirectives() : void
135
    {
136
        $query = 'query MyQuery($withoutDogs: Boolean!) { human { dogs(name: "Root") @skip(if:$withoutDogs) { name } } }';
137
138
        $this->getRule()->setRawVariableValues(['withoutDogs' => true]);
139
140
        $this->assertDocumentValidators($query, 1, 2);
141
    }
142
143
    public function testQueryWithDisabledSkipDirectives() : void
144
    {
145
        $query = 'query MyQuery($withoutDogs: Boolean!) { human { dogs(name: "Root") @skip(if:$withoutDogs) { name } } }';
146
147
        $this->getRule()->setRawVariableValues(['withoutDogs' => false]);
148
149
        $this->assertDocumentValidators($query, 3, 4);
150
    }
151
152
    public function testQueryWithMultipleDirectives() : void
153
    {
154
        $query = 'query MyQuery($withDogs: Boolean!, $withoutDogName: Boolean!) { human { dogs(name: "Root") @include(if:$withDogs) { name @skip(if:$withoutDogName) } } }';
155
156
        $this->getRule()->setRawVariableValues([
157
            'withDogs'       => true,
158
            'withoutDogName' => true,
159
        ]);
160
161
        $this->assertDocumentValidators($query, 2, 3);
162
    }
163
164
    public function testComplexityIntrospectionQuery() : void
165
    {
166
        $this->assertIntrospectionQuery(181);
167
    }
168
169
    public function testIntrospectionTypeMetaFieldQuery() : void
170
    {
171
        $this->assertIntrospectionTypeMetaFieldQuery(2);
172
    }
173
174
    public function testTypeNameMetaFieldQuery() : void
175
    {
176
        $this->assertTypeNameMetaFieldQuery(3);
177
    }
178
179
    public function testSkippedWhenThereAreOtherValidationErrors() : void
180
    {
181
        $query = 'query MyQuery { human(name: INVALID_VALUE) { dogs {name} } }';
182
183
        $reportedError = new Error('OtherValidatorError');
184
        $otherRule     = new CustomValidationRule(
185
            'otherRule',
186
            static function (ValidationContext $context) use ($reportedError) {
187
                return [
188
                    NodeKind::OPERATION_DEFINITION => [
189
                        'leave' => static function () use ($context, $reportedError) {
190
                            $context->reportError($reportedError);
191
                        },
192
                    ],
193
                ];
194
            }
195
        );
196
197
        $errors = DocumentValidator::validate(
198
            QuerySecuritySchema::buildSchema(),
199
            Parser::parse($query),
200
            [$otherRule, $this->getRule(1)]
201
        );
202
203
        self::assertEquals(1, count($errors));
204
        self::assertSame($reportedError, $errors[0]);
205
206
        $this->expectException(Error::class);
207
        DocumentValidator::validate(
208
            QuerySecuritySchema::buildSchema(),
209
            Parser::parse($query),
210
            [$this->getRule(1)]
211
        );
212
    }
213
214
    /**
215
     * @param int $max
216
     * @param int $count
217
     *
218
     * @return string
219
     */
220
    protected function getErrorMessage($max, $count)
221
    {
222
        return QueryComplexity::maxQueryComplexityErrorMessage($max, $count);
223
    }
224
}
225