1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Tests\Framework\TestRequest;
use Piwik\API\Request;
use PHPUnit\Framework\Assert as Asserts;
use Exception;
use Piwik\Tests\Framework\Fixture;
use Piwik\Tests\Framework\TestCase\SystemTestCase;
/**
* Utility class used to obtain and process API responses for API tests.
* @since 2.8.0
*/
class Response
{
private $processedResponseText;
private $params;
private $requestUrl;
public function __construct($apiResponse, $params, $requestUrl, $normalize = true)
{
$this->params = $params;
$this->requestUrl = $requestUrl;
$apiResponse = (string) $apiResponse;
$this->processedResponseText = $normalize ? $this->normalizeApiResponse($apiResponse) : $apiResponse;
}
public function getResponseText()
{
return $this->processedResponseText;
}
public function save($path)
{
file_put_contents($path, $this->processedResponseText);
}
public static function loadFromFile($path, $params, $requestUrl)
{
$contents = @file_get_contents($path);
if (empty($contents)) {
throw new Exception("$path does not exist");
}
return new Response($contents, $params, $requestUrl);
}
public static function loadFromApi($params, $requestUrl, $normalize = true)
{
$testRequest = new Request($requestUrl);
// Cast as string is important. For example when calling
// with format=original, objects or php arrays can be returned.
$response = (string) $testRequest->process();
return new Response($response, $params, $requestUrl, $normalize);
}
public static function assertEquals(Response $expected, Response $actual, $message = false)
{
$expectedText = $expected->getResponseText();
$actualText = $actual->getResponseText();
$expectedText = preg_replace('/[^\x09-\x0d\x1b\x20-\xff]/', '', $expectedText);
$actualText = preg_replace('/[^\x09-\x0d\x1b\x20-\xff]/', '', $actualText);
if ($expected->requestUrl['format'] == 'xml') {
Asserts::assertXmlStringEqualsXmlString($expectedText, $actualText, $message);
return;
}
// check content size to get quick feedback and avoid lengthy diff
$checkSizeFirst = array('pdf', 'csv', 'html');
if(!empty($expected->requestUrl['reportFormat'])
&& in_array($expected->requestUrl['reportFormat'], $checkSizeFirst)) {
Asserts::assertEquals(strlen($expectedText), strlen($actualText), $message);
}
Asserts::assertEquals($expectedText, $actualText, $message);
}
private function normalizeApiResponse($apiResponse)
{
$apiResponse = $this->removeSubtableIdsFromXml($apiResponse);
$apiResponse = $this->removePageViewIds($apiResponse);
if ($this->shouldDeleteLiveIds()) {
$apiResponse = $this->removeAllIdsFromXml($apiResponse);
}
if ($this->shouldDeleteLiveDates()) {
$apiResponse = $this->removeAllLiveDatesFromXml($apiResponse);
} else if ($this->requestHasNonDeterministicDate()) {
// If date=lastN the <prettyDate> element will change each day, we remove XML element before comparison
if ($this->requestUrl['method'] == 'API.getProcessedReport') {
$apiResponse = $this->removeXmlElement($apiResponse, 'prettyDate');
}
$apiResponse = $this->removeXmlElement($apiResponse, 'visitServerHour');
$regex = "/date=[-0-9,%Ca-z]+/"; // need to remove %2C which is encoded ,
$apiResponse = preg_replace($regex, 'date=', $apiResponse);
}
$apiResponse = $this->normalizePdfContent($apiResponse);
$apiResponse = $this->removeXmlFields($apiResponse);
$apiResponse = $this->removeTodaysDate($apiResponse);
$apiResponse = $this->normalizeDecimalFields($apiResponse);
$apiResponse = $this->normalizeEncodingPhp533($apiResponse);
$apiResponse = $this->normalizeSpaces($apiResponse);
$apiResponse = $this->replacePiwikUrl($apiResponse);
return $apiResponse;
}
private function removeTodaysDate($apiResponse)
{
$result = preg_replace('/' . date('Y-m-d') . ' [0-9]{2}:[0-9]{2}:[0-9]{2}/', 'today-date-removed-in-tests', $apiResponse);
$result = str_replace(date('Y-m-d'), 'today-date-removed-in-tests', $result);;
return $result;
}
private function normalizeEncodingPhp533($apiResponse)
{
return str_replace('&#039;', "'", $apiResponse);
}
private function removePageViewIds($apiResponse)
{
$toRemove = array(
'idpageview',
);
return $this->removeXmlFields($apiResponse, $toRemove);
}
private function removeAllIdsFromXml($apiResponse)
{
$toRemove = array(
'visitorId',
'nextVisitorId',
'previousVisitorId',
'idvisitor'
);
return $this->removeXmlFields($apiResponse, $toRemove);
}
private function removeAllLiveDatesFromXml($apiResponse)
{
$toRemove = array(
'serverDate',
'firstActionTimestamp',
'lastActionTimestamp',
'lastActionDateTime',
'serverTimestamp',
'serverTimePretty',
'daysAgo',
'serverDatePretty',
'serverDatePrettyFirstAction',
'serverTimePrettyFirstAction',
'goalTimePretty',
'serverTimePretty',
'visitServerHour',
'timestamp',
'date',
'prettyDate',
'serverDateTimePrettyFirstAction'
);
return $this->removeXmlFields($apiResponse, $toRemove);
}
/**
* Removes content from PDF binary the content that changes with the datetime or other random Ids
*/
private function normalizePdfContent($response)
{
// normalize date markups and document ID in pdf files :
// - /LastModified (D:20120820204023+00'00')
// - /CreationDate (D:20120820202226+00'00')
// - /ModDate (D:20120820202226+00'00')
// - /M (D:20120820202226+00'00')
// - /ID [ <0f5cc387dc28c0e13e682197f485fe65> <0f5cc387dc28c0e13e682197f485fe65> ]
$response = preg_replace('/\(D:[0-9]{14}/', '(D:19700101000000', $response);
$response = preg_replace('/\/ID \[ <.*> ]/', '', $response);
$response = preg_replace('/\/id:\[ <.*> ]/', '', $response);
$response = $this->removeXmlElement($response, "xmp:CreateDate");
$response = $this->removeXmlElement($response, "xmp:ModifyDate");
$response = $this->removeXmlElement($response, "xmp:MetadataDate");
$response = $this->removeXmlElement($response, "xmpMM:DocumentID");
$response = $this->removeXmlElement($response, "xmpMM:InstanceID");
return $response;
}
private function removeXmlFields($input, $fieldsToRemove = false)
{
if ($fieldsToRemove === false) {
$fieldsToRemove = @$this->params['xmlFieldsToRemove'];
}
if (!is_array($fieldsToRemove)) {
$fieldsToRemove = array();
}
foreach ($fieldsToRemove as $xml) {
$input = $this->removeXmlElement($input, $xml);
}
return $input;
}
private function removeXmlElement($input, $xmlElement, $testNotSmallAfter = true)
{
// Only raise error if there was some data before
$testNotSmallAfter = strlen($input > 100) && $testNotSmallAfter;
$oldInput = $input;
$input = preg_replace('/(<' . $xmlElement . '>.+?<\/' . $xmlElement . '>)/', '', $input);
$input = str_replace('<' . $xmlElement . ' />', '', $input);
// check we didn't delete the whole string
if ($testNotSmallAfter && $input != $oldInput) {
$this->assertTrue(strlen($input) > 100);
}
return $input;
}
private function requestHasNonDeterministicDate()
{
if (empty($this->requestUrl['date'])) {
return false;
}
$dateTime = $this->requestUrl['date'];
return strpos($dateTime, 'last') !== false
|| strpos($dateTime, 'today') !== false
|| strpos($dateTime, 'now') !== false;
}
private function shouldDeleteLiveIds()
{
return empty($this->params['keepLiveIds']);
}
private function shouldDeleteLiveDates()
{
return empty($this->params['keepLiveDates'])
&& ($this->requestUrl['method'] == 'Live.getLastVisits'
|| $this->requestUrl['method'] == 'Live.getLastVisitsDetails'
|| $this->requestUrl['method'] == 'Live.getVisitorProfile');
}
private function normalizeDecimalFields($response)
{
// Do not test for TRUNCATE(SUM()) returning .00 on mysqli since this is not working
// http://bugs.php.net/bug.php?id=54508
$response = str_replace('.000000</l', '</l', $response); //lat/long
$response = str_replace('.00</revenue>', '</revenue>', $response);
// eg. <totalEcommerceRevenue>0.00</totalEcommerceRevenue>
$response = str_replace('.00</t', '</t', $response);
return $response;
}
private function normalizeSpaces($apiResponse)
{
if (strpos($this->requestUrl['format'], 'json') === 0) {
$apiResponse = str_replace(' ', '\u00a0', $apiResponse);
}
return $apiResponse;
}
private function removeSubtableIdsFromXml($apiResponse)
{
return $this->removeXmlFields($apiResponse, array('idsubdatatable_in_db'));
}
/**
* To allow tests to pass no matter what port Piwik is on, we replace the test URL w/ another
* one in the response. We don't remove the URL outright, because then we would not be able
* to detect regressions where the root URL went missing.
*
* @param $apiResponse
* @return mixed
* @throws Exception
*/
private function replacePiwikUrl($apiResponse)
{
$rootUrl = Fixture::getRootUrl();
$rootUrlRel = str_replace(array('http://', 'https://'), '//', $rootUrl);
$apiResponse = str_replace($rootUrl, "http://example.com/piwik/", $apiResponse);
$apiResponse = str_replace($rootUrlRel, "//example.com/piwik/", $apiResponse);
return $apiResponse;
}
}
|