Completed
Pull Request — master (#245)
by Alexis
02:33
created

HttpAssertions::assertStatusCode()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 8.7624
cc 5
eloc 12
nc 4
nop 2
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
    public function isSuccessful(Response $response, $success = true, $type = 'text/html')
30
    {
31
        try {
32
            $crawler = new Crawler();
33
            $crawler->addContent($response->getContent(), $type);
34
            if (!count($crawler->filter('title'))) {
35
                $title = '['.$response->getStatusCode().'] - '.$response->getContent();
36
            } else {
37
                $title = $crawler->filter('title')->text();
38
            }
39
        } catch (\Exception $e) {
40
            $title = $e->getMessage();
41
        }
42
43
        if ($success) {
44
            $this->assertTrue($response->isSuccessful(), 'The Response was not successful: '.$title);
45
        } else {
46
            $this->assertFalse($response->isSuccessful(), 'The Response was successful: '.$title);
47
        }
48
    }
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
    public function assertStatusCode($expectedStatusCode, Client $client)
59
    {
60
        $helpfulErrorMessage = null;
61
62
        if ($expectedStatusCode !== $client->getResponse()->getStatusCode()) {
63
            // Get a more useful error message, if available
64
            if ($exception = $client->getContainer()->get('liip_functional_test.exception_listener')->getLastException()) {
65
                $helpfulErrorMessage = $exception->getMessage();
66
            } elseif (count($validationErrors = $client->getContainer()->get('liip_functional_test.validator')->getLastErrors())) {
67
                $helpfulErrorMessage = "Unexpected validation errors:\n";
68
69
                foreach ($validationErrors as $error) {
70
                    $helpfulErrorMessage .= sprintf("+ %s: %s\n", $error->getPropertyPath(), $error->getMessage());
71
                }
72
            } else {
73
                $helpfulErrorMessage = substr($client->getResponse(), 0, 200);
74
            }
75
        }
76
77
        self::assertEquals($expectedStatusCode, $client->getResponse()->getStatusCode(), $helpfulErrorMessage);
78
    }
79
80
    /**
81
     * Assert that the last validation errors within $container match the
82
     * expected keys.
83
     *
84
     * @param array              $expected  A flat array of field names
85
     * @param ContainerInterface $container
86
     */
87
    public function assertValidationErrors(array $expected, ContainerInterface $container)
88
    {
89
        self::assertThat(
90
            $container->get('liip_functional_test.validator')->getLastErrors(),
91
            new ValidationErrorsConstraint($expected),
92
            'Validation errors should match.'
93
        );
94
    }
95
}
96