REST.php
40.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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
<?php
namespace Codeception\Module;
use Codeception\Exception\ModuleException;
use Codeception\Lib\Interfaces\ConflictsWithModule;
use Codeception\Module as CodeceptionModule;
use Codeception\PHPUnit\Constraint\JsonContains;
use Codeception\PHPUnit\Constraint\JsonType as JsonTypeConstraint;
use Codeception\TestInterface;
use Codeception\Lib\Interfaces\API;
use Codeception\Lib\Framework;
use Codeception\Lib\InnerBrowser;
use Codeception\Lib\Interfaces\DependsOnModule;
use Codeception\Lib\Interfaces\PartedModule;
use Codeception\Util\JsonArray;
use Codeception\Util\JsonType;
use Codeception\Util\XmlStructure;
use Codeception\Util\Soap as XmlUtils;
/**
* Module for testing REST WebService.
*
* This module can be used either with frameworks or PHPBrowser.
* If a framework module is connected, the testing will occur in the application directly.
* Otherwise, a PHPBrowser should be specified as a dependency to send requests and receive responses from a server.
*
* ## Configuration
*
* * url *optional* - the url of api
*
* This module requires PHPBrowser or any of Framework modules enabled.
*
* ### Example
*
* modules:
* enabled:
* - REST:
* depends: PhpBrowser
* url: 'http://serviceapp/api/v1/'
*
* ## Public Properties
*
* * headers - array of headers going to be sent.
* * params - array of sent data
* * response - last response (string)
*
* ## Parts
*
* * Json - actions for validating Json responses (no Xml responses)
* * Xml - actions for validating XML responses (no Json responses)
*
* ## Conflicts
*
* Conflicts with SOAP module
*
*/
class REST extends CodeceptionModule implements DependsOnModule, PartedModule, API, ConflictsWithModule
{
protected $config = [
'url' => ''
];
protected $dependencyMessage = <<<EOF
Example configuring PhpBrowser as backend for REST module.
--
modules:
enabled:
- REST:
depends: PhpBrowser
url: http://localhost/api/
--
Framework modules can be used for testing of API as well.
EOF;
/**
* @var \Symfony\Component\HttpKernel\Client|\Symfony\Component\BrowserKit\Client
*/
public $client = null;
public $isFunctional = false;
/**
* @var InnerBrowser
*/
protected $connectionModule;
public $params = [];
public $response = "";
public function _before(TestInterface $test)
{
$this->client = &$this->connectionModule->client;
$this->resetVariables();
}
protected function resetVariables()
{
$this->params = [];
$this->response = "";
$this->connectionModule->headers = [];
}
public function _conflicts()
{
return 'Codeception\Lib\Interfaces\API';
}
public function _depends()
{
return ['Codeception\Lib\InnerBrowser' => $this->dependencyMessage];
}
public function _parts()
{
return ['xml', 'json'];
}
public function _inject(InnerBrowser $connection)
{
$this->connectionModule = $connection;
if ($this->connectionModule instanceof Framework) {
$this->isFunctional = true;
}
if ($this->connectionModule instanceof PhpBrowser) {
if (!$this->connectionModule->_getConfig('url')) {
$this->connectionModule->_setConfig(['url' => $this->config['url']]);
}
}
}
protected function getRunningClient()
{
if ($this->client->getInternalRequest() === null) {
throw new ModuleException($this, "Response is empty. Use `\$I->sendXXX()` methods to send HTTP request");
}
return $this->client;
}
/**
* Sets HTTP header valid for all next requests. Use `deleteHeader` to unset it
*
* ```php
* <?php
* $I->haveHttpHeader('Content-Type', 'application/json');
* // all next requests will contain this header
* ?>
* ```
*
* @param $name
* @param $value
* @part json
* @part xml
*/
public function haveHttpHeader($name, $value)
{
$this->connectionModule->haveHttpHeader($name, $value);
}
/**
* Deletes the header with the passed name. Subsequent requests
* will not have the deleted header in its request.
*
* Example:
* ```php
* <?php
* $I->haveHttpHeader('X-Requested-With', 'Codeception');
* $I->sendGET('test-headers.php');
* // ...
* $I->deleteHeader('X-Requested-With');
* $I->sendPOST('some-other-page.php');
* ?>
* ```
*
* @param string $name the name of the header to delete.
* @part json
* @part xml
*/
public function deleteHeader($name)
{
$this->connectionModule->deleteHeader($name);
}
/**
* Checks over the given HTTP header and (optionally)
* its value, asserting that are there
*
* @param $name
* @param $value
* @part json
* @part xml
*/
public function seeHttpHeader($name, $value = null)
{
if ($value !== null) {
$this->assertEquals(
$value,
$this->getRunningClient()->getInternalResponse()->getHeader($name)
);
return;
}
$this->assertNotNull($this->getRunningClient()->getInternalResponse()->getHeader($name));
}
/**
* Checks over the given HTTP header and (optionally)
* its value, asserting that are not there
*
* @param $name
* @param $value
* @part json
* @part xml
*/
public function dontSeeHttpHeader($name, $value = null)
{
if ($value !== null) {
$this->assertNotEquals(
$value,
$this->getRunningClient()->getInternalResponse()->getHeader($name)
);
return;
}
$this->assertNull($this->getRunningClient()->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
* @part json
* @part xml
*/
public function seeHttpHeaderOnce($name)
{
$headers = $this->getRunningClient()->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
* @part json
* @part xml
*/
public function grabHttpHeader($name, $first = true)
{
return $this->getRunningClient()->getInternalResponse()->getHeader($name, $first);
}
/**
* Adds HTTP authentication via username/password.
*
* @param $username
* @param $password
* @part json
* @part xml
*/
public function amHttpAuthenticated($username, $password)
{
if ($this->isFunctional) {
$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
* @part json
* @part xml
*/
public function amDigestAuthenticated($username, $password)
{
$this->client->setAuth($username, $password, 'digest');
}
/**
* Adds Bearer authentication via access token.
*
* @param $accessToken
* @part json
* @part xml
*/
public function amBearerAuthenticated($accessToken)
{
$this->haveHttpHeader('Authorization', 'Bearer ' . $accessToken);
}
/**
* Sends a POST request to given uri. Parameters and files can be provided separately.
*
* Example:
* ```php
* <?php
* //simple POST call
* $I->sendPOST('/message', ['subject' => 'Read this!', 'to' => 'johndoe@example.com']);
* //simple upload method
* $I->sendPOST('/message/24', ['inline' => 0], ['attachmentFile' => codecept_data_dir('sample_file.pdf')]);
* //uploading a file with a custom name and mime-type. This is also useful to simulate upload errors.
* $I->sendPOST('/message/24', ['inline' => 0], [
* 'attachmentFile' => [
* 'name' => 'document.pdf',
* 'type' => 'application/pdf',
* 'error' => UPLOAD_ERR_OK,
* 'size' => filesize(codecept_data_dir('sample_file.pdf')),
* 'tmp_name' => codecept_data_dir('sample_file.pdf')
* ]
* ]);
* ```
*
* @param $url
* @param array|\JsonSerializable $params
* @param array $files A list of filenames or "mocks" of $_FILES (each entry being an array with the following
* keys: name, type, error, size, tmp_name (pointing to the real file path). Each key works
* as the "name" attribute of a file input field.
*
* @see http://php.net/manual/en/features.file-upload.post-method.php
* @see codecept_data_dir()
* @part json
* @part xml
*/
public function sendPOST($url, $params = [], $files = [])
{
$this->execute('POST', $url, $params, $files);
}
/**
* Sends a HEAD request to given uri.
*
* @param $url
* @param array $params
* @part json
* @part xml
*/
public function sendHEAD($url, $params = [])
{
$this->execute('HEAD', $url, $params);
}
/**
* Sends an OPTIONS request to given uri.
*
* @param $url
* @param array $params
* @part json
* @part xml
*/
public function sendOPTIONS($url, $params = [])
{
$this->execute('OPTIONS', $url, $params);
}
/**
* Sends a GET request to given uri.
*
* @param $url
* @param array $params
* @part json
* @part xml
*/
public function sendGET($url, $params = [])
{
$this->execute('GET', $url, $params);
}
/**
* Sends PUT request to given uri.
*
* @param $url
* @param array $params
* @param array $files
* @part json
* @part xml
*/
public function sendPUT($url, $params = [], $files = [])
{
$this->execute('PUT', $url, $params, $files);
}
/**
* Sends PATCH request to given uri.
*
* @param $url
* @param array $params
* @param array $files
* @part json
* @part xml
*/
public function sendPATCH($url, $params = [], $files = [])
{
$this->execute('PATCH', $url, $params, $files);
}
/**
* Sends DELETE request to given uri.
*
* @param $url
* @param array $params
* @param array $files
* @part json
* @part xml
*/
public function sendDELETE($url, $params = [], $files = [])
{
$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 = [];
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->haveHttpHeader('Link', implode(', ', $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
* @part json
* @part xml
*/
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
* @part json
* @part xml
*/
public function sendUNLINK($url, array $linkEntries)
{
$this->setHeaderLink($linkEntries);
$this->execute('UNLINK', $url);
}
protected function execute($method, $url, $parameters = [], $files = [])
{
// allow full url to be requested
if (strpos($url, '://') === false) {
$url = $this->config['url'] . $url;
}
$this->params = $parameters;
$parameters = $this->encodeApplicationJson($method, $parameters);
if (is_array($parameters) || $method === 'GET') {
if (!empty($parameters) && $method === 'GET') {
if (strpos($url, '?') !== false) {
$url .= '&';
} else {
$url .= '?';
}
$url .= http_build_query($parameters);
}
if ($method == 'GET') {
$this->debugSection("Request", "$method $url");
$files = [];
} else {
$this->debugSection("Request", "$method $url " . json_encode($parameters));
$files = $this->formatFilesArray($files);
}
$this->response = (string)$this->connectionModule->_request($method, $url, $parameters, $files);
} else {
$requestData = $parameters;
if ($this->isBinaryData($requestData)) {
$requestData = $this->binaryToDebugString($requestData);
}
$this->debugSection("Request", "$method $url " . $requestData);
$this->response = (string)$this->connectionModule->_request($method, $url, [], $files, [], $parameters);
}
$printedResponse = $this->response;
if ($this->isBinaryData($printedResponse)) {
$printedResponse = $this->binaryToDebugString($printedResponse);
}
$this->debugSection("Response", $printedResponse);
}
/**
* Check if data has non-printable bytes and it is not a valid unicode string
*
* @param string $data the text or binary data string
* @return boolean
*/
protected function isBinaryData($data)
{
return !ctype_print($data) && false === mb_detect_encoding($data, mb_detect_order(), true);
}
/**
* Format a binary string for debug printing
*
* @param string $data the binary data string
* @return string the debug string
*/
protected function binaryToDebugString($data)
{
return '[binary-data length:' . strlen($data) . ' md5:' . md5($data) . ']';
}
protected function encodeApplicationJson($method, $parameters)
{
if ($method !== 'GET' && array_key_exists('Content-Type', $this->connectionModule->headers)
&& ($this->connectionModule->headers['Content-Type'] === 'application/json'
|| preg_match('!^application/.+\+json$!', $this->connectionModule->headers['Content-Type'])
)
) {
if ($parameters instanceof \JsonSerializable) {
return json_encode($parameters);
}
if (is_array($parameters) || $parameters instanceof \ArrayAccess) {
$parameters = $this->scalarizeArray($parameters);
return json_encode($parameters);
}
}
return $parameters;
}
private function formatFilesArray(array $files)
{
foreach ($files as $name => $value) {
if (is_string($value)) {
$this->checkFileBeforeUpload($value);
$files[$name] = [
'name' => basename($value),
'tmp_name' => $value,
'size' => filesize($value),
'type' => $this->getFileType($value),
'error' => 0,
];
continue;
} elseif (is_array($value)) {
if (isset($value['tmp_name'])) {
$this->checkFileBeforeUpload($value['tmp_name']);
if (!isset($value['name'])) {
$value['name'] = basename($value);
}
if (!isset($value['size'])) {
$value['size'] = filesize($value);
}
if (!isset($value['type'])) {
$value['type'] = $this->getFileType($value);
}
if (!isset($value['error'])) {
$value['error'] = 0;
}
} else {
$files[$name] = $this->formatFilesArray($value);
}
} elseif (is_object($value)) {
/**
* do nothing, probably the user knows what he is doing
* @issue https://github.com/Codeception/Codeception/issues/3298
*/
} else {
throw new ModuleException(__CLASS__, "Invalid value of key $name in files array");
}
}
return $files;
}
private function getFileType($file)
{
if (function_exists('mime_content_type') && mime_content_type($file)) {
return mime_content_type($file);
}
return 'application/octet-stream';
}
private function checkFileBeforeUpload($file)
{
if (!file_exists($file)) {
throw new ModuleException(__CLASS__, "File $file does not exist");
}
if (!is_readable($file)) {
throw new ModuleException(__CLASS__, "File $file is not readable");
}
if (!is_file($file)) {
throw new ModuleException(__CLASS__, "File $file is not a regular file");
}
}
/**
* Checks whether last response was valid JSON.
* This is done with json_last_error function.
*
* @part json
*/
public function seeResponseIsJson()
{
$responseContent = $this->connectionModule->_getResponseContent();
\PHPUnit_Framework_Assert::assertNotEquals('', $responseContent, 'response is empty');
json_decode($responseContent);
$errorCode = json_last_error();
$errorMessage = json_last_error_msg();
\PHPUnit_Framework_Assert::assertEquals(
JSON_ERROR_NONE,
$errorCode,
sprintf(
"Invalid json: %s. System message: %s.",
$responseContent,
$errorMessage
)
);
}
/**
* Checks whether the last response contains text.
*
* @param $text
* @part json
* @part xml
*/
public function seeResponseContains($text)
{
$this->assertContains($text, $this->connectionModule->_getResponseContent(), "REST response contains");
}
/**
* Checks whether last response do not contain text.
*
* @param $text
* @part json
* @part xml
*/
public function dontSeeResponseContains($text)
{
$this->assertNotContains($text, $this->connectionModule->_getResponseContent(), "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
* @part json
*/
public function seeResponseContainsJson($json = [])
{
\PHPUnit_Framework_Assert::assertThat(
$this->connectionModule->_getResponseContent(),
new JsonContains($json)
);
}
/**
* 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
* @part json
* @part xml
*/
public function grabResponse()
{
return $this->connectionModule->_getResponseContent();
}
/**
* Returns data from the current JSON response using [JSONPath](http://goessner.net/articles/JsonPath/) as selector.
* JsonPath is XPath equivalent for querying Json structures.
* Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
* Even for a single value an array is returned.
*
* This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
*
* Example:
*
* ``` php
* <?php
* // match the first `user.id` in json
* $firstUserId = $I->grabDataFromResponseByJsonPath('$..users[0].id');
* $I->sendPUT('/user', array('id' => $firstUserId[0], 'name' => 'davert'));
* ?>
* ```
*
* @param string $jsonPath
* @return array Array of matching items
* @version 2.0.9
* @throws \Exception
* @part json
*/
public function grabDataFromResponseByJsonPath($jsonPath)
{
return (new JsonArray($this->connectionModule->_getResponseContent()))->filterByJsonPath($jsonPath);
}
/**
* Checks if json structure in response matches the xpath provided.
* JSON is not supposed to be checked against XPath, yet it can be converted to xml and used with XPath.
* This assertion allows you to check the structure of response json.
* *
* ```json
* { "store": {
* "book": [
* { "category": "reference",
* "author": "Nigel Rees",
* "title": "Sayings of the Century",
* "price": 8.95
* },
* { "category": "fiction",
* "author": "Evelyn Waugh",
* "title": "Sword of Honour",
* "price": 12.99
* }
* ],
* "bicycle": {
* "color": "red",
* "price": 19.95
* }
* }
* }
* ```
*
* ```php
* <?php
* // at least one book in store has author
* $I->seeResponseJsonMatchesXpath('//store/book/author');
* // first book in store has author
* $I->seeResponseJsonMatchesXpath('//store/book[1]/author');
* // at least one item in store has price
* $I->seeResponseJsonMatchesXpath('/store//price');
* ?>
* ```
* @param string $xpath
* @part json
* @version 2.0.9
*/
public function seeResponseJsonMatchesXpath($xpath)
{
$response = $this->connectionModule->_getResponseContent();
$this->assertGreaterThan(
0,
(new JsonArray($response))->filterByXPath($xpath)->length,
"Received JSON did not match the XPath `$xpath`.\nJson Response: \n" . $response
);
}
/**
* Opposite to seeResponseJsonMatchesXpath
*
* @param string $xpath
* @part json
*/
public function dontSeeResponseJsonMatchesXpath($xpath)
{
$response = $this->connectionModule->_getResponseContent();
$this->assertEquals(
0,
(new JsonArray($response))->filterByXPath($xpath)->length,
"Received JSON matched the XPath `$xpath`.\nJson Response: \n" . $response
);
}
/**
* Checks if json structure in response matches [JsonPath](http://goessner.net/articles/JsonPath/).
* JsonPath is XPath equivalent for querying Json structures.
* Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
* This assertion allows you to check the structure of response json.
*
* This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
*
* ```json
* { "store": {
* "book": [
* { "category": "reference",
* "author": "Nigel Rees",
* "title": "Sayings of the Century",
* "price": 8.95
* },
* { "category": "fiction",
* "author": "Evelyn Waugh",
* "title": "Sword of Honour",
* "price": 12.99
* }
* ],
* "bicycle": {
* "color": "red",
* "price": 19.95
* }
* }
* }
* ```
*
* ```php
* <?php
* // at least one book in store has author
* $I->seeResponseJsonMatchesJsonPath('$.store.book[*].author');
* // first book in store has author
* $I->seeResponseJsonMatchesJsonPath('$.store.book[0].author');
* // at least one item in store has price
* $I->seeResponseJsonMatchesJsonPath('$.store..price');
* ?>
* ```
*
* @param string $jsonPath
* @part json
* @version 2.0.9
*/
public function seeResponseJsonMatchesJsonPath($jsonPath)
{
$response = $this->connectionModule->_getResponseContent();
$this->assertNotEmpty(
(new JsonArray($response))->filterByJsonPath($jsonPath),
"Received JSON did not match the JsonPath `$jsonPath`.\nJson Response: \n" . $response
);
}
/**
* Opposite to seeResponseJsonMatchesJsonPath
*
* @param string $jsonPath
* @part json
*/
public function dontSeeResponseJsonMatchesJsonPath($jsonPath)
{
$response = $this->connectionModule->_getResponseContent();
$this->assertEmpty(
(new JsonArray($response))->filterByJsonPath($jsonPath),
"Received JSON matched the JsonPath `$jsonPath`.\nJson Response: \n" . $response
);
}
/**
* Opposite to seeResponseContainsJson
*
* @part json
* @param array $json
*/
public function dontSeeResponseContainsJson($json = [])
{
$jsonResponseArray = new JsonArray($this->connectionModule->_getResponseContent());
$this->assertFalse(
$jsonResponseArray->containsArray($json),
"Response JSON contains provided JSON\n"
. "- <info>" . var_export($json, true) . "</info>\n"
. "+ " . var_export($jsonResponseArray->toArray(), true)
);
}
/**
* Checks that Json matches provided types.
* In case you don't know the actual values of JSON data returned you can match them by type.
* Starts check with a root element. If JSON data is array it will check the first element of an array.
* You can specify the path in the json which should be checked with JsonPath
*
* Basic example:
*
* ```php
* <?php
* // {'user_id': 1, 'name': 'davert', 'is_active': false}
* $I->seeResponseMatchesJsonType([
* 'user_id' => 'integer',
* 'name' => 'string|null',
* 'is_active' => 'boolean'
* ]);
*
* // narrow down matching with JsonPath:
* // {"users": [{ "name": "davert"}, {"id": 1}]}
* $I->seeResponseMatchesJsonType(['name' => 'string'], '$.users[0]');
* ?>
* ```
*
* In this case you can match that record contains fields with data types you expected.
* The list of possible data types:
*
* * string
* * integer
* * float
* * array (json object is array as well)
* * boolean
*
* You can also use nested data type structures:
*
* ```php
* <?php
* // {'user_id': 1, 'name': 'davert', 'company': {'name': 'Codegyre'}}
* $I->seeResponseMatchesJsonType([
* 'user_id' => 'integer|string', // multiple types
* 'company' => ['name' => 'string']
* ]);
* ?>
* ```
*
* You can also apply filters to check values. Filter can be applied with `:` char after the type declatation.
*
* Here is the list of possible filters:
*
* * `integer:>{val}` - checks that integer is greater than {val} (works with float and string types too).
* * `integer:<{val}` - checks that integer is lower than {val} (works with float and string types too).
* * `string:url` - checks that value is valid url.
* * `string:date` - checks that value is date in JavaScript format: https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
* * `string:email` - checks that value is a valid email according to http://emailregex.com/
* * `string:regex({val})` - checks that string matches a regex provided with {val}
*
* This is how filters can be used:
*
* ```php
* <?php
* // {'user_id': 1, 'email' => 'davert@codeception.com'}
* $I->seeResponseMatchesJsonType([
* 'user_id' => 'string:>0:<1000', // multiple filters can be used
* 'email' => 'string:regex(~\@~)' // we just check that @ char is included
* ]);
*
* // {'user_id': '1'}
* $I->seeResponseMatchesJsonType([
* 'user_id' => 'string:>0', // works with strings as well
* }
* ?>
* ```
*
* You can also add custom filters y accessing `JsonType::addCustomFilter` method.
* See [JsonType reference](http://codeception.com/docs/reference/JsonType).
*
* @part json
* @version 2.1.3
* @param array $jsonType
* @param string $jsonPath
*/
public function seeResponseMatchesJsonType(array $jsonType, $jsonPath = null)
{
$jsonArray = new JsonArray($this->connectionModule->_getResponseContent());
if ($jsonPath) {
$jsonArray = $jsonArray->filterByJsonPath($jsonPath);
}
\PHPUnit_Framework_Assert::assertThat($jsonArray, new JsonTypeConstraint($jsonType));
}
/**
* Opposite to `seeResponseMatchesJsonType`.
*
* @part json
* @see seeResponseMatchesJsonType
* @param $jsonType jsonType structure
* @param null $jsonPath optionally set specific path to structure with JsonPath
* @version 2.1.3
*/
public function dontSeeResponseMatchesJsonType($jsonType, $jsonPath = null)
{
$jsonArray = new JsonArray($this->connectionModule->_getResponseContent());
if ($jsonPath) {
$jsonArray = $jsonArray->filterByJsonPath($jsonPath);
}
\PHPUnit_Framework_Assert::assertThat($jsonArray, new JsonTypeConstraint($jsonType, false));
}
/**
* Checks if response is exactly the same as provided.
*
* @part json
* @part xml
* @param $response
*/
public function seeResponseEquals($expected)
{
$this->assertEquals($expected, $this->connectionModule->_getResponseContent());
}
/**
* Checks response code equals to provided value.
*
* ```php
* <?php
* $I->seeResponseCodeIs(200);
*
* // preferred to use \Codeception\Util\HttpCode
* $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
* ```
*
* @part json
* @part xml
* @param $code
*/
public function seeResponseCodeIs($code)
{
$this->connectionModule->seeResponseCodeIs($code);
}
/**
* Checks that response code is not equal to provided value.
*
* ```php
* <?php
* $I->dontSeeResponseCodeIs(200);
*
* // preferred to use \Codeception\Util\HttpCode
* $I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
* ```
*
* @part json
* @part xml
* @param $code
*/
public function dontSeeResponseCodeIs($code)
{
$this->connectionModule->dontSeeResponseCodeIs($code);
}
/**
* Checks whether last response was valid XML.
* This is done with libxml_get_last_error function.
*
* @part xml
*/
public function seeResponseIsXml()
{
libxml_use_internal_errors(true);
$doc = simplexml_load_string($this->connectionModule->_getResponseContent());
$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 wheather XML response matches XPath
*
* ```php
* <?php
* $I->seeXmlResponseMatchesXpath('//root/user[@id=1]');
* ```
* @part xml
* @param $xpath
*/
public function seeXmlResponseMatchesXpath($xpath)
{
$structure = new XmlStructure($this->connectionModule->_getResponseContent());
$this->assertTrue($structure->matchesXpath($xpath), 'xpath not matched');
}
/**
* Checks wheather XML response does not match XPath
*
* ```php
* <?php
* $I->dontSeeXmlResponseMatchesXpath('//root/user[@id=1]');
* ```
* @part xml
* @param $xpath
*/
public function dontSeeXmlResponseMatchesXpath($xpath)
{
$structure = new XmlStructure($this->connectionModule->_getResponseContent());
$this->assertFalse($structure->matchesXpath($xpath), 'accidentally matched xpath');
}
/**
* Finds and returns text contents of element.
* Element is matched by either CSS or XPath
*
* @param $cssOrXPath
* @return string
* @part xml
*/
public function grabTextContentFromXmlElement($cssOrXPath)
{
$el = (new XmlStructure($this->connectionModule->_getResponseContent()))->matchElement($cssOrXPath);
return $el->textContent;
}
/**
* Finds and returns attribute of element.
* Element is matched by either CSS or XPath
*
* @param $cssOrXPath
* @param $attribute
* @return string
* @part xml
*/
public function grabAttributeFromXmlElement($cssOrXPath, $attribute)
{
$el = (new XmlStructure($this->connectionModule->_getResponseContent()))->matchElement($cssOrXPath);
if (!$el->hasAttribute($attribute)) {
$this->fail("Attribute not found in element matched by '$cssOrXPath'");
}
return $el->getAttribute($attribute);
}
/**
* Checks XML response equals provided XML.
* Comparison is done by canonicalizing both xml`s.
*
* Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
*
* @param $xml
* @part xml
*/
public function seeXmlResponseEquals($xml)
{
\PHPUnit_Framework_Assert::assertXmlStringEqualsXmlString($this->connectionModule->_getResponseContent(), $xml);
}
/**
* Checks XML response does not equal to provided XML.
* Comparison is done by canonicalizing both xml`s.
*
* Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
*
* @param $xml
* @part xml
*/
public function dontSeeXmlResponseEquals($xml)
{
\PHPUnit_Framework_Assert::assertXmlStringNotEqualsXmlString(
$this->connectionModule->_getResponseContent(),
$xml
);
}
/**
* Checks XML response includes provided XML.
* Comparison is done by canonicalizing both xml`s.
* Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
*
* Example:
*
* ``` php
* <?php
* $I->seeXmlResponseIncludes("<result>1</result>");
* ?>
* ```
*
* @param $xml
* @part xml
*/
public function seeXmlResponseIncludes($xml)
{
$this->assertContains(
XmlUtils::toXml($xml)->C14N(),
XmlUtils::toXml($this->connectionModule->_getResponseContent())->C14N(),
"found in XML Response"
);
}
/**
* Checks XML response does not include provided XML.
* Comparison is done by canonicalizing both xml`s.
* Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
*
* @param $xml
* @part xml
*/
public function dontSeeXmlResponseIncludes($xml)
{
$this->assertNotContains(
XmlUtils::toXml($xml)->C14N(),
XmlUtils::toXml($this->connectionModule->_getResponseContent())->C14N(),
"found in XML Response"
);
}
/**
* Checks if the hash of a binary response is exactly the same as provided.
* Parameter can be passed as any hash string supported by hash(), with an
* optional second parameter to specify the hash type, which defaults to md5.
*
* Example: Using md5 hash key
*
* ```php
* <?php
* $I->seeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
* ?>
* ```
*
* Example: Using md5 for a file contents
*
* ```php
* <?php
* $fileData = file_get_contents("test_file.jpg");
* $I->seeBinaryResponseEquals(md5($fileData));
* ?>
* ```
* Example: Using sha256 hsah
*
* ```php
* <?php
* $fileData = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; // very small jpeg
* $I->seeBinaryResponseEquals(hash("sha256", base64_decode($fileData)), 'sha256');
* ?>
* ```
*
* @param $hash the hashed data response expected
* @param $algo the hash algorithm to use. Default md5.
* @part json
* @part xml
*/
public function seeBinaryResponseEquals($hash, $algo = 'md5')
{
$responseHash = hash($algo, $this->connectionModule->_getResponseContent());
$this->assertEquals($hash, $responseHash);
}
/**
* Checks if the hash of a binary response is not the same as provided.
*
* ```php
* <?php
* $I->dontSeeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
* ?>
* ```
* Opposite to `seeBinaryResponseEquals`
*
* @param $hash the hashed data response expected
* @param $algo the hash algorithm to use. Default md5.
* @part json
* @part xml
*/
public function dontSeeBinaryResponseEquals($hash, $algo = 'md5')
{
$responseHash = hash($algo, $this->connectionModule->_getResponseContent());
$this->assertNotEquals($hash, $responseHash);
}
/**
* Deprecated since 2.0.9 and removed since 2.1.0
*
* @param $path
* @throws ModuleException
* @deprecated
*/
public function grabDataFromJsonResponse($path)
{
throw new ModuleException(
$this,
"This action was deprecated in Codeception 2.0.9 and removed in 2.1. "
. "Please use `grabDataFromResponseByJsonPath` instead"
);
}
/**
* Prevents automatic redirects to be followed by the client
*
* ```php
* <?php
* $I->stopFollowingRedirects();
* ```
*
* @part xml
* @part json
*/
public function stopFollowingRedirects()
{
$this->client->followRedirects(false);
}
/**
* Enables automatic redirects to be followed by the client
*
* ```php
* <?php
* $I->startFollowingRedirects();
* ```
*
* @part xml
* @part json
*/
public function startFollowingRedirects()
{
$this->client->followRedirects(true);
}
}