Completed
Push — master ( 2ac5c9...413932 )
by Lukas Kahwe
03:39
created

HttpAssertions::assertValidationErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

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