graphql-php/tests/Validator/QuerySecurityTestCase.php
2018-08-31 14:41:18 +02:00

98 lines
2.5 KiB
PHP

<?php
namespace GraphQL\Tests\Validator;
use GraphQL\Error\FormattedError;
use GraphQL\Language\Parser;
use GraphQL\Type\Introspection;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\QuerySecurityRule;
use PHPUnit\Framework\TestCase;
abstract class QuerySecurityTestCase extends TestCase
{
/**
* @param $max
*
* @return QuerySecurityRule
*/
abstract protected function getRule($max);
/**
* @param $max
* @param $count
*
* @return string
*/
abstract protected function getErrorMessage($max, $count);
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage argument must be greater or equal to 0.
*/
public function testMaxQueryDepthMustBeGreaterOrEqualTo0() : void
{
$this->getRule(-1);
}
protected function createFormattedError($max, $count, $locations = [])
{
return FormattedError::create($this->getErrorMessage($max, $count), $locations);
}
protected function assertDocumentValidator($queryString, $max, array $expectedErrors = [])
{
$errors = DocumentValidator::validate(
QuerySecuritySchema::buildSchema(),
Parser::parse($queryString),
[$this->getRule($max)]
);
$this->assertEquals($expectedErrors, array_map(['GraphQL\Error\Error', 'formatError'], $errors), $queryString);
return $errors;
}
protected function assertIntrospectionQuery($maxExpected)
{
$query = Introspection::getIntrospectionQuery();
$this->assertMaxValue($query, $maxExpected);
}
protected function assertIntrospectionTypeMetaFieldQuery($maxExpected)
{
$query = '
{
__type(name: "Human") {
name
}
}
';
$this->assertMaxValue($query, $maxExpected);
}
protected function assertTypeNameMetaFieldQuery($maxExpected)
{
$query = '
{
human {
__typename
firstName
}
}
';
$this->assertMaxValue($query, $maxExpected);
}
protected function assertMaxValue($query, $maxExpected)
{
$this->assertDocumentValidator($query, $maxExpected);
$newMax = $maxExpected - 1;
if ($newMax === QuerySecurityRule::DISABLED) {
return;
}
$this->assertDocumentValidator($query, $newMax, [$this->createFormattedError($newMax, $maxExpected)]);
}
}