Failed Conditions
Pull Request — master (#11)
by Adrien
15:48 queued 12:33
created

AbstractServer::testSchemaIsValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Testing\Api;
6
7
use Ecodev\Felix\Api\Server;
1 ignored issue
show
Bug introduced by
The type Ecodev\Felix\Api\Server was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Ecodev\Felix\Testing\Traits\TestWithTransaction;
9
use Exception;
10
use GraphQL\Executor\ExecutionResult;
11
use GraphQL\Type\Schema;
12
use Laminas\Diactoros\ServerRequest;
13
use Mezzio\Session\Session;
14
use Mezzio\Session\SessionMiddleware;
15
use PHPUnit\Framework\TestCase;
16
17
abstract class AbstractServer extends TestCase
18
{
19
    use TestWithTransaction;
20
21
    /**
22
     * Should get user and call User::setCurrent().
23
     */
24
    abstract protected function setCurrentUser(?string $user): void;
25
26
    abstract protected function createSchema(): Schema;
27
28
    protected function createServer(bool $debug): Server
29
    {
30
        return new Server($this->createSchema(), $debug);
31
    }
32
33
    public function testSchemaIsValid(): void
34
    {
35
        $schema = $this->createSchema();
36
        $schema->assertValid();
37
38
        self::assertTrue(true, 'schema passes validation');
39
    }
40
41
    /**
42
     * @dataProvider providerQuery
43
     */
44
    public function testQuery(?string $user, ServerRequest $request, array $expected, ?callable $dataPreparator = null, ?callable $additionalAsserts = null): void
45
    {
46
        $this->setCurrentUser($user);
47
48
        if ($dataPreparator) {
49
            $dataPreparator(_em()->getConnection());
50
        }
51
52
        // Use this flag to easily debug API test issues
53
        /** @var bool $debug */
54
        $debug = false;
55
56
        // Configure server
57
        $server = $this->createServer($debug);
58
59
        // Execute query
60
        $result = $server->execute($request);
61
62
        $actual = $this->resultToArray($result, $debug);
63
64
        if ($debug) {
0 ignored issues
show
introduced by
The condition $debug is always false.
Loading history...
65
            ve($actual);
66
            unset($actual['errors'][0]['trace']);
67
        }
68
69
        self::assertEquals($expected, $actual);
70
71
        if ($additionalAsserts) {
72
            $additionalAsserts(_em()->getConnection());
73
        }
74
    }
75
76
    public function providerQuery(): array
77
    {
78
        $data = [];
79
        $files = glob('tests/data/query/*.php');
80
        if ($files === false) {
81
            throw new Exception('Could not find any queries to test server');
82
        }
83
84
        foreach ($files as $file) {
85
            $name = str_replace('-', ' ', basename($file, '.php'));
86
            $user = preg_replace('/\d/', '', explode(' ', $name)[0]);
87
            if ($user === 'anonymous') {
88
                $user = null;
89
            }
90
91
            $args = require $file;
92
93
            // Convert arg into request
94
            $request = new ServerRequest();
95
            $args[0] = $request
96
                ->withParsedBody($args[0])
97
                ->withAttribute(SessionMiddleware::SESSION_ATTRIBUTE, new Session([]))
98
                ->withMethod('POST')
99
                ->withHeader('content-type', ['application/json']);
100
101
            array_unshift($args, $user);
102
            $data[$name] = $args;
103
        }
104
105
        return $data;
106
    }
107
108
    /**
109
     * @param ExecutionResult|ExecutionResult[] $result
110
     */
111
    private function resultToArray(array|ExecutionResult $result, bool $debug): array
112
    {
113
        if (is_array($result)) {
0 ignored issues
show
introduced by
The condition is_array($result) is always true.
Loading history...
114
            foreach ($result as &$one) {
115
                $one = $this->oneResultToArray($one, $debug);
116
            }
117
        } else {
118
            $result = $this->oneResultToArray($result, $debug);
119
        }
120
121
        return $result;
122
    }
123
124
    private function oneResultToArray(ExecutionResult $result, bool $debug): array
125
    {
126
        $result = $result->toArray();
127
        if ($debug) {
128
            ve($result);
129
            // @phpstan-ignore-next-line
130
            unset($result['errors'][0]['trace']);
131
        }
132
133
        return $result;
134
    }
135
}
136