Passed
Pull Request — master (#3003)
by
unknown
07:38 queued 03:14
created

ApiTestAssertionsTrait   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 123
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 32
dl 0
loc 123
rs 10
c 1
b 0
f 0
wmc 19

8 Methods

Rating   Name   Duplication   Size   Complexity  
A assertMatchesResourceJsonSchema() 0 3 1
A getHttpResponse() 0 7 2
A assertJsonEquals() 0 10 3
A getHttpClient() 0 13 3
A getSchemaFactory() 0 13 5
A assertMatchesJsonSchema() 0 5 1
A assertArraySubset() 0 4 1
A assertJsonContains() 0 10 3
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test;
15
16
use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Constraint\ArraySubset;
17
use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Constraint\MatchesJsonSchema;
18
use ApiPlatform\Core\JsonSchema\Schema;
19
use ApiPlatform\Core\JsonSchema\SchemaFactoryInterface;
20
use PHPUnit\Framework\ExpectationFailedException;
21
use Psr\Container\ContainerInterface;
22
use Symfony\Contracts\HttpClient\ResponseInterface;
23
24
/**
25
 * @see \Symfony\Bundle\FrameworkBundle\Test\WebTestAssertionsTrait
26
 *
27
 * @experimental
28
 */
29
trait ApiTestAssertionsTrait
30
{
31
    use BrowserKitAssertionsTrait;
32
33
    /**
34
     * Asserts that the retrieved JSON contains has the specified subset.
35
     *
36
     * This method delegates to self::assertArraySubset().
37
     *
38
     * @param array|string $subset
39
     *
40
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
41
     * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
42
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
43
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
44
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
45
     */
46
    public static function assertJsonContains($subset, bool $checkForObjectIdentity = true, string $message = ''): void
47
    {
48
        if (\is_string($subset)) {
49
            $subset = json_decode($subset, true);
50
        }
51
        if (!\is_array($subset)) {
52
            throw new \InvalidArgumentException('$subset must be array or string (JSON array or JSON object)');
53
        }
54
55
        static::assertArraySubset($subset, self::getHttpResponse()->toArray(false), $checkForObjectIdentity, $message);
56
    }
57
58
    /**
59
     * Asserts that the retrieved JSON is equal to $json.
60
     *
61
     * Both values are canonicalized before the comparision.
62
     *
63
     * @param array|string $json
64
     */
65
    public static function assertJsonEquals($json, string $message = ''): void
66
    {
67
        if (\is_string($json)) {
68
            $json = json_decode($json, true);
69
        }
70
        if (!\is_array($json)) {
71
            throw new \InvalidArgumentException('$json must be array or string (JSON array or JSON object)');
72
        }
73
74
        static::assertEqualsCanonicalizing($json, self::getHttpResponse()->toArray(false), $message);
75
    }
76
77
    /**
78
     * Asserts that an array has a specified subset.
79
     *
80
     * Imported from dms/phpunit-arraysubset, because the original constraint has been deprecated.
81
     *
82
     * @copyright Sebastian Bergmann <[email protected]>
83
     * @copyright Rafael Dohms <[email protected]>
84
     *
85
     * @see https://github.com/sebastianbergmann/phpunit/issues/3494
86
     *
87
     * @param iterable $subset
88
     * @param iterable $array
89
     *
90
     * @throws ExpectationFailedException
91
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
92
     * @throws \Exception
93
     */
94
    public static function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false, string $message = ''): void
95
    {
96
        $constraint = new ArraySubset($subset, $checkForObjectIdentity);
97
        static::assertThat($array, $constraint, $message);
98
    }
99
100
    /**
101
     * @param Schema|array|string $jsonSchema
102
     */
103
    public static function assertMatchesJsonSchema($jsonSchema, ?int $checkMode = null, string $message = ''): void
104
    {
105
        $constraint = new MatchesJsonSchema($jsonSchema, $checkMode);
106
107
        static::assertThat(self::getHttpResponse()->toArray(false), $constraint, $message);
108
    }
109
110
    public static function assertMatchesResourceJsonSchema(string $resourceClass, string $format = 'json', bool $output = true, ?string $operationType = null, ?string $operationName = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): void
111
    {
112
        static::assertMatchesJsonSchema(self::getSchemaFactory()->buildSchema($resourceClass, $format, $output, $operationType, $operationName, $schema, $serializerContext, $forceCollection));
113
    }
114
115
    private static function getHttpClient(Client $newClient = null): ?Client
116
    {
117
        static $client;
118
119
        if (0 < \func_num_args()) {
120
            return $client = $newClient;
121
        }
122
123
        if (!$client instanceof Client) {
124
            static::fail(sprintf('A client must be set to make assertions on it. Did you forget to call "%s::createClient()"?', __CLASS__));
125
        }
126
127
        return $client;
128
    }
129
130
    private static function getHttpResponse(): ResponseInterface
131
    {
132
        if (!$response = self::getHttpClient()->getResponse()) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::getHttpClient() targeting ApiPlatform\Core\Bridge\...sTrait::getHttpClient() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
133
            static::fail('A client must have an HTTP Response to make assertions. Did you forget to make an HTTP request?');
134
        }
135
136
        return $response;
137
    }
138
139
    private static function getSchemaFactory(): SchemaFactoryInterface
140
    {
141
        static $schemaFactory;
142
143
        if (null !== $schemaFactory) {
144
            return $schemaFactory;
145
        }
146
147
        if (!isset(static::$container) || !static::$container instanceof ContainerInterface || !static::$container->has('api_platform.json_schema.schema_factory')) {
148
            static::fail();
149
        }
150
151
        return $schemaFactory = static::$container->get('api_platform.json_schema.schema_factory');
152
    }
153
}
154