|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\Backend\Test\Mftf\Helper; |
| 9 | + |
| 10 | +use Magento\FunctionalTestingFramework\Helper\Helper; |
| 11 | + |
| 12 | +/** |
| 13 | + * Class for MFTF helpers for curl requests. |
| 14 | + */ |
| 15 | +class CurlHelpers extends Helper |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Assert a that a curl request's response contains an expected string |
| 19 | + * |
| 20 | + * @param string $url |
| 21 | + * @param string $expectedString |
| 22 | + * @param string $postBody |
| 23 | + * @param string $cookieName |
| 24 | + * @return void |
| 25 | + * |
| 26 | + */ |
| 27 | + public function assertCurlResponseContainsString($url, $expectedString, $postBody = null, $cookieName = 'admin'): void |
| 28 | + { |
| 29 | + $cookie = $this->getCookie($cookieName); |
| 30 | + $curlResponse = $this->getCurlResponse($url, $cookie, $postBody); |
| 31 | + $this->assertStringContainsString($expectedString, $curlResponse); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Sends a curl request with the provided URL & cookie. Returns the response |
| 36 | + * |
| 37 | + * @param string $url |
| 38 | + * @param string $cookie |
| 39 | + * @param string $postBody |
| 40 | + * @return string |
| 41 | + * |
| 42 | + */ |
| 43 | + private function getCurlResponse($url, $cookie = null, $postBody = null): string |
| 44 | + { |
| 45 | + // Start Session |
| 46 | + $session = curl_init($url); |
| 47 | + |
| 48 | + // Set Options |
| 49 | + if ($postBody) { |
| 50 | + $data = json_decode($postBody, true); |
| 51 | + curl_setopt($session, CURLOPT_POST, true); |
| 52 | + curl_setopt($session, CURLOPT_POSTFIELDS, $data); |
| 53 | + } |
| 54 | + curl_setopt($session, CURLOPT_COOKIE, $cookie); |
| 55 | + curl_setopt($session, CURLOPT_RETURNTRANSFER, true); |
| 56 | + |
| 57 | + // Execute |
| 58 | + $response = curl_exec($session); |
| 59 | + curl_close($session); |
| 60 | + |
| 61 | + return $response; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Gets the value of the specified cookie and returns the key value pair of the cookie |
| 66 | + * |
| 67 | + * @param string $cookieName |
| 68 | + * @return string |
| 69 | + * |
| 70 | + */ |
| 71 | + private function getCookie($cookieName = 'admin'): string |
| 72 | + { |
| 73 | + try { |
| 74 | + $webDriver = $this->getModule('\Magento\FunctionalTestingFramework\Module\MagentoWebDriver'); |
| 75 | + $cookieValue = $webDriver->grabCookie($cookieName); |
| 76 | + |
| 77 | + return $cookieName . '=' . $cookieValue; |
| 78 | + } catch (\Exception $exception) { |
| 79 | + $this->fail($exception->getMessage()); |
| 80 | + return ''; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments