-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathREST.php
More file actions
1740 lines (1597 loc) · 52.8 KB
/
REST.php
File metadata and controls
1740 lines (1597 loc) · 52.8 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
<?php
declare(strict_types=1);
namespace Codeception\Module;
use ArrayAccess;
use Codeception\Exception\ConfigurationException;
use Codeception\Exception\ExternalUrlException;
use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;
use Codeception\Lib\Framework;
use Codeception\Lib\InnerBrowser;
use Codeception\Lib\Interfaces\API;
use Codeception\Lib\Interfaces\ConflictsWithModule;
use Codeception\Lib\Interfaces\DependsOnModule;
use Codeception\Lib\Interfaces\PartedModule;
use Codeception\Module;
use Codeception\PHPUnit\Constraint\JsonContains;
use Codeception\PHPUnit\Constraint\JsonType as JsonTypeConstraint;
use Codeception\TestInterface;
use Codeception\Util\JsonArray;
use Codeception\Util\JsonType;
use Codeception\Util\Soap as XmlUtils;
use Codeception\Util\XmlStructure;
use JsonException;
use JsonSchema\Constraints\Constraint as JsonConstraint;
use JsonSchema\Validator as JsonSchemaValidator;
use JsonSerializable;
use PHPUnit\Framework\Assert;
use Symfony\Component\BrowserKit\AbstractBrowser;
use Symfony\Component\HttpKernel\HttpKernelBrowser;
/**
* Module for testing REST WebService.
*
* This module requires either [PhpBrowser](https://codeception.com/docs/modules/PhpBrowser)
* or a framework module (e.g. [Symfony](https://codeception.com/docs/modules/Symfony), [Laravel](https://codeception.com/docs/modules/Laravel5))
* to send the actual HTTP request.
*
* ## Configuration
*
* * `url` *optional* - the url of api
* * `shortDebugResponse` *optional* - number of chars to limit the API response length
*
* ### Example
*
* ```yaml
* modules:
* enabled:
* - REST:
* depends: PhpBrowser
* url: 'https://example.com/api/v1/'
* shortDebugResponse: 300 # only the first 300 characters of the response
* ```
*
* In case you need to configure low-level HTTP headers, that's done on the PhpBrowser level like so:
*
* ```yaml
* modules:
* enabled:
* - REST:
* depends: PhpBrowser
* url: &url 'https://example.com/api/v1/'
* config:
* PhpBrowser:
* url: *url
* headers:
* Content-Type: application/json
* ```
*
* ## JSONPath
*
* [JSONPath](https://goessner.net/articles/JsonPath/) is the equivalent to XPath, for querying JSON data structures.
* Here's an [Online JSONPath Expressions Tester](https://jsonpath.curiousconcept.com/)
*
* ## 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 Module implements DependsOnModule, PartedModule, API, ConflictsWithModule
{
/**
* @var string[]
*/
public const QUERY_PARAMS_AWARE_METHODS = ['GET', 'HEAD', 'OPTIONS'];
/**
* @var array<string, string>
*/
protected array $config = [
'url' => '',
'aws' => ''
];
protected string $dependencyMessage = <<<EOF
Example configuring PhpBrowser as backend for REST module.
--
modules:
enabled:
- REST:
depends: PhpBrowser
url: http://localhost/api/
shortDebugResponse: 300
--
Framework modules can be used for testing of API as well.
EOF;
protected int $DEFAULT_SHORTEN_VALUE = 150;
/**
* @var HttpKernelBrowser|AbstractBrowser
*/
public $client;
public bool $isFunctional = false;
protected ?InnerBrowser $connectionModule = null;
/** @var array */
public $params = [];
public ?string $response = null;
public function _before(TestInterface $test): void
{
$this->client = &$this->connectionModule->client;
$this->resetVariables();
}
protected function resetVariables(): void
{
$this->params = [];
$this->response = '';
$this->connectionModule->headers = [];
}
public function _conflicts(): string
{
return \Codeception\Lib\Interfaces\API::class;
}
public function _depends(): array
{
return [InnerBrowser::class => $this->dependencyMessage];
}
/**
* @return string[]
*/
public function _parts(): array
{
return ['xml', 'json'];
}
public function _inject(InnerBrowser $connection)
{
$this->connectionModule = $connection;
if ($this->connectionModule instanceof Framework) {
$this->isFunctional = true;
}
if ($this->connectionModule instanceof PhpBrowser && !$this->connectionModule->_getConfig('url')) {
$this->connectionModule->_setConfig(['url' => $this->config['url']]);
}
}
public function _failed(TestInterface $test, $fail)
{
if ($this->response === null || $this->response === '' || $this->response === '0') {
return;
}
$printedResponse = $this->response;
if ($this->isBinaryData($printedResponse)) {
$printedResponse = $this->binaryToDebugString($printedResponse);
}
$test->getMetadata()->addReport('body', $printedResponse);
}
protected function getRunningClient(): AbstractBrowser
{
if ($this->client->getInternalRequest() === null) {
throw new ModuleException($this, "Response is empty. Use `\$I->sendXXX()` methods to send HTTP request");
}
return $this->client;
}
/**
* Sets a HTTP header to be used for all subsequent requests. Use [`unsetHttpHeader`](#unsetHttpHeader) to unset it.
*
* ```php
* <?php
* $I->haveHttpHeader('Content-Type', 'application/json');
* // all next requests will contain this header
* ```
*
* @part json
* @part xml
*/
public function haveHttpHeader(string $name, string $value): void
{
$this->connectionModule->haveHttpHeader($name, $value);
}
/**
* Unsets a HTTP header (that was originally added by [haveHttpHeader()](#haveHttpHeader)),
* so that subsequent requests will not send it anymore.
*
* Example:
* ```php
* <?php
* $I->haveHttpHeader('X-Requested-With', 'Codeception');
* $I->sendGet('test-headers.php');
* // ...
* $I->unsetHttpHeader('X-Requested-With');
* $I->sendPost('some-other-page.php');
* ```
*
* @param string $name the name of the header to unset.
* @part json
* @part xml
*/
public function unsetHttpHeader(string $name): void
{
$this->connectionModule->deleteHeader($name);
}
/**
* @deprecated Use [unsetHttpHeader](#unsetHttpHeader) instead
*/
public function deleteHeader(string $name): void
{
$this->unsetHttpHeader($name);
}
/**
* Checks over the given HTTP header and (optionally)
* its value, asserting that are there
*
* @param $value
* @part json
* @part xml
*/
public function seeHttpHeader(string $name, $value = null): void
{
if ($value !== null) {
$this->assertSame(
$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 $value
* @part json
* @part xml
*/
public function dontSeeHttpHeader(string $name, $value = null): void
{
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');
* ```
*
* @part json
* @part xml
*/
public function seeHttpHeaderOnce(string $name): void
{
$headers = $this->getRunningClient()->getInternalResponse()->getHeader($name, false);
$this->assertCount(1, $headers);
}
/**
* Returns the value of the specified header name
*
* @param bool $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(string $name, bool $first = true): string|array|null
{
return $this->getRunningClient()->getInternalResponse()->getHeader($name, $first);
}
/**
* Adds HTTP authentication via username/password.
*
* @part json
* @part xml
*/
public function amHttpAuthenticated(string $username, string $password): void
{
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.
*
* @part json
* @part xml
*/
public function amDigestAuthenticated(string $username, string $password): void
{
if ($this->isFunctional) {
throw new ModuleException(__METHOD__, 'Not supported by functional modules');
}
$this->client->setAuth($username, $password, 'digest');
}
/**
* Adds Bearer authentication via access token.
*
* @part json
* @part xml
*/
public function amBearerAuthenticated(string $accessToken): void
{
$this->haveHttpHeader('Authorization', 'Bearer ' . $accessToken);
}
/**
* Adds NTLM authentication via username/password.
* Requires client to be Guzzle >=6.3.0
* Out of scope for functional modules.
*
* Example:
* ```php
* <?php
* $I->amNTLMAuthenticated('jon_snow', 'targaryen');
* ```
*
* @throws \Codeception\Exception\ModuleException
* @part json
* @part xml
*/
public function amNTLMAuthenticated(string $username, string $password): void
{
if ($this->isFunctional) {
throw new ModuleException(__METHOD__, 'Not supported by functional modules');
}
if (!defined('\GuzzleHttp\Client::MAJOR_VERSION') && !defined('\GuzzleHttp\Client::VERSION')) {
throw new ModuleException(__METHOD__, 'Not supported if not using a Guzzle client');
}
$this->client->setAuth($username, $password, 'ntlm');
}
/**
* Allows to send REST request using AWS Authorization
*
* Only works with PhpBrowser
* Example Config:
* ```yml
* modules:
* enabled:
* - REST:
* aws:
* key: accessKey
* secret: accessSecret
* service: awsService
* region: awsRegion
* ```
* Code:
* ```php
* <?php
* $I->amAWSAuthenticated();
* ```
* @throws \Codeception\Exception\ConfigurationException
*/
public function amAWSAuthenticated(array $additionalAWSConfig = []): void
{
if (method_exists($this->client, 'setAwsAuth')) {
$config = array_merge($this->config['aws'], $additionalAWSConfig);
if (!isset($config['key'])) {
throw new ConfigurationException('AWS Key is not set');
}
if (!isset($config['secret'])) {
throw new ConfigurationException('AWS Secret is not set');
}
if (!isset($config['service'])) {
throw new ConfigurationException('AWS Service is not set');
}
if (!isset($config['region'])) {
throw new ConfigurationException('AWS Region is not set');
}
$this->client->setAwsAuth($config);
}
}
/**
* Sends a POST request to given uri. Parameters and files can be provided separately.
*
* Example:
* ```php
* <?php
* //simple POST call
* $response = $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')
* ]
* ]);
* // If your field names contain square brackets (e.g. `<input type="text" name="form[task]">`),
* // PHP parses them into an array. In this case you need to pass the fields like this:
* $I->sendPost('/add-task', ['form' => [
* 'task' => 'lorem ipsum',
* 'category' => 'miscellaneous',
* ]]);
* ```
*
* @param array|string|\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 https://php.net/manual/en/features.file-upload.post-method.php
* @see codecept_data_dir()
* @part json
* @part xml
*/
public function sendPost(string $url, $params = [], array $files = [])
{
return $this->execute('POST', $url, $params, $files);
}
/**
* Sends a HEAD request to given uri.
*
* @part json
* @part xml
*/
public function sendHead(string $url, array $params = [])
{
return $this->execute('HEAD', $url, $params);
}
/**
* Sends an OPTIONS request to given uri.
*
* @part json
* @part xml
*/
public function sendOptions(string $url, array $params = []): void
{
$this->execute('OPTIONS', $url, $params);
}
/**
* Sends a GET request to given uri.
*
* ```php
* <?php
* $response = $I->sendGet('/users');
*
* // send get with query params
* $I->sendGet('/orders', ['id' => 1])
* ```
*
* @part json
* @part xml
*/
public function sendGet(string $url, array $params = [])
{
return $this->execute('GET', $url, $params);
}
/**
* Sends PUT request to given uri.
*
* ```php
* <?php
* $response = $I->sendPut('/message/1', ['subject' => 'Read this!']);
* ```
*
* @param array|string|\JsonSerializable $params
* @part json
* @part xml
*/
public function sendPut(string $url, $params = [], array $files = [])
{
return $this->execute('PUT', $url, $params, $files);
}
/**
* Sends PATCH request to given uri.
*
* ```php
* <?php
* $response = $I->sendPatch('/message/1', ['subject' => 'Read this!']);
* ```
*
* @param array|string|\JsonSerializable $params
* @part json
* @part xml
*/
public function sendPatch(string $url, $params = [], array $files = [])
{
return $this->execute('PATCH', $url, $params, $files);
}
/**
* Sends DELETE request to given uri.
*
* ```php
* <?php
* $I->sendDelete('/message/1');
* ```
*
* @part json
* @part xml
*/
public function sendDelete(string $url, array $params = [], array $files = [])
{
return $this->execute('DELETE', $url, $params, $files);
}
/**
* Sends a HTTP request.
*
* @param array|string|\JsonSerializable $params
* @part json
* @part xml
*/
public function send(string $method, string $url, $params = [], array $files = [])
{
return $this->execute(strtoupper($method), $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 https://tools.ietf.org/html/rfc2068#section-19.6.2.4
*
* @author samva.ua@gmail.com
*/
private function setHeaderLink(array $linkEntries): void
{
$values = [];
foreach ($linkEntries as $linkEntry) {
Assert::assertArrayHasKey(
'uri',
$linkEntry,
'linkEntry should contain property "uri"'
);
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 array $linkEntries (entry is array with keys "uri" and "link-param")
*
* @link https://tools.ietf.org/html/rfc2068#section-19.6.2.4
*
* @author samva.ua@gmail.com
* @part json
* @part xml
*/
public function sendLink(string $url, array $linkEntries): void
{
$this->setHeaderLink($linkEntries);
$this->execute('LINK', $url);
}
/**
* Sends UNLINK request to given uri.
*
* @param array $linkEntries (entry is array with keys "uri" and "link-param")
* @link https://tools.ietf.org/html/rfc2068#section-19.6.2.4
* @author samva.ua@gmail.com
* @part json
* @part xml
*/
public function sendUnlink(string $url, array $linkEntries): void
{
$this->setHeaderLink($linkEntries);
$this->execute('UNLINK', $url);
}
/**
* @param $method
* @param $url
* @param array|string|object $parameters
* @param array $files
* @throws ModuleException|ExternalUrlException|JsonException
*/
protected function execute($method, $url, $parameters = [], $files = [])
{
// allow full url to be requested
if (!$url) {
$url = $this->config['url'];
} elseif (!is_string($url)) {
throw new ModuleException(__CLASS__, 'URL must be string');
} elseif (!str_contains($url, '://') && $this->config['url']) {
$url = rtrim($this->config['url'], '/') . '/' . ltrim($url, '/');
}
$this->params = $parameters;
$isQueryParamsAwareMethod = in_array($method, self::QUERY_PARAMS_AWARE_METHODS, true);
if ($isQueryParamsAwareMethod) {
if (!is_array($parameters)) {
throw new ModuleException(__CLASS__, $method . ' parameters must be passed in array format');
}
} else {
$parameters = $this->encodeApplicationJson($method, $parameters);
}
if (is_array($parameters) || $isQueryParamsAwareMethod) {
if ($isQueryParamsAwareMethod) {
if (!empty($parameters)) {
if (str_contains($url, '?')) {
$url .= '&';
} else {
$url .= '?';
}
$url .= http_build_query($parameters);
}
$this->debugSection("Request", sprintf('%s %s', $method, $url));
$files = [];
} else {
$this->debugSection("Request",
sprintf('%s %s ', $method, $url) . json_encode($parameters, JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR)
);
$files = $this->formatFilesArray($files);
}
$this->response = $this->connectionModule->_request($method, $url, $parameters, $files);
} else {
$requestData = $parameters;
if ($this->isBinaryData($requestData)) {
$requestData = $this->binaryToDebugString($requestData);
}
$this->debugSection("Request", sprintf('%s %s ', $method, $url) . $requestData);
$this->response = $this->connectionModule->_request($method, $url, [], $files, [], $parameters);
}
$printedResponse = $this->response;
if ($this->isBinaryData((string)$printedResponse)) {
$printedResponse = $this->binaryToDebugString($printedResponse);
}
$short = $this->_getConfig('shortDebugResponse');
if (!is_null($short)) {
$printedResponse = $this->shortenMessage($printedResponse, $short);
$this->debugSection("Shortened Response", $printedResponse);
} else {
$this->debugSection("Response", $printedResponse);
}
return $this->response;
}
/**
* Check if data has non-printable bytes and it is not a valid unicode string
*
* @param string $data the text or binary data string
*/
protected function isBinaryData(string $data): bool
{
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(string $data): string
{
return '[binary-data length:' . strlen($data) . ' md5:' . md5($data) . ']';
}
protected function encodeApplicationJson(string $method, $parameters)
{
if (
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, JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR);
}
if (is_array($parameters) || $parameters instanceof ArrayAccess) {
$parameters = $this->scalarizeArray($parameters);
return json_encode($parameters, JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR);
}
}
if ($parameters instanceof JsonSerializable) {
throw new ModuleException(__CLASS__, $method . ' parameters is JsonSerializable object, but Content-Type header is not set to application/json');
}
if (!is_string($parameters) && !is_array($parameters)) {
throw new ModuleException(__CLASS__, $method . ' parameters must be array, string or object implementing JsonSerializable interface');
}
return $parameters;
}
private function formatFilesArray(array $files): array
{
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;
}
if (is_array($value)) {
if (isset($value['tmp_name'])) {
$this->checkFileBeforeUpload($value['tmp_name']);
if (!isset($value['name'])) {
$value['name'] = basename($value['tmp_name']);
}
if (!isset($value['size'])) {
$value['size'] = filesize($value['tmp_name']);
}
if (!isset($value['type'])) {
$value['type'] = $this->getFileType($value['tmp_name']);
}
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__, sprintf('Invalid value of key %s in files array', $name));
}
}
return $files;
}
private function getFileType($file): string
{
if (function_exists('mime_content_type') && mime_content_type($file)) {
return mime_content_type($file);
}
return 'application/octet-stream';
}
private function checkFileBeforeUpload(string $file): void
{
if (!file_exists($file)) {
throw new ModuleException(__CLASS__, sprintf('File %s does not exist', $file));
}
if (!is_readable($file)) {
throw new ModuleException(__CLASS__, sprintf('File %s is not readable', $file));
}
if (!is_file($file)) {
throw new ModuleException(__CLASS__, sprintf('File %s is not a regular file', $file));
}
}
/**
* Extends the function Module::validateConfig for shorten messages
*
*/
protected function validateConfig(): void
{
parent::validateConfig();
$short = $this->_getConfig('shortDebugResponse');
if (!is_null($short) && (!is_int($short) || $short < 0)) {
throw new ModuleConfigException(__CLASS__, 'The value of "shortDebugMessage" should be integer and greater or equal "0".');
}
}
/**
* Checks whether last response was valid JSON.
* This is done with json_last_error function.
*
* @part json
*/
public function seeResponseIsJson(): void
{
$responseContent = $this->connectionModule->_getResponseContent();
Assert::assertNotEquals('', $responseContent, 'response is empty');
$this->decodeAndValidateJson($responseContent);
}
/**
* Checks whether the last response contains text.
*
* @part json
* @part xml
*/
public function seeResponseContains(string $text): void
{
$this->assertStringContainsString($text, $this->connectionModule->_getResponseContent(), 'REST response contains');
}
/**
* Checks whether last response do not contain text.
*
* @part json
* @part xml
*/
public function dontSeeResponseContains(string $text): void
{
$this->assertStringNotContainsString($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.
*
* @part json
*/
public function seeResponseContainsJson(array $json = []): void
{
Assert::assertThat(
$this->connectionModule->_getResponseContent(),
new JsonContains($json)
);
}
/**
* Checks whether last response matches the supplied json schema (https://json-schema.org/)
* Supply schema as json string.
*
* Examples:
*
* ``` php
* <?php
* // response: {"name": "john", "age": 20}
* $I->seeResponseIsValidOnJsonSchemaString('{"type": "object"}');
*
* // response {"name": "john", "age": 20}
* $schema = [
* 'properties' => [
* 'age' => [
* 'type' => 'integer',
* 'minimum' => 18
* ]
* ]
* ];
* $I->seeResponseIsValidOnJsonSchemaString(json_encode($schema));
*
* ```
*
* @part json
*/
public function seeResponseIsValidOnJsonSchemaString(string $schema): void
{
$responseContent = $this->connectionModule->_getResponseContent();
Assert::assertNotEquals('', $responseContent, 'response is empty');
$responseObject = $this->decodeAndValidateJson($responseContent);
Assert::assertNotEquals('', $schema, 'schema is empty');
$schemaObject = $this->decodeAndValidateJson($schema, "Invalid schema json: %s. System message: %s.");
$validator = new JsonSchemaValidator();
$validator->validate($responseObject, $schemaObject, JsonConstraint::CHECK_MODE_VALIDATE_SCHEMA);
$outcome = $validator->isValid();
$message = '';
if (!$outcome) {
foreach ($validator->getErrors() as $error) {
if ($message !== '') {
$message .= ', ';
}
$message .= sprintf("[Property: '%s'] %s", $error['property'], $error['message']);
}
}
Assert::assertTrue(
$outcome,
$message
);
}
/**
* Checks whether last response matches the supplied json schema (https://json-schema.org/)
* Supply schema as relative file path in your project directory or an absolute path
*
* @part json
* @see codecept_absolute_path()
*/
public function seeResponseIsValidOnJsonSchema(string $schemaFilename): void
{
$file = codecept_absolute_path($schemaFilename);
if (!file_exists($file)) {
throw new ModuleException(__CLASS__, sprintf('File %s does not exist', $file));
}
$this->seeResponseIsValidOnJsonSchemaString(file_get_contents($file));