HttpAssertions::assertStatusCode()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 29
ccs 0
cts 15
cp 0
crap 56
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Liip/FunctionalTestBundle
7
 *
8
 * (c) Lukas Kahwe Smith <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace Liip\FunctionalTestBundle\Utils;
15
16
use Liip\FunctionalTestBundle\Test\ValidationErrorsConstraint;
17
use PHPUnit\Framework\TestCase;
18
use Symfony\Bundle\FrameworkBundle\Client;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use Symfony\Component\DomCrawler\Crawler;
21
use Symfony\Component\HttpFoundation\Response;
22
23
class HttpAssertions extends TestCase
24
{
25
    /**
26
     * Checks the success state of a response.
27
     *
28
     * @param Response $response Response object
29
     * @param bool     $success  to define whether the response is expected to be successful
30
     */
31 1
    public static function isSuccessful(Response $response, bool $success = true, string $type = 'text/html'): void
32
    {
33
        try {
34 1
            $crawler = new Crawler();
35 1
            $crawler->addContent($response->getContent(), $type);
36
            if (!\count($crawler->filter('title'))) {
37
                $title = '['.$response->getStatusCode().'] - '.$response->getContent();
38
            } else {
39
                $title = $crawler->filter('title')->text();
40
            }
41 1
        } catch (\Exception $e) {
42 1
            $title = $e->getMessage();
43
        }
44
45 1
        if ($success) {
46 1
            self::assertTrue($response->isSuccessful(), 'The Response was not successful: '.$title);
47
        } else {
48
            self::assertFalse($response->isSuccessful(), 'The Response was successful: '.$title);
49
        }
50
    }
51
52
    /**
53
     * Asserts that the HTTP response code of the last request performed by
54
     * $client matches the expected code. If not, raises an error with more
55
     * information.
56
     */
57
    public static function assertStatusCode(int $expectedStatusCode, Client $client): void
58
    {
59
        $container = $client->getContainer();
60
61
        if ($container->has('test.service_container')) {
62
            $container = $container->get('test.service_container');
63
        }
64
65
        $helpfulErrorMessage = '';
66
67
        if ($expectedStatusCode !== $client->getResponse()->getStatusCode()) {
68
            // Get a more useful error message, if available
69
            if ($exception = $container->get('liip_functional_test.exception_listener')->getLastException()) {
70
                $helpfulErrorMessage = $exception->getMessage()."\n\n".$exception->getTraceAsString();
71
            } elseif (
72
                $container->has('liip_functional_test.validator') &&
73
                \count($validationErrors = $container->get('liip_functional_test.validator')->getLastErrors())
74
            ) {
75
                $helpfulErrorMessage = "Unexpected validation errors:\n";
76
77
                foreach ($validationErrors as $error) {
78
                    $helpfulErrorMessage .= sprintf("+ %s: %s\n", $error->getPropertyPath(), $error->getMessage());
79
                }
80
            } else {
81
                $helpfulErrorMessage = substr((string) $client->getResponse(), 0, 200);
82
            }
83
        }
84
85
        self::assertSame($expectedStatusCode, $client->getResponse()->getStatusCode(), $helpfulErrorMessage);
86
    }
87
88
    /**
89
     * Assert that the last validation errors within $container match the
90
     * expected keys.
91
     *
92
     * @param array $expected A flat array of field names
93
     */
94 1
    public static function assertValidationErrors(array $expected, ContainerInterface $container): void
95
    {
96 1
        if ($container->has('test.service_container')) {
97 1
            $container = $container->get('test.service_container');
98
        }
99
100 1
        if (!$container->has('liip_functional_test.validator')) {
101 1
            self::fail(sprintf(
102
                'Method %s() can not be used as the validation component of the Symfony framework is disabled.',
103
                __METHOD__
104
            ));
105
        }
106
107
        self::assertThat(
108
            $container->get('liip_functional_test.validator')->getLastErrors(),
109
            new ValidationErrorsConstraint($expected),
110
            'Validation errors should match.'
111
        );
112
    }
113
}
114