Repository navigation
Expand file tree
/
Copy pathREST.php
More file actions
669 lines (611 loc) · 19.3 KB
/
Copy pathREST.php
File metadata and controls
669 lines (611 loc) · 19.3 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
<?php
namespace Codeception\Module;
use Symfony\Component\BrowserKit\Cookie;
use Codeception\Exception\ModuleConfig as ModuleConfigException;
/**
* Module for testing REST WebService.
*
* This module can be used either with frameworks or PHPBrowser.
* It tries to guess the framework is is attached to.
*
* Whether framework is used it operates via standard framework modules.
* Otherwise sends raw HTTP requests to url via PHPBrowser.
*
* ## Status
*
* * Maintainer: **tiger-seo**, **davert**
* * Stability: **stable**
* * Contact: codecept@davert.mail.ua
* * Contact: tiger.seo@gmail.com
*
* ## Configuration
*
* * url *optional* - the url of api
* * timeout *optional* - the maximum number of seconds to allow cURL functions to execute
*
* ### Example
*
* modules:
* enabled: [REST]
* config:
* REST:
* url: 'http://serviceapp/api/v1/'
* timeout: 90
*
* ## Public Properties
*
* * headers - array of headers going to be sent.
* * params - array of sent data
* * response - last response (string)
*
*
*/
class REST extends \Codeception\Module
{
protected $config = array(
'url' => '',
'timeout' => 30,
'xdebug_remote' => false
);
/**
* @var \Symfony\Component\HttpKernel\Client|\Symfony\Component\BrowserKit\Client|\Behat\Mink\Driver\Goutte\Client
*/
public $client = null;
public $is_functional = false;
public $headers = array();
public $params = array();
public $response = "";
public function _before(\Codeception\TestCase $test)
{
if (!$this->client) {
if (!strpos($this->config['url'], '://')) {
// not valid url
foreach ($this->getModules() as $module) {
if ($module instanceof \Codeception\Lib\Framework) {
$this->client = $module->client;
$this->is_functional = true;
break;
}
}
} else {
if (!$this->hasModule('PhpBrowser')) {
throw new ModuleConfigException(__CLASS__, "For REST testing via HTTP please enable PhpBrowser module");
}
$this->client = $this->getModule('PhpBrowser')->client;
}
if (!$this->client) {
throw new ModuleConfigException(__CLASS__, "Client for REST requests not initialized.\nProvide either PhpBrowser module, or a framework module which shares FrameworkInterface");
}
}
$this->headers = array();
$this->params = array();
$this->response = "";
$this->client->setServerParameters(array());
$timeout = $this->config['timeout'];
if ($this->config['xdebug_remote']
&& function_exists('xdebug_is_enabled')
&& xdebug_is_enabled()
&& ini_get('xdebug.remote_enable')
) {
$cookie = new Cookie('XDEBUG_SESSION', $this->config['xdebug_remote'], null, '/');
$this->client->getCookieJar()->set($cookie);
// timeout is disabled, so we can debug gently :)
$timeout = 0;
}
if (method_exists($this->client, 'getClient')) {
$clientConfig = $this->client->getClient()->getConfig();
$curlOptions = $clientConfig->get('curl.options');
$curlOptions[CURLOPT_TIMEOUT] = $timeout;
$clientConfig->set('curl.options', $curlOptions);
}
}
/**
* Sets HTTP header
*
* @param $name
* @param $value
*/
public function haveHttpHeader($name, $value)
{
$this->headers[$name] = $value;
}
/**
* Checks over the given HTTP header and (optionally)
* its value, asserting that are there
*
* @param $name
* @param $value
*/
public function seeHttpHeader($name, $value = null)
{
if ($value) {
\PHPUnit_Framework_Assert::assertEquals(
$this->client->getInternalResponse()->getHeader($name),
$value
);
}
else {
\PHPUnit_Framework_Assert::assertNotNull($this->client->getInternalResponse()->getHeader($name));
}
}
/**
* Checks over the given HTTP header and (optionally)
* its value, asserting that are not there
*
* @param $name
* @param $value
*/
public function dontSeeHttpHeader($name, $value = null) {
if ($value) {
\PHPUnit_Framework_Assert::assertNotEquals(
$this->client->getInternalResponse()->getHeader($name),
$value
);
}
else {
\PHPUnit_Framework_Assert::assertNull($this->client->getInternalResponse()->getHeader($name));
}
}
/**
* Checks that http response header is received only once.
* HTTP RFC2616 allows multiple response headers with the same name.
* You can check that you didn't accidentally sent the same header twice.
*
* ``` php
* <?php
* $I->seeHttpHeaderOnce('Cache-Control');
* ?>>
* ```
*
* @param $name
*/
public function seeHttpHeaderOnce($name)
{
$headers = $this->client->getInternalResponse()->getHeader($name, false);
$this->assertEquals(1, count($headers));
}
/**
* Returns the value of the specified header name
*
* @param $name
* @param Boolean $first Whether to return the first value or all header values
*
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function grabHttpHeader($name, $first = true) {
return $this->client->getInternalResponse()->getHeader($name, $first);
}
/**
* Adds HTTP authentication via username/password.
*
* @param $username
* @param $password
*/
public function amHttpAuthenticated($username, $password)
{
if ($this->is_functional) {
$this->client->setServerParameter('PHP_AUTH_USER', $username);
$this->client->setServerParameter('PHP_AUTH_PW', $password);
} else {
$this->client->setAuth($username, $password);
}
}
/**
* Adds Digest authentication via username/password.
*
* @param $username
* @param $password
*/
public function amDigestAuthenticated($username, $password)
{
$this->client->setAuth($username, $password, CURLAUTH_DIGEST);
}
/**
* Sends a POST request to given uri.
*
* Parameters and files (as array of filenames) can be provided.
*
* @param $url
* @param array $params
* @param array $files
*/
public function sendPOST($url, $params = array(), $files = array())
{
$this->execute('POST', $url, $params, $files);
}
/**
* Sends a HEAD request to given uri.
*
* @param $url
* @param array $params
*/
public function sendHEAD($url, $params = array())
{
$this->execute('HEAD', $url, $params);
}
/**
* Sends an OPTIONS request to given uri.
*
* @param $url
* @param array $params
*/
public function sendOPTIONS($url, $params = array())
{
$this->execute('OPTIONS', $url, $params);
}
/**
* Sends a GET request to given uri.
*
* @param $url
* @param array $params
*/
public function sendGET($url, $params = array())
{
$this->execute('GET', $url, $params);
}
/**
* Sends PUT request to given uri.
*
* @param $url
* @param array $params
* @param array $files
*/
public function sendPUT($url, $params = array(), $files = array())
{
$this->execute('PUT', $url, $params, $files);
}
/**
* Sends PATCH request to given uri.
*
* @param $url
* @param array $params
* @param array $files
*/
public function sendPATCH($url, $params = array(), $files = array())
{
$this->execute('PATCH', $url, $params, $files);
}
/**
* Sends DELETE request to given uri.
*
* @param $url
* @param array $params
* @param array $files
*/
public function sendDELETE($url, $params = array(), $files = array())
{
$this->execute('DELETE', $url, $params, $files);
}
/**
* Sets Headers "Link" as one header "Link" based on linkEntries
*
* @param array $linkEntries (entry is array with keys "uri" and "link-param")
*
* @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
*
* @author samva.ua@gmail.com
*/
private function setHeaderLink(array $linkEntries)
{
$values = array();
foreach ($linkEntries as $linkEntry) {
\PHPUnit_Framework_Assert::assertArrayHasKey(
'uri',
$linkEntry,
'linkEntry should contain property "uri"'
);
\PHPUnit_Framework_Assert::assertArrayHasKey(
'link-param',
$linkEntry,
'linkEntry should contain property "link-param"'
);
$values[] = $linkEntry['uri'] . '; ' . $linkEntry['link-param'];
}
$this->headers['Link'] = join(', ', $values);
}
/**
* Sends LINK request to given uri.
*
* @param $url
* @param array $linkEntries (entry is array with keys "uri" and "link-param")
*
* @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
*
* @author samva.ua@gmail.com
*/
public function sendLINK($url, array $linkEntries)
{
$this->setHeaderLink($linkEntries);
$this->execute('LINK', $url);
}
/**
* Sends UNLINK request to given uri.
*
* @param $url
* @param array $linkEntries (entry is array with keys "uri" and "link-param")
*
* @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
*
* @author samva.ua@gmail.com
*/
public function sendUNLINK($url, array $linkEntries)
{
$this->setHeaderLink($linkEntries);
$this->execute('UNLINK', $url);
}
protected function execute($method = 'GET', $url, $parameters = array(), $files = array())
{
foreach ($this->headers as $header => $val) {
$header = str_replace('-','_',strtoupper($header));
$this->client->setServerParameter("HTTP_$header", $val);
# Issue #827 - symfony foundation requires 'CONTENT_TYPE' without HTTP_
if ($this->is_functional and $header == 'CONTENT_TYPE') {
$this->client->setServerParameter($header, $val);
}
}
// allow full url to be requested
$url = (strpos($url, '://') === false ? $this->config['url'] : '') . $url;
$parameters = $this->encodeApplicationJson($method, $parameters);
if (is_array($parameters) || $method == 'GET') {
if (!empty($parameters) && $method == 'GET') {
$url .= '?' . http_build_query($parameters);
}
if($method == 'GET') {
$this->debugSection("Request", "$method $url");
} else {
$this->debugSection("Request", "$method $url ".json_encode($parameters));
}
$this->client->request($method, $url, $parameters, $files);
} else {
$this->debugSection("Request", "$method $url " . $parameters);
$this->client->request($method, $url, array(), $files, array(), $parameters);
}
$this->response = $this->client->getInternalResponse()->getContent();
$this->debugSection("Response", $this->response);
if (count($this->client->getInternalRequest()->getCookies())) {
$this->debugSection('Cookies', json_encode($this->client->getInternalRequest()->getCookies()));
}
$this->debugSection("Headers", json_encode($this->client->getInternalResponse()->getHeaders()));
$this->debugSection("Status", json_encode($this->client->getInternalResponse()->getStatus()));
}
protected function encodeApplicationJson($method, $parameters)
{
if (is_array($parameters) || $parameters instanceof \ArrayAccess) {
$parameters = $this->scalarizeArray($parameters);
if (array_key_exists('Content-Type', $this->headers)
&& $this->headers['Content-Type'] === 'application/json'
&& $method != 'GET'
) {
return json_encode($parameters);
}
}
return $parameters;
}
/**
* Checks whether last response was valid JSON.
* This is done with json_last_error function.
*
*/
public function seeResponseIsJson()
{
json_decode($this->response);
\PHPUnit_Framework_Assert::assertEquals(
0,
$num = json_last_error(),
"json decoding error #$num, see http://php.net/manual/en/function.json-last-error.php"
);
}
/**
* Checks whether last response was valid XML.
* This is done with libxml_get_last_error function.
*
*/
public function seeResponseIsXml()
{
libxml_use_internal_errors(true);
$doc = simplexml_load_string($this->response);
$num="";
$title="";
if ($doc===false) {
$error = libxml_get_last_error();
$num=$error->code;
$title=trim($error->message);
libxml_clear_errors();
}
libxml_use_internal_errors(false);
\PHPUnit_Framework_Assert::assertNotSame(false,
$doc ,
"xml decoding error #$num with message \"$title\", see http://www.xmlsoft.org/html/libxml-xmlerror.html"
);
}
/**
* Checks whether the last response contains text.
*
* @param $text
*/
public function seeResponseContains($text)
{
\PHPUnit_Framework_Assert::assertContains($text, $this->response, "REST response contains");
}
/**
* Checks whether last response do not contain text.
*
* @param $text
*/
public function dontSeeResponseContains($text)
{
\PHPUnit_Framework_Assert::assertNotContains($text, $this->response, "REST response contains");
}
/**
* Checks whether the last JSON response contains provided array.
* The response is converted to array with json_decode($response, true)
* Thus, JSON is represented by associative array.
* This method matches that response array contains provided array.
*
* Examples:
*
* ``` php
* <?php
* // response: {name: john, email: john@gmail.com}
* $I->seeResponseContainsJson(array('name' => 'john'));
*
* // response {user: john, profile: { email: john@gmail.com }}
* $I->seeResponseContainsJson(array('email' => 'john@gmail.com'));
*
* ?>
* ```
*
* This method recursively checks if one array can be found inside of another.
*
* @param array $json
*/
public function seeResponseContainsJson($json = array())
{
$resp_json = json_decode($this->response, true);
\PHPUnit_Framework_Assert::assertTrue(
$this->arrayHasArray($json, $resp_json),
"Response JSON contains provided\n"
."- ".print_r($json, true)
."+ ".print_r($resp_json, true)
);
}
/**
* Returns current response so that it can be used in next scenario steps.
*
* Example:
*
* ``` php
* <?php
* $user_id = $I->grabResponse();
* $I->sendPUT('/user', array('id' => $user_id, 'name' => 'davert'));
* ?>
* ```
*
* @version 1.1
* @return string
*/
public function grabResponse()
{
return $this->response;
}
/**
* Returns data from the current JSON response using specified path
* so that it can be used in next scenario steps
*
* Example:
*
* ``` php
* <?php
* $user_id = $I->grabDataFromJsonResponse('user.user_id');
* $I->sendPUT('/user', array('id' => $user_id, 'name' => 'davert'));
* ?>
* ```
*
* @param string $path
*
* @since 1.1.2
* @return string
*
* @author tiger.seo@gmail.com
*/
public function grabDataFromJsonResponse($path)
{
$data = $response = json_decode($this->response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$this->fail('Response is not of JSON format or is malformed');
$this->debugSection('Response', $this->response);
}
if ($path === '') {
return $data;
}
foreach (explode('.', $path) as $key) {
if (!is_array($data) || !array_key_exists($key, $data)) {
$this->fail('Response does not have required data');
$this->debugSection('Response', $response);
}
$data = $data[$key];
}
return $data;
}
/**
* @author nleippe@integr8ted.com
* @author tiger.seo@gmail.com
* @link http://www.php.net/manual/en/function.array-intersect-assoc.php#39822
*
* @param mixed $arr1
* @param mixed $arr2
*
* @return array|bool
*/
private function arrayIntersectAssocRecursive($arr1, $arr2)
{
if (!is_array($arr1) || !is_array($arr2)) {
return null;
}
$commonkeys = array_intersect(array_keys($arr1), array_keys($arr2));
$ret = array();
foreach ($commonkeys as $key) {
$_return = $this->arrayIntersectAssocRecursive($arr1[$key], $arr2[$key]);
if ($_return) {
$ret[$key] = $_return;
continue;
}
if ($arr1[$key] === $arr2[$key]) {
$ret[$key] = $arr1[$key];
}
}
if (empty($commonkeys)) {
foreach ($arr2 as $arr) {
$_return = $this->arrayIntersectAssocRecursive($arr1, $arr);
if ($_return && $_return == $arr1) return $_return;
}
}
return $ret;
}
protected function arrayHasArray(array $needle, array $haystack)
{
return $needle == $this->arrayIntersectAssocRecursive($needle, $haystack);
}
/**
* Opposite to seeResponseContainsJson
*
* @param array $json
*/
public function dontSeeResponseContainsJson($json = array())
{
$resp_json = json_decode($this->response, true);
\PHPUnit_Framework_Assert::assertFalse(
$this->arrayHasArray($json, $resp_json),
"Response JSON does not contain JSON provided\n"
."- ".print_r($json, true)
."+ ".print_r($resp_json, true)
);
}
/**
* Checks if response is exactly the same as provided.
*
* @param $response
*/
public function seeResponseEquals($response)
{
\PHPUnit_Framework_Assert::assertEquals($response, $this->response);
}
/**
* Checks response code equals to provided value.
*
* @param $code
*/
public function seeResponseCodeIs($code)
{
$this->assertEquals($code, $this->client->getInternalResponse()->getStatus());
}
/**
* Checks that response code is not equal to provided value.
*
* @param $code
*/
public function dontSeeResponseCodeIs($code)
{
$this->assertNotEquals($code, $this->client->getInternalResponse()->getStatus());
}
}