REST.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. <?php
  2. namespace Codeception\Module;
  3. use Codeception\Exception\ConfigurationException;
  4. use Codeception\Exception\ModuleException;
  5. use Codeception\Lib\Interfaces\ConflictsWithModule;
  6. use Codeception\Module as CodeceptionModule;
  7. use Codeception\PHPUnit\Constraint\JsonContains;
  8. use Codeception\PHPUnit\Constraint\JsonType as JsonTypeConstraint;
  9. use Codeception\TestInterface;
  10. use Codeception\Lib\Interfaces\API;
  11. use Codeception\Lib\Framework;
  12. use Codeception\Lib\InnerBrowser;
  13. use Codeception\Lib\Interfaces\DependsOnModule;
  14. use Codeception\Lib\Interfaces\PartedModule;
  15. use Codeception\Util\JsonArray;
  16. use Codeception\Util\JsonType;
  17. use Codeception\Util\XmlStructure;
  18. use Codeception\Util\Soap as XmlUtils;
  19. /**
  20. * Module for testing REST WebService.
  21. *
  22. * This module can be used either with frameworks or PHPBrowser.
  23. * If a framework module is connected, the testing will occur in the application directly.
  24. * Otherwise, a PHPBrowser should be specified as a dependency to send requests and receive responses from a server.
  25. *
  26. * ## Configuration
  27. *
  28. * * url *optional* - the url of api
  29. *
  30. * This module requires PHPBrowser or any of Framework modules enabled.
  31. *
  32. * ### Example
  33. *
  34. * modules:
  35. * enabled:
  36. * - REST:
  37. * depends: PhpBrowser
  38. * url: 'http://serviceapp/api/v1/'
  39. *
  40. * ## Public Properties
  41. *
  42. * * headers - array of headers going to be sent.
  43. * * params - array of sent data
  44. * * response - last response (string)
  45. *
  46. * ## Parts
  47. *
  48. * * Json - actions for validating Json responses (no Xml responses)
  49. * * Xml - actions for validating XML responses (no Json responses)
  50. *
  51. * ## Conflicts
  52. *
  53. * Conflicts with SOAP module
  54. *
  55. */
  56. class REST extends CodeceptionModule implements DependsOnModule, PartedModule, API, ConflictsWithModule
  57. {
  58. protected $config = [
  59. 'url' => '',
  60. 'aws' => ''
  61. ];
  62. protected $dependencyMessage = <<<EOF
  63. Example configuring PhpBrowser as backend for REST module.
  64. --
  65. modules:
  66. enabled:
  67. - REST:
  68. depends: PhpBrowser
  69. url: http://localhost/api/
  70. --
  71. Framework modules can be used for testing of API as well.
  72. EOF;
  73. /**
  74. * @var \Symfony\Component\HttpKernel\Client|\Symfony\Component\BrowserKit\Client
  75. */
  76. public $client = null;
  77. public $isFunctional = false;
  78. /**
  79. * @var InnerBrowser
  80. */
  81. protected $connectionModule;
  82. public $params = [];
  83. public $response = "";
  84. public function _before(TestInterface $test)
  85. {
  86. $this->client = &$this->connectionModule->client;
  87. $this->resetVariables();
  88. }
  89. protected function resetVariables()
  90. {
  91. $this->params = [];
  92. $this->response = "";
  93. $this->connectionModule->headers = [];
  94. }
  95. public function _conflicts()
  96. {
  97. return 'Codeception\Lib\Interfaces\API';
  98. }
  99. public function _depends()
  100. {
  101. return ['Codeception\Lib\InnerBrowser' => $this->dependencyMessage];
  102. }
  103. public function _parts()
  104. {
  105. return ['xml', 'json'];
  106. }
  107. public function _inject(InnerBrowser $connection)
  108. {
  109. $this->connectionModule = $connection;
  110. if ($this->connectionModule instanceof Framework) {
  111. $this->isFunctional = true;
  112. }
  113. if ($this->connectionModule instanceof PhpBrowser) {
  114. if (!$this->connectionModule->_getConfig('url')) {
  115. $this->connectionModule->_setConfig(['url' => $this->config['url']]);
  116. }
  117. }
  118. }
  119. protected function getRunningClient()
  120. {
  121. if ($this->client->getInternalRequest() === null) {
  122. throw new ModuleException($this, "Response is empty. Use `\$I->sendXXX()` methods to send HTTP request");
  123. }
  124. return $this->client;
  125. }
  126. /**
  127. * Sets HTTP header valid for all next requests. Use `deleteHeader` to unset it
  128. *
  129. * ```php
  130. * <?php
  131. * $I->haveHttpHeader('Content-Type', 'application/json');
  132. * // all next requests will contain this header
  133. * ?>
  134. * ```
  135. *
  136. * @param $name
  137. * @param $value
  138. * @part json
  139. * @part xml
  140. */
  141. public function haveHttpHeader($name, $value)
  142. {
  143. $this->connectionModule->haveHttpHeader($name, $value);
  144. }
  145. /**
  146. * Deletes the header with the passed name. Subsequent requests
  147. * will not have the deleted header in its request.
  148. *
  149. * Example:
  150. * ```php
  151. * <?php
  152. * $I->haveHttpHeader('X-Requested-With', 'Codeception');
  153. * $I->sendGET('test-headers.php');
  154. * // ...
  155. * $I->deleteHeader('X-Requested-With');
  156. * $I->sendPOST('some-other-page.php');
  157. * ?>
  158. * ```
  159. *
  160. * @param string $name the name of the header to delete.
  161. * @part json
  162. * @part xml
  163. */
  164. public function deleteHeader($name)
  165. {
  166. $this->connectionModule->deleteHeader($name);
  167. }
  168. /**
  169. * Checks over the given HTTP header and (optionally)
  170. * its value, asserting that are there
  171. *
  172. * @param $name
  173. * @param $value
  174. * @part json
  175. * @part xml
  176. */
  177. public function seeHttpHeader($name, $value = null)
  178. {
  179. if ($value !== null) {
  180. $this->assertEquals(
  181. $value,
  182. $this->getRunningClient()->getInternalResponse()->getHeader($name)
  183. );
  184. return;
  185. }
  186. $this->assertNotNull($this->getRunningClient()->getInternalResponse()->getHeader($name));
  187. }
  188. /**
  189. * Checks over the given HTTP header and (optionally)
  190. * its value, asserting that are not there
  191. *
  192. * @param $name
  193. * @param $value
  194. * @part json
  195. * @part xml
  196. */
  197. public function dontSeeHttpHeader($name, $value = null)
  198. {
  199. if ($value !== null) {
  200. $this->assertNotEquals(
  201. $value,
  202. $this->getRunningClient()->getInternalResponse()->getHeader($name)
  203. );
  204. return;
  205. }
  206. $this->assertNull($this->getRunningClient()->getInternalResponse()->getHeader($name));
  207. }
  208. /**
  209. * Checks that http response header is received only once.
  210. * HTTP RFC2616 allows multiple response headers with the same name.
  211. * You can check that you didn't accidentally sent the same header twice.
  212. *
  213. * ``` php
  214. * <?php
  215. * $I->seeHttpHeaderOnce('Cache-Control');
  216. * ?>>
  217. * ```
  218. *
  219. * @param $name
  220. * @part json
  221. * @part xml
  222. */
  223. public function seeHttpHeaderOnce($name)
  224. {
  225. $headers = $this->getRunningClient()->getInternalResponse()->getHeader($name, false);
  226. $this->assertCount(1, $headers);
  227. }
  228. /**
  229. * Returns the value of the specified header name
  230. *
  231. * @param $name
  232. * @param Boolean $first Whether to return the first value or all header values
  233. *
  234. * @return string|array The first header value if $first is true, an array of values otherwise
  235. * @part json
  236. * @part xml
  237. */
  238. public function grabHttpHeader($name, $first = true)
  239. {
  240. return $this->getRunningClient()->getInternalResponse()->getHeader($name, $first);
  241. }
  242. /**
  243. * Adds HTTP authentication via username/password.
  244. *
  245. * @param $username
  246. * @param $password
  247. * @part json
  248. * @part xml
  249. */
  250. public function amHttpAuthenticated($username, $password)
  251. {
  252. if ($this->isFunctional) {
  253. $this->client->setServerParameter('PHP_AUTH_USER', $username);
  254. $this->client->setServerParameter('PHP_AUTH_PW', $password);
  255. } else {
  256. $this->client->setAuth($username, $password);
  257. }
  258. }
  259. /**
  260. * Adds Digest authentication via username/password.
  261. *
  262. * @param $username
  263. * @param $password
  264. * @part json
  265. * @part xml
  266. */
  267. public function amDigestAuthenticated($username, $password)
  268. {
  269. if ($this->isFunctional) {
  270. throw new ModuleException(__METHOD__, 'Not supported by functional modules');
  271. }
  272. $this->client->setAuth($username, $password, 'digest');
  273. }
  274. /**
  275. * Adds Bearer authentication via access token.
  276. *
  277. * @param $accessToken
  278. * @part json
  279. * @part xml
  280. */
  281. public function amBearerAuthenticated($accessToken)
  282. {
  283. $this->haveHttpHeader('Authorization', 'Bearer ' . $accessToken);
  284. }
  285. /**
  286. * Adds NTLM authentication via username/password.
  287. * Requires client to be Guzzle >=6.3.0
  288. * Out of scope for functional modules.
  289. *
  290. * Example:
  291. * ```php
  292. * <?php
  293. * $I->amNTLMAuthenticated('jon_snow', 'targaryen');
  294. * ?>
  295. * ```
  296. *
  297. * @param $username
  298. * @param $password
  299. * @throws ModuleException
  300. * @part json
  301. * @part xml
  302. */
  303. public function amNTLMAuthenticated($username, $password)
  304. {
  305. if ($this->isFunctional) {
  306. throw new ModuleException(__METHOD__, 'Not supported by functional modules');
  307. }
  308. if (!defined('\GuzzleHttp\Client::VERSION')) {
  309. throw new ModuleException(__METHOD__, 'Not supported if not using a Guzzle client');
  310. }
  311. if (version_compare(\GuzzleHttp\Client::VERSION, '6.2.1', 'lt')) {
  312. throw new ModuleException(__METHOD__, 'Guzzle '.\GuzzleHttp\Client::VERSION.' found. Requires Guzzle >=6.3.0 for NTLM auth option');
  313. }
  314. $this->client->setAuth($username, $password, 'ntlm');
  315. }
  316. /**
  317. * Allows to send REST request using AWS Authorization
  318. *
  319. * Only works with PhpBrowser
  320. * Example Config:
  321. * ```yml
  322. * modules:
  323. * enabled:
  324. * - REST:
  325. * aws:
  326. * key: accessKey
  327. * secret: accessSecret
  328. * service: awsService
  329. * region: awsRegion
  330. * ```
  331. * Code:
  332. * ```php
  333. * <?php
  334. * $I->amAWSAuthenticated();
  335. * ?>
  336. * ```
  337. * @param array $additionalAWSConfig
  338. * @throws ModuleException
  339. */
  340. public function amAWSAuthenticated($additionalAWSConfig = [])
  341. {
  342. if (method_exists($this->client, 'setAwsAuth')) {
  343. $config = array_merge($this->config['aws'], $additionalAWSConfig);
  344. if (!isset($config['key'])) {
  345. throw new ConfigurationException('AWS Key is not set');
  346. }
  347. if (!isset($config['secret'])) {
  348. throw new ConfigurationException('AWS Secret is not set');
  349. }
  350. if (!isset($config['service'])) {
  351. throw new ConfigurationException('AWS Service is not set');
  352. }
  353. if (!isset($config['region'])) {
  354. throw new ConfigurationException('AWS Region is not set');
  355. }
  356. $this->client->setAwsAuth($config);
  357. }
  358. }
  359. /**
  360. * Sends a POST request to given uri. Parameters and files can be provided separately.
  361. *
  362. * Example:
  363. * ```php
  364. * <?php
  365. * //simple POST call
  366. * $I->sendPOST('/message', ['subject' => 'Read this!', 'to' => 'johndoe@example.com']);
  367. * //simple upload method
  368. * $I->sendPOST('/message/24', ['inline' => 0], ['attachmentFile' => codecept_data_dir('sample_file.pdf')]);
  369. * //uploading a file with a custom name and mime-type. This is also useful to simulate upload errors.
  370. * $I->sendPOST('/message/24', ['inline' => 0], [
  371. * 'attachmentFile' => [
  372. * 'name' => 'document.pdf',
  373. * 'type' => 'application/pdf',
  374. * 'error' => UPLOAD_ERR_OK,
  375. * 'size' => filesize(codecept_data_dir('sample_file.pdf')),
  376. * 'tmp_name' => codecept_data_dir('sample_file.pdf')
  377. * ]
  378. * ]);
  379. * ```
  380. *
  381. * @param $url
  382. * @param array|\JsonSerializable $params
  383. * @param array $files A list of filenames or "mocks" of $_FILES (each entry being an array with the following
  384. * keys: name, type, error, size, tmp_name (pointing to the real file path). Each key works
  385. * as the "name" attribute of a file input field.
  386. *
  387. * @see http://php.net/manual/en/features.file-upload.post-method.php
  388. * @see codecept_data_dir()
  389. * @part json
  390. * @part xml
  391. */
  392. public function sendPOST($url, $params = [], $files = [])
  393. {
  394. $this->execute('POST', $url, $params, $files);
  395. }
  396. /**
  397. * Sends a HEAD request to given uri.
  398. *
  399. * @param $url
  400. * @param array $params
  401. * @part json
  402. * @part xml
  403. */
  404. public function sendHEAD($url, $params = [])
  405. {
  406. $this->execute('HEAD', $url, $params);
  407. }
  408. /**
  409. * Sends an OPTIONS request to given uri.
  410. *
  411. * @param $url
  412. * @param array $params
  413. * @part json
  414. * @part xml
  415. */
  416. public function sendOPTIONS($url, $params = [])
  417. {
  418. $this->execute('OPTIONS', $url, $params);
  419. }
  420. /**
  421. * Sends a GET request to given uri.
  422. *
  423. * @param $url
  424. * @param array $params
  425. * @part json
  426. * @part xml
  427. */
  428. public function sendGET($url, $params = [])
  429. {
  430. $this->execute('GET', $url, $params);
  431. }
  432. /**
  433. * Sends PUT request to given uri.
  434. *
  435. * @param $url
  436. * @param array $params
  437. * @param array $files
  438. * @part json
  439. * @part xml
  440. */
  441. public function sendPUT($url, $params = [], $files = [])
  442. {
  443. $this->execute('PUT', $url, $params, $files);
  444. }
  445. /**
  446. * Sends PATCH request to given uri.
  447. *
  448. * @param $url
  449. * @param array $params
  450. * @param array $files
  451. * @part json
  452. * @part xml
  453. */
  454. public function sendPATCH($url, $params = [], $files = [])
  455. {
  456. $this->execute('PATCH', $url, $params, $files);
  457. }
  458. /**
  459. * Sends DELETE request to given uri.
  460. *
  461. * @param $url
  462. * @param array $params
  463. * @param array $files
  464. * @part json
  465. * @part xml
  466. */
  467. public function sendDELETE($url, $params = [], $files = [])
  468. {
  469. $this->execute('DELETE', $url, $params, $files);
  470. }
  471. /**
  472. * Sets Headers "Link" as one header "Link" based on linkEntries
  473. *
  474. * @param array $linkEntries (entry is array with keys "uri" and "link-param")
  475. *
  476. * @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
  477. *
  478. * @author samva.ua@gmail.com
  479. */
  480. private function setHeaderLink(array $linkEntries)
  481. {
  482. $values = [];
  483. foreach ($linkEntries as $linkEntry) {
  484. \PHPUnit\Framework\Assert::assertArrayHasKey(
  485. 'uri',
  486. $linkEntry,
  487. 'linkEntry should contain property "uri"'
  488. );
  489. \PHPUnit\Framework\Assert::assertArrayHasKey(
  490. 'link-param',
  491. $linkEntry,
  492. 'linkEntry should contain property "link-param"'
  493. );
  494. $values[] = $linkEntry['uri'] . '; ' . $linkEntry['link-param'];
  495. }
  496. $this->haveHttpHeader('Link', implode(', ', $values));
  497. }
  498. /**
  499. * Sends LINK request to given uri.
  500. *
  501. * @param $url
  502. * @param array $linkEntries (entry is array with keys "uri" and "link-param")
  503. *
  504. * @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
  505. *
  506. * @author samva.ua@gmail.com
  507. * @part json
  508. * @part xml
  509. */
  510. public function sendLINK($url, array $linkEntries)
  511. {
  512. $this->setHeaderLink($linkEntries);
  513. $this->execute('LINK', $url);
  514. }
  515. /**
  516. * Sends UNLINK request to given uri.
  517. *
  518. * @param $url
  519. * @param array $linkEntries (entry is array with keys "uri" and "link-param")
  520. * @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
  521. * @author samva.ua@gmail.com
  522. * @part json
  523. * @part xml
  524. */
  525. public function sendUNLINK($url, array $linkEntries)
  526. {
  527. $this->setHeaderLink($linkEntries);
  528. $this->execute('UNLINK', $url);
  529. }
  530. protected function execute($method, $url, $parameters = [], $files = [])
  531. {
  532. // allow full url to be requested
  533. if (strpos($url, '://') === false) {
  534. $url = $this->config['url'] . $url;
  535. if ($this->config['url'] && strpos($url, '://') === false && $this->config['url'][0] !== '/') {
  536. $url = '/' . $url;
  537. }
  538. }
  539. $this->params = $parameters;
  540. $parameters = $this->encodeApplicationJson($method, $parameters);
  541. if (is_array($parameters) || $method === 'GET') {
  542. if (!empty($parameters) && $method === 'GET') {
  543. if (strpos($url, '?') !== false) {
  544. $url .= '&';
  545. } else {
  546. $url .= '?';
  547. }
  548. $url .= http_build_query($parameters);
  549. }
  550. if ($method == 'GET') {
  551. $this->debugSection("Request", "$method $url");
  552. $files = [];
  553. } else {
  554. $this->debugSection("Request", "$method $url " . json_encode($parameters));
  555. $files = $this->formatFilesArray($files);
  556. }
  557. $this->response = (string)$this->connectionModule->_request($method, $url, $parameters, $files);
  558. } else {
  559. $requestData = $parameters;
  560. if ($this->isBinaryData($requestData)) {
  561. $requestData = $this->binaryToDebugString($requestData);
  562. }
  563. $this->debugSection("Request", "$method $url " . $requestData);
  564. $this->response = (string)$this->connectionModule->_request($method, $url, [], $files, [], $parameters);
  565. }
  566. $printedResponse = $this->response;
  567. if ($this->isBinaryData($printedResponse)) {
  568. $printedResponse = $this->binaryToDebugString($printedResponse);
  569. }
  570. $this->debugSection("Response", $printedResponse);
  571. }
  572. /**
  573. * Check if data has non-printable bytes and it is not a valid unicode string
  574. *
  575. * @param string $data the text or binary data string
  576. * @return boolean
  577. */
  578. protected function isBinaryData($data)
  579. {
  580. return !ctype_print($data) && false === mb_detect_encoding($data, mb_detect_order(), true);
  581. }
  582. /**
  583. * Format a binary string for debug printing
  584. *
  585. * @param string $data the binary data string
  586. * @return string the debug string
  587. */
  588. protected function binaryToDebugString($data)
  589. {
  590. return '[binary-data length:' . strlen($data) . ' md5:' . md5($data) . ']';
  591. }
  592. protected function encodeApplicationJson($method, $parameters)
  593. {
  594. if ($method !== 'GET' && array_key_exists('Content-Type', $this->connectionModule->headers)
  595. && ($this->connectionModule->headers['Content-Type'] === 'application/json'
  596. || preg_match('!^application/.+\+json$!', $this->connectionModule->headers['Content-Type'])
  597. )
  598. ) {
  599. if ($parameters instanceof \JsonSerializable) {
  600. return json_encode($parameters);
  601. }
  602. if (is_array($parameters) || $parameters instanceof \ArrayAccess) {
  603. $parameters = $this->scalarizeArray($parameters);
  604. return json_encode($parameters);
  605. }
  606. }
  607. return $parameters;
  608. }
  609. private function formatFilesArray(array $files)
  610. {
  611. foreach ($files as $name => $value) {
  612. if (is_string($value)) {
  613. $this->checkFileBeforeUpload($value);
  614. $files[$name] = [
  615. 'name' => basename($value),
  616. 'tmp_name' => $value,
  617. 'size' => filesize($value),
  618. 'type' => $this->getFileType($value),
  619. 'error' => 0,
  620. ];
  621. continue;
  622. } elseif (is_array($value)) {
  623. if (isset($value['tmp_name'])) {
  624. $this->checkFileBeforeUpload($value['tmp_name']);
  625. if (!isset($value['name'])) {
  626. $value['name'] = basename($value['tmp_name']);
  627. }
  628. if (!isset($value['size'])) {
  629. $value['size'] = filesize($value['tmp_name']);
  630. }
  631. if (!isset($value['type'])) {
  632. $value['type'] = $this->getFileType($value['tmp_name']);
  633. }
  634. if (!isset($value['error'])) {
  635. $value['error'] = 0;
  636. }
  637. } else {
  638. $files[$name] = $this->formatFilesArray($value);
  639. }
  640. } elseif (is_object($value)) {
  641. /**
  642. * do nothing, probably the user knows what he is doing
  643. * @issue https://github.com/Codeception/Codeception/issues/3298
  644. */
  645. } else {
  646. throw new ModuleException(__CLASS__, "Invalid value of key $name in files array");
  647. }
  648. }
  649. return $files;
  650. }
  651. private function getFileType($file)
  652. {
  653. if (function_exists('mime_content_type') && mime_content_type($file)) {
  654. return mime_content_type($file);
  655. }
  656. return 'application/octet-stream';
  657. }
  658. private function checkFileBeforeUpload($file)
  659. {
  660. if (!file_exists($file)) {
  661. throw new ModuleException(__CLASS__, "File $file does not exist");
  662. }
  663. if (!is_readable($file)) {
  664. throw new ModuleException(__CLASS__, "File $file is not readable");
  665. }
  666. if (!is_file($file)) {
  667. throw new ModuleException(__CLASS__, "File $file is not a regular file");
  668. }
  669. }
  670. /**
  671. * Checks whether last response was valid JSON.
  672. * This is done with json_last_error function.
  673. *
  674. * @part json
  675. */
  676. public function seeResponseIsJson()
  677. {
  678. $responseContent = $this->connectionModule->_getResponseContent();
  679. \PHPUnit\Framework\Assert::assertNotEquals('', $responseContent, 'response is empty');
  680. json_decode($responseContent);
  681. $errorCode = json_last_error();
  682. $errorMessage = json_last_error_msg();
  683. \PHPUnit\Framework\Assert::assertEquals(
  684. JSON_ERROR_NONE,
  685. $errorCode,
  686. sprintf(
  687. "Invalid json: %s. System message: %s.",
  688. $responseContent,
  689. $errorMessage
  690. )
  691. );
  692. }
  693. /**
  694. * Checks whether the last response contains text.
  695. *
  696. * @param $text
  697. * @part json
  698. * @part xml
  699. */
  700. public function seeResponseContains($text)
  701. {
  702. $this->assertContains($text, $this->connectionModule->_getResponseContent(), "REST response contains");
  703. }
  704. /**
  705. * Checks whether last response do not contain text.
  706. *
  707. * @param $text
  708. * @part json
  709. * @part xml
  710. */
  711. public function dontSeeResponseContains($text)
  712. {
  713. $this->assertNotContains($text, $this->connectionModule->_getResponseContent(), "REST response contains");
  714. }
  715. /**
  716. * Checks whether the last JSON response contains provided array.
  717. * The response is converted to array with json_decode($response, true)
  718. * Thus, JSON is represented by associative array.
  719. * This method matches that response array contains provided array.
  720. *
  721. * Examples:
  722. *
  723. * ``` php
  724. * <?php
  725. * // response: {name: john, email: john@gmail.com}
  726. * $I->seeResponseContainsJson(array('name' => 'john'));
  727. *
  728. * // response {user: john, profile: { email: john@gmail.com }}
  729. * $I->seeResponseContainsJson(array('email' => 'john@gmail.com'));
  730. *
  731. * ?>
  732. * ```
  733. *
  734. * This method recursively checks if one array can be found inside of another.
  735. *
  736. * @param array $json
  737. * @part json
  738. */
  739. public function seeResponseContainsJson($json = [])
  740. {
  741. \PHPUnit\Framework\Assert::assertThat(
  742. $this->connectionModule->_getResponseContent(),
  743. new JsonContains($json)
  744. );
  745. }
  746. /**
  747. * Returns current response so that it can be used in next scenario steps.
  748. *
  749. * Example:
  750. *
  751. * ``` php
  752. * <?php
  753. * $user_id = $I->grabResponse();
  754. * $I->sendPUT('/user', array('id' => $user_id, 'name' => 'davert'));
  755. * ?>
  756. * ```
  757. *
  758. * @version 1.1
  759. * @return string
  760. * @part json
  761. * @part xml
  762. */
  763. public function grabResponse()
  764. {
  765. return $this->connectionModule->_getResponseContent();
  766. }
  767. /**
  768. * Returns data from the current JSON response using [JSONPath](http://goessner.net/articles/JsonPath/) as selector.
  769. * JsonPath is XPath equivalent for querying Json structures.
  770. * Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
  771. * Even for a single value an array is returned.
  772. *
  773. * This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
  774. *
  775. * Example:
  776. *
  777. * ``` php
  778. * <?php
  779. * // match the first `user.id` in json
  780. * $firstUserId = $I->grabDataFromResponseByJsonPath('$..users[0].id');
  781. * $I->sendPUT('/user', array('id' => $firstUserId[0], 'name' => 'davert'));
  782. * ?>
  783. * ```
  784. *
  785. * @param string $jsonPath
  786. * @return array Array of matching items
  787. * @version 2.0.9
  788. * @throws \Exception
  789. * @part json
  790. */
  791. public function grabDataFromResponseByJsonPath($jsonPath)
  792. {
  793. return (new JsonArray($this->connectionModule->_getResponseContent()))->filterByJsonPath($jsonPath);
  794. }
  795. /**
  796. * Checks if json structure in response matches the xpath provided.
  797. * JSON is not supposed to be checked against XPath, yet it can be converted to xml and used with XPath.
  798. * This assertion allows you to check the structure of response json.
  799. * *
  800. * ```json
  801. * { "store": {
  802. * "book": [
  803. * { "category": "reference",
  804. * "author": "Nigel Rees",
  805. * "title": "Sayings of the Century",
  806. * "price": 8.95
  807. * },
  808. * { "category": "fiction",
  809. * "author": "Evelyn Waugh",
  810. * "title": "Sword of Honour",
  811. * "price": 12.99
  812. * }
  813. * ],
  814. * "bicycle": {
  815. * "color": "red",
  816. * "price": 19.95
  817. * }
  818. * }
  819. * }
  820. * ```
  821. *
  822. * ```php
  823. * <?php
  824. * // at least one book in store has author
  825. * $I->seeResponseJsonMatchesXpath('//store/book/author');
  826. * // first book in store has author
  827. * $I->seeResponseJsonMatchesXpath('//store/book[1]/author');
  828. * // at least one item in store has price
  829. * $I->seeResponseJsonMatchesXpath('/store//price');
  830. * ?>
  831. * ```
  832. * @param string $xpath
  833. * @part json
  834. * @version 2.0.9
  835. */
  836. public function seeResponseJsonMatchesXpath($xpath)
  837. {
  838. $response = $this->connectionModule->_getResponseContent();
  839. $this->assertGreaterThan(
  840. 0,
  841. (new JsonArray($response))->filterByXPath($xpath)->length,
  842. "Received JSON did not match the XPath `$xpath`.\nJson Response: \n" . $response
  843. );
  844. }
  845. /**
  846. * Opposite to seeResponseJsonMatchesXpath
  847. *
  848. * @param string $xpath
  849. * @part json
  850. */
  851. public function dontSeeResponseJsonMatchesXpath($xpath)
  852. {
  853. $response = $this->connectionModule->_getResponseContent();
  854. $this->assertEquals(
  855. 0,
  856. (new JsonArray($response))->filterByXPath($xpath)->length,
  857. "Received JSON matched the XPath `$xpath`.\nJson Response: \n" . $response
  858. );
  859. }
  860. /**
  861. * Checks if json structure in response matches [JsonPath](http://goessner.net/articles/JsonPath/).
  862. * JsonPath is XPath equivalent for querying Json structures.
  863. * Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
  864. * This assertion allows you to check the structure of response json.
  865. *
  866. * This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
  867. *
  868. * ```json
  869. * { "store": {
  870. * "book": [
  871. * { "category": "reference",
  872. * "author": "Nigel Rees",
  873. * "title": "Sayings of the Century",
  874. * "price": 8.95
  875. * },
  876. * { "category": "fiction",
  877. * "author": "Evelyn Waugh",
  878. * "title": "Sword of Honour",
  879. * "price": 12.99
  880. * }
  881. * ],
  882. * "bicycle": {
  883. * "color": "red",
  884. * "price": 19.95
  885. * }
  886. * }
  887. * }
  888. * ```
  889. *
  890. * ```php
  891. * <?php
  892. * // at least one book in store has author
  893. * $I->seeResponseJsonMatchesJsonPath('$.store.book[*].author');
  894. * // first book in store has author
  895. * $I->seeResponseJsonMatchesJsonPath('$.store.book[0].author');
  896. * // at least one item in store has price
  897. * $I->seeResponseJsonMatchesJsonPath('$.store..price');
  898. * ?>
  899. * ```
  900. *
  901. * @param string $jsonPath
  902. * @part json
  903. * @version 2.0.9
  904. */
  905. public function seeResponseJsonMatchesJsonPath($jsonPath)
  906. {
  907. $response = $this->connectionModule->_getResponseContent();
  908. $this->assertNotEmpty(
  909. (new JsonArray($response))->filterByJsonPath($jsonPath),
  910. "Received JSON did not match the JsonPath `$jsonPath`.\nJson Response: \n" . $response
  911. );
  912. }
  913. /**
  914. * Opposite to seeResponseJsonMatchesJsonPath
  915. *
  916. * @param string $jsonPath
  917. * @part json
  918. */
  919. public function dontSeeResponseJsonMatchesJsonPath($jsonPath)
  920. {
  921. $response = $this->connectionModule->_getResponseContent();
  922. $this->assertEmpty(
  923. (new JsonArray($response))->filterByJsonPath($jsonPath),
  924. "Received JSON matched the JsonPath `$jsonPath`.\nJson Response: \n" . $response
  925. );
  926. }
  927. /**
  928. * Opposite to seeResponseContainsJson
  929. *
  930. * @part json
  931. * @param array $json
  932. */
  933. public function dontSeeResponseContainsJson($json = [])
  934. {
  935. $jsonResponseArray = new JsonArray($this->connectionModule->_getResponseContent());
  936. $this->assertFalse(
  937. $jsonResponseArray->containsArray($json),
  938. "Response JSON contains provided JSON\n"
  939. . "- <info>" . var_export($json, true) . "</info>\n"
  940. . "+ " . var_export($jsonResponseArray->toArray(), true)
  941. );
  942. }
  943. /**
  944. * Checks that Json matches provided types.
  945. * In case you don't know the actual values of JSON data returned you can match them by type.
  946. * Starts check with a root element. If JSON data is array it will check the first element of an array.
  947. * You can specify the path in the json which should be checked with JsonPath
  948. *
  949. * Basic example:
  950. *
  951. * ```php
  952. * <?php
  953. * // {'user_id': 1, 'name': 'davert', 'is_active': false}
  954. * $I->seeResponseMatchesJsonType([
  955. * 'user_id' => 'integer',
  956. * 'name' => 'string|null',
  957. * 'is_active' => 'boolean'
  958. * ]);
  959. *
  960. * // narrow down matching with JsonPath:
  961. * // {"users": [{ "name": "davert"}, {"id": 1}]}
  962. * $I->seeResponseMatchesJsonType(['name' => 'string'], '$.users[0]');
  963. * ?>
  964. * ```
  965. *
  966. * In this case you can match that record contains fields with data types you expected.
  967. * The list of possible data types:
  968. *
  969. * * string
  970. * * integer
  971. * * float
  972. * * array (json object is array as well)
  973. * * boolean
  974. *
  975. * You can also use nested data type structures:
  976. *
  977. * ```php
  978. * <?php
  979. * // {'user_id': 1, 'name': 'davert', 'company': {'name': 'Codegyre'}}
  980. * $I->seeResponseMatchesJsonType([
  981. * 'user_id' => 'integer|string', // multiple types
  982. * 'company' => ['name' => 'string']
  983. * ]);
  984. * ?>
  985. * ```
  986. *
  987. * You can also apply filters to check values. Filter can be applied with `:` char after the type declaration.
  988. *
  989. * Here is the list of possible filters:
  990. *
  991. * * `integer:>{val}` - checks that integer is greater than {val} (works with float and string types too).
  992. * * `integer:<{val}` - checks that integer is lower than {val} (works with float and string types too).
  993. * * `string:url` - checks that value is valid url.
  994. * * `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
  995. * * `string:email` - checks that value is a valid email according to http://emailregex.com/
  996. * * `string:regex({val})` - checks that string matches a regex provided with {val}
  997. *
  998. * This is how filters can be used:
  999. *
  1000. * ```php
  1001. * <?php
  1002. * // {'user_id': 1, 'email' => 'davert@codeception.com'}
  1003. * $I->seeResponseMatchesJsonType([
  1004. * 'user_id' => 'string:>0:<1000', // multiple filters can be used
  1005. * 'email' => 'string:regex(~\@~)' // we just check that @ char is included
  1006. * ]);
  1007. *
  1008. * // {'user_id': '1'}
  1009. * $I->seeResponseMatchesJsonType([
  1010. * 'user_id' => 'string:>0', // works with strings as well
  1011. * }
  1012. * ?>
  1013. * ```
  1014. *
  1015. * You can also add custom filters y accessing `JsonType::addCustomFilter` method.
  1016. * See [JsonType reference](http://codeception.com/docs/reference/JsonType).
  1017. *
  1018. * @part json
  1019. * @version 2.1.3
  1020. * @param array $jsonType
  1021. * @param string $jsonPath
  1022. */
  1023. public function seeResponseMatchesJsonType(array $jsonType, $jsonPath = null)
  1024. {
  1025. $jsonArray = new JsonArray($this->connectionModule->_getResponseContent());
  1026. if ($jsonPath) {
  1027. $jsonArray = $jsonArray->filterByJsonPath($jsonPath);
  1028. }
  1029. \PHPUnit\Framework\Assert::assertThat($jsonArray, new JsonTypeConstraint($jsonType));
  1030. }
  1031. /**
  1032. * Opposite to `seeResponseMatchesJsonType`.
  1033. *
  1034. * @part json
  1035. * @see seeResponseMatchesJsonType
  1036. * @param $jsonType jsonType structure
  1037. * @param null $jsonPath optionally set specific path to structure with JsonPath
  1038. * @version 2.1.3
  1039. */
  1040. public function dontSeeResponseMatchesJsonType($jsonType, $jsonPath = null)
  1041. {
  1042. $jsonArray = new JsonArray($this->connectionModule->_getResponseContent());
  1043. if ($jsonPath) {
  1044. $jsonArray = $jsonArray->filterByJsonPath($jsonPath);
  1045. }
  1046. \PHPUnit\Framework\Assert::assertThat($jsonArray, new JsonTypeConstraint($jsonType, false));
  1047. }
  1048. /**
  1049. * Checks if response is exactly the same as provided.
  1050. *
  1051. * @part json
  1052. * @part xml
  1053. * @param $response
  1054. */
  1055. public function seeResponseEquals($expected)
  1056. {
  1057. $this->assertEquals($expected, $this->connectionModule->_getResponseContent());
  1058. }
  1059. /**
  1060. * Checks response code equals to provided value.
  1061. *
  1062. * ```php
  1063. * <?php
  1064. * $I->seeResponseCodeIs(200);
  1065. *
  1066. * // preferred to use \Codeception\Util\HttpCode
  1067. * $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
  1068. * ```
  1069. *
  1070. * @part json
  1071. * @part xml
  1072. * @param $code
  1073. */
  1074. public function seeResponseCodeIs($code)
  1075. {
  1076. $this->connectionModule->seeResponseCodeIs($code);
  1077. }
  1078. /**
  1079. * Checks that response code is not equal to provided value.
  1080. *
  1081. * ```php
  1082. * <?php
  1083. * $I->dontSeeResponseCodeIs(200);
  1084. *
  1085. * // preferred to use \Codeception\Util\HttpCode
  1086. * $I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
  1087. * ```
  1088. *
  1089. * @part json
  1090. * @part xml
  1091. * @param $code
  1092. */
  1093. public function dontSeeResponseCodeIs($code)
  1094. {
  1095. $this->connectionModule->dontSeeResponseCodeIs($code);
  1096. }
  1097. /**
  1098. * Checks that the response code is 2xx
  1099. *
  1100. * @part json
  1101. * @part xml
  1102. */
  1103. public function seeResponseCodeIsSuccessful()
  1104. {
  1105. $this->connectionModule->seeResponseCodeIsSuccessful();
  1106. }
  1107. /**
  1108. * Checks that the response code 3xx
  1109. *
  1110. * @part json
  1111. * @part xml
  1112. */
  1113. public function seeResponseCodeIsRedirection()
  1114. {
  1115. $this->connectionModule->seeResponseCodeIsRedirection();
  1116. }
  1117. /**
  1118. * Checks that the response code is 4xx
  1119. *
  1120. * @part json
  1121. * @part xml
  1122. */
  1123. public function seeResponseCodeIsClientError()
  1124. {
  1125. $this->connectionModule->seeResponseCodeIsClientError();
  1126. }
  1127. /**
  1128. * Checks that the response code is 5xx
  1129. *
  1130. * @part json
  1131. * @part xml
  1132. */
  1133. public function seeResponseCodeIsServerError()
  1134. {
  1135. $this->connectionModule->seeResponseCodeIsServerError();
  1136. }
  1137. /**
  1138. * Checks whether last response was valid XML.
  1139. * This is done with libxml_get_last_error function.
  1140. *
  1141. * @part xml
  1142. */
  1143. public function seeResponseIsXml()
  1144. {
  1145. libxml_use_internal_errors(true);
  1146. $doc = simplexml_load_string($this->connectionModule->_getResponseContent());
  1147. $num = "";
  1148. $title = "";
  1149. if ($doc === false) {
  1150. $error = libxml_get_last_error();
  1151. $num = $error->code;
  1152. $title = trim($error->message);
  1153. libxml_clear_errors();
  1154. }
  1155. libxml_use_internal_errors(false);
  1156. \PHPUnit\Framework\Assert::assertNotSame(
  1157. false,
  1158. $doc,
  1159. "xml decoding error #$num with message \"$title\", see http://www.xmlsoft.org/html/libxml-xmlerror.html"
  1160. );
  1161. }
  1162. /**
  1163. * Checks whether XML response matches XPath
  1164. *
  1165. * ```php
  1166. * <?php
  1167. * $I->seeXmlResponseMatchesXpath('//root/user[@id=1]');
  1168. * ```
  1169. * @part xml
  1170. * @param $xpath
  1171. */
  1172. public function seeXmlResponseMatchesXpath($xpath)
  1173. {
  1174. $structure = new XmlStructure($this->connectionModule->_getResponseContent());
  1175. $this->assertTrue($structure->matchesXpath($xpath), 'xpath not matched');
  1176. }
  1177. /**
  1178. * Checks whether XML response does not match XPath
  1179. *
  1180. * ```php
  1181. * <?php
  1182. * $I->dontSeeXmlResponseMatchesXpath('//root/user[@id=1]');
  1183. * ```
  1184. * @part xml
  1185. * @param $xpath
  1186. */
  1187. public function dontSeeXmlResponseMatchesXpath($xpath)
  1188. {
  1189. $structure = new XmlStructure($this->connectionModule->_getResponseContent());
  1190. $this->assertFalse($structure->matchesXpath($xpath), 'accidentally matched xpath');
  1191. }
  1192. /**
  1193. * Finds and returns text contents of element.
  1194. * Element is matched by either CSS or XPath
  1195. *
  1196. * @param $cssOrXPath
  1197. * @return string
  1198. * @part xml
  1199. */
  1200. public function grabTextContentFromXmlElement($cssOrXPath)
  1201. {
  1202. $el = (new XmlStructure($this->connectionModule->_getResponseContent()))->matchElement($cssOrXPath);
  1203. return $el->textContent;
  1204. }
  1205. /**
  1206. * Finds and returns attribute of element.
  1207. * Element is matched by either CSS or XPath
  1208. *
  1209. * @param $cssOrXPath
  1210. * @param $attribute
  1211. * @return string
  1212. * @part xml
  1213. */
  1214. public function grabAttributeFromXmlElement($cssOrXPath, $attribute)
  1215. {
  1216. $el = (new XmlStructure($this->connectionModule->_getResponseContent()))->matchElement($cssOrXPath);
  1217. if (!$el->hasAttribute($attribute)) {
  1218. $this->fail("Attribute not found in element matched by '$cssOrXPath'");
  1219. }
  1220. return $el->getAttribute($attribute);
  1221. }
  1222. /**
  1223. * Checks XML response equals provided XML.
  1224. * Comparison is done by canonicalizing both xml`s.
  1225. *
  1226. * Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
  1227. *
  1228. * @param $xml
  1229. * @part xml
  1230. */
  1231. public function seeXmlResponseEquals($xml)
  1232. {
  1233. \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlString($this->connectionModule->_getResponseContent(), $xml);
  1234. }
  1235. /**
  1236. * Checks XML response does not equal to provided XML.
  1237. * Comparison is done by canonicalizing both xml`s.
  1238. *
  1239. * Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
  1240. *
  1241. * @param $xml
  1242. * @part xml
  1243. */
  1244. public function dontSeeXmlResponseEquals($xml)
  1245. {
  1246. \PHPUnit\Framework\Assert::assertXmlStringNotEqualsXmlString(
  1247. $this->connectionModule->_getResponseContent(),
  1248. $xml
  1249. );
  1250. }
  1251. /**
  1252. * Checks XML response includes provided XML.
  1253. * Comparison is done by canonicalizing both xml`s.
  1254. * Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
  1255. *
  1256. * Example:
  1257. *
  1258. * ``` php
  1259. * <?php
  1260. * $I->seeXmlResponseIncludes("<result>1</result>");
  1261. * ?>
  1262. * ```
  1263. *
  1264. * @param $xml
  1265. * @part xml
  1266. */
  1267. public function seeXmlResponseIncludes($xml)
  1268. {
  1269. $this->assertContains(
  1270. XmlUtils::toXml($xml)->C14N(),
  1271. XmlUtils::toXml($this->connectionModule->_getResponseContent())->C14N(),
  1272. "found in XML Response"
  1273. );
  1274. }
  1275. /**
  1276. * Checks XML response does not include provided XML.
  1277. * Comparison is done by canonicalizing both xml`s.
  1278. * Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
  1279. *
  1280. * @param $xml
  1281. * @part xml
  1282. */
  1283. public function dontSeeXmlResponseIncludes($xml)
  1284. {
  1285. $this->assertNotContains(
  1286. XmlUtils::toXml($xml)->C14N(),
  1287. XmlUtils::toXml($this->connectionModule->_getResponseContent())->C14N(),
  1288. "found in XML Response"
  1289. );
  1290. }
  1291. /**
  1292. * Checks if the hash of a binary response is exactly the same as provided.
  1293. * Parameter can be passed as any hash string supported by hash(), with an
  1294. * optional second parameter to specify the hash type, which defaults to md5.
  1295. *
  1296. * Example: Using md5 hash key
  1297. *
  1298. * ```php
  1299. * <?php
  1300. * $I->seeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
  1301. * ?>
  1302. * ```
  1303. *
  1304. * Example: Using md5 for a file contents
  1305. *
  1306. * ```php
  1307. * <?php
  1308. * $fileData = file_get_contents("test_file.jpg");
  1309. * $I->seeBinaryResponseEquals(md5($fileData));
  1310. * ?>
  1311. * ```
  1312. * Example: Using sha256 hash
  1313. *
  1314. * ```php
  1315. * <?php
  1316. * $fileData = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; // very small jpeg
  1317. * $I->seeBinaryResponseEquals(hash("sha256", base64_decode($fileData)), 'sha256');
  1318. * ?>
  1319. * ```
  1320. *
  1321. * @param $hash the hashed data response expected
  1322. * @param $algo the hash algorithm to use. Default md5.
  1323. * @part json
  1324. * @part xml
  1325. */
  1326. public function seeBinaryResponseEquals($hash, $algo = 'md5')
  1327. {
  1328. $responseHash = hash($algo, $this->connectionModule->_getResponseContent());
  1329. $this->assertEquals($hash, $responseHash);
  1330. }
  1331. /**
  1332. * Checks if the hash of a binary response is not the same as provided.
  1333. *
  1334. * ```php
  1335. * <?php
  1336. * $I->dontSeeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
  1337. * ?>
  1338. * ```
  1339. * Opposite to `seeBinaryResponseEquals`
  1340. *
  1341. * @param $hash the hashed data response expected
  1342. * @param $algo the hash algorithm to use. Default md5.
  1343. * @part json
  1344. * @part xml
  1345. */
  1346. public function dontSeeBinaryResponseEquals($hash, $algo = 'md5')
  1347. {
  1348. $responseHash = hash($algo, $this->connectionModule->_getResponseContent());
  1349. $this->assertNotEquals($hash, $responseHash);
  1350. }
  1351. /**
  1352. * Deprecated since 2.0.9 and removed since 2.1.0
  1353. *
  1354. * @param $path
  1355. * @throws ModuleException
  1356. * @deprecated
  1357. */
  1358. public function grabDataFromJsonResponse($path)
  1359. {
  1360. throw new ModuleException(
  1361. $this,
  1362. "This action was deprecated in Codeception 2.0.9 and removed in 2.1. "
  1363. . "Please use `grabDataFromResponseByJsonPath` instead"
  1364. );
  1365. }
  1366. /**
  1367. * Prevents automatic redirects to be followed by the client
  1368. *
  1369. * ```php
  1370. * <?php
  1371. * $I->stopFollowingRedirects();
  1372. * ```
  1373. *
  1374. * @part xml
  1375. * @part json
  1376. */
  1377. public function stopFollowingRedirects()
  1378. {
  1379. $this->client->followRedirects(false);
  1380. }
  1381. /**
  1382. * Enables automatic redirects to be followed by the client
  1383. *
  1384. * ```php
  1385. * <?php
  1386. * $I->startFollowingRedirects();
  1387. * ```
  1388. *
  1389. * @part xml
  1390. * @part json
  1391. */
  1392. public function startFollowingRedirects()
  1393. {
  1394. $this->client->followRedirects(true);
  1395. }
  1396. }