Completed
Push — test-EZP-26707-issearchable-fu... ( 965a07...6812c2 )
by
unknown
33:45 queued 07:39
created

TestCase::tearDownAfterClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the Functional\TestCase class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 *
9
 * @version //autogentag//
10
 */
11
namespace eZ\Bundle\EzPublishRestBundle\Tests\Functional;
12
13
use Buzz\Message\Request as HttpRequest;
14
use Buzz\Message\Response as HttpResponse;
15
use PHPUnit_Framework_TestCase;
16
17
class TestCase extends PHPUnit_Framework_TestCase
18
{
19
    /**
20
     * @var \Buzz\Client\ClientInterface
21
     */
22
    private $httpClient;
23
24
    /**
25
     * @var string
26
     */
27
    private $httpHost;
28
29
    /**
30
     * @var string
31
     * Basic auth login:password
32
     */
33
    private $httpAuth;
34
35
    protected static $testSuffix;
36
37
    protected function setUp()
38
    {
39
        parent::setUp();
40
41
        $this->httpHost = getenv('EZP_TEST_REST_HOST') ?: 'localhost';
42
        $this->httpAuth = getenv('EZP_TEST_REST_AUTH') ?: 'admin:publish';
43
44
        $this->httpClient = new \Buzz\Client\Curl();
45
        $this->httpClient->setVerifyPeer(false);
46
        $this->httpClient->setTimeout(90);
47
        $this->httpClient->setOption(CURLOPT_FOLLOWLOCATION, false);
48
    }
49
50
    /**
51
     * @return HttpResponse
52
     */
53
    public function sendHttpRequest(HttpRequest $request)
54
    {
55
        $response = new HttpResponse();
56
        $this->httpClient->send($request, $response);
57
58
        return $response;
59
    }
60
61
    /**
62
     * @return HttpRequest
63
     */
64
    public function createHttpRequest($method, $uri, $contentType = '', $acceptType = '')
65
    {
66
        $request = new HttpRequest($method, $uri, $this->httpHost);
67
        $request->addHeader('Authorization: Basic ' . base64_encode($this->httpAuth));
68
        $request->addHeader('Content-Type: ' . $this->generateMediaTypeString($contentType));
69
        $request->addHeader('Accept: ' . $this->generateMediaTypeString($acceptType));
70
71
        return $request;
72
    }
73
74
    protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
75
    {
76
        $responseCode = $response->getStatusCode();
77
        if ($responseCode != $expected) {
78
            $errorMessageString = '';
79
            if ($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+xml') {
80
                $body = \simplexml_load_string($response->getContent());
81
                $errorMessageString = $body->errorDescription;
0 ignored issues
show
Bug introduced by
The property errorDescription does not seem to exist in SimpleXMLElement.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
82
            } elseif (($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+json')) {
83
                $body = json_decode($response->getContent());
84
                $errorMessageString = "Error message: {$body->ErrorMessage->errorDescription}";
85
            }
86
87
            self::assertEquals($expected, $responseCode, $errorMessageString);
88
        }
89
    }
90
91
    protected function assertHttpResponseHasHeader(HttpResponse $response, $header, $expectedValue = null)
92
    {
93
        $headerValue = $response->getHeader($header);
94
        self::assertNotNull($headerValue, "Failed asserting that response has a $header header");
95
        if ($expectedValue !== null) {
96
            self::assertEquals($expectedValue, $headerValue);
97
        }
98
    }
99
100
    protected function generateMediaTypeString($typeString)
101
    {
102
        return "application/vnd.ez.api.$typeString";
103
    }
104
105
    protected function addCreatedElement($href)
106
    {
107
        $testCase = $this;
108
        self::$createdContent[$href] = function () use ($href, $testCase) {
109
            $testCase->sendHttpRequest(
110
                $testCase->createHttpRequest('DELETE', $href)
111
            );
112
        };
113
    }
114
115
    public static function tearDownAfterClass()
116
    {
117
        self::clearCreatedElement(self::$createdContent);
118
    }
119
120
    private static function clearCreatedElement(array $contentArray)
121
    {
122
        foreach (array_reverse($contentArray) as $href => $callback) {
123
            $callback();
124
        }
125
    }
126
127
    /**
128
     * @param string $parentLocationId The REST id of the parent location
129
     *
130
     * @return array created Content, as an array
131
     */
132
    protected function createFolder($string, $parentLocationId)
133
    {
134
        $string = $this->addTestSuffix($string);
135
        $xml = <<< XML
136
<?xml version="1.0" encoding="UTF-8"?>
137
<ContentCreate>
138
  <ContentType href="/api/ezp/v2/content/types/1" />
139
  <mainLanguageCode>eng-GB</mainLanguageCode>
140
  <LocationCreate>
141
    <ParentLocation href="{$parentLocationId}" />
142
    <priority>0</priority>
143
    <hidden>false</hidden>
144
    <sortField>PATH</sortField>
145
    <sortOrder>ASC</sortOrder>
146
  </LocationCreate>
147
  <Section href="/api/ezp/v2/content/sections/1" />
148
  <alwaysAvailable>true</alwaysAvailable>
149
  <remoteId>{$string}</remoteId>
150
  <User href="/api/ezp/v2/user/users/14" />
151
  <modificationDate>2012-09-30T12:30:00</modificationDate>
152
  <fields>
153
    <field>
154
      <fieldDefinitionIdentifier>name</fieldDefinitionIdentifier>
155
      <languageCode>eng-GB</languageCode>
156
      <fieldValue>{$string}</fieldValue>
157
    </field>
158
  </fields>
159
</ContentCreate>
160
XML;
161
162
        return $this->createContent($xml);
163
    }
164
165
    /**
166
     * @param $xml
167
     *
168
     * @return array Content key of the Content struct array
169
     */
170
    protected function createContent($xml)
171
    {
172
        $request = $this->createHttpRequest('POST', '/api/ezp/v2/content/objects', 'ContentCreate+xml', 'Content+json');
173
        $request->setContent($xml);
174
175
        $response = $this->sendHttpRequest($request);
176
177
        self::assertHttpResponseCodeEquals($response, 201);
178
179
        $content = json_decode($response->getContent(), true);
180
181
        if (!isset($content['Content']['CurrentVersion']['Version'])) {
182
            self::fail("Incomplete response (no version):\n" . $response->getContent() . "\n");
183
        }
184
185
        $response = $this->sendHttpRequest(
186
            $request = $this->createHttpRequest('PUBLISH', $content['Content']['CurrentVersion']['Version']['_href'])
187
        );
188
189
        self::assertHttpResponseCodeEquals($response, 204);
190
191
        $this->addCreatedElement($content['Content']['_href'], true);
192
193
        return $content['Content'];
194
    }
195
196
    /**
197
     * @param string $contentHref
198
     *
199
     * @return array
200
     */
201 View Code Duplication
    protected function getContentLocations($contentHref)
202
    {
203
        $response = $this->sendHttpRequest(
204
            $this->createHttpRequest('GET', "$contentHref/locations", '', 'LocationList+json')
205
        );
206
        self::assertHttpResponseCodeEquals($response, 200);
207
        $folderLocations = json_decode($response->getContent(), true);
208
209
        return $folderLocations;
210
    }
211
212
    protected function addTestSuffix($string)
213
    {
214
        if (!isset(self::$testSuffix)) {
215
            self::$testSuffix = uniqid();
216
        }
217
218
        return $string . '_' . self::$testSuffix;
219
    }
220
221
    /**
222
     * List of REST contentId (/content/objects/12345) created by tests.
223
     *
224
     * @var array
225
     */
226
    private static $createdContent = array();
227
}
228