This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,296 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\GraphQl;
use Magento\TestFramework\TestCase\HttpClient\CurlClient;
use Magento\TestFramework\Helper\JsonSerializer;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Curl client for GraphQL
*/
class Client
{
/**#@+
* GraphQL HTTP method
*/
public const GRAPHQL_METHOD_POST = 'POST';
/**#@-*/
/** @var CurlClient */
private $curlClient;
/** @var JsonSerializer */
private $json;
/**
* @param CurlClient|null $curlClient
* @param JsonSerializer|null $json
*/
public function __construct(
\Magento\TestFramework\TestCase\HttpClient\CurlClient $curlClient = null,
\Magento\TestFramework\Helper\JsonSerializer $json = null
) {
$objectManager = Bootstrap::getObjectManager();
$this->curlClient = $curlClient ?: $objectManager->get(CurlClient::class);
$this->json = $json ?: $objectManager->get(JsonSerializer::class);
}
/**
* Perform HTTP POST request for query
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return array|string|int|float|bool
* @throws \Exception
*/
public function post(string $query, array $variables = [], string $operationName = '', array $headers = [])
{
$url = $this->getEndpointUrl();
$headers = array_merge($headers, ['Accept: application/json', 'Content-Type: application/json']);
$requestArray = [
'query' => $query,
'variables' => !empty($variables) ? $variables : null,
'operationName' => !empty($operationName) ? $operationName : null
];
$postData = $this->json->jsonEncode($requestArray);
try {
$responseBody = $this->curlClient->post($url, $postData, $headers);
} catch (\Exception $e) {
// if response code > 400 then response is the exception message
$responseBody = $e->getMessage();
}
return $this->processResponse($responseBody);
}
/**
* Perform HTTP GET request for query
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return mixed
* @throws \Exception
*/
public function get(string $query, array $variables = [], string $operationName = '', array $headers = [])
{
$url = $this->getEndpointUrl();
$requestArray = [
'query' => $query,
'variables' => $variables ? $this->json->jsonEncode($variables) : null,
'operationName' => $operationName ? $operationName : null
];
array_filter($requestArray);
try {
$responseBody = $this->curlClient->get($url, $requestArray, $headers);
} catch (\Exception $e) {
// if response code > 400 then response is the exception message
$responseBody = $e->getMessage();
}
return $this->processResponse($responseBody);
}
/**
* Process response from GraphQL server.
*
* @param string $response
* @param array $responseHeaders
* @param array $responseCookies
* @return mixed
* @throws \Exception
*/
private function processResponse(string $response, array $responseHeaders = [], array $responseCookies = [])
{
$responseArray = null;
try {
$responseArray = $this->json->jsonDecode($response);
} catch (\Exception $exception) {
// Note: We don't care about this exception because we have error checking bellow if it fails to decode.
}
if (!is_array($responseArray)) {
//phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception('Unknown GraphQL response body: ' . $response);
}
$this->processErrors($responseArray, $responseHeaders, $responseCookies);
if (!isset($responseArray['data'])) {
//phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception('Unknown GraphQL response body: ' . $response);
}
return $responseArray['data'];
}
/**
* Perform HTTP GET request, return response data and headers
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @param bool $flushCookies
*
* @return array
*/
public function getWithResponseHeaders(
string $query,
array $variables = [],
string $operationName = '',
array $headers = [],
bool $flushCookies = false
): array {
$url = $this->getEndpointUrl();
$requestArray = [
'query' => $query,
'variables' => $variables ? $this->json->jsonEncode($variables) : null,
'operationName' => !empty($operationName) ? $operationName : null
];
array_filter($requestArray);
$response = $this->curlClient->getWithFullResponse($url, $requestArray, $headers, $flushCookies);
$responseHeaders = !empty($response['header']) ? $this->processResponseHeaders($response['header']) : [];
$responseCookies = !empty($response['header']) ? $this->processResponseCookies($response['header']) : [];
$responseBody = $this->processResponse($response['body'], $responseHeaders, $responseCookies);
return ['headers' => $responseHeaders, 'body' => $responseBody, 'cookies' => $responseCookies];
}
/**
* Perform HTTP POST request, return response data and headers
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @param bool $flushCookies
*
* @return array
*/
public function postWithResponseHeaders(
string $query,
array $variables = [],
string $operationName = '',
array $headers = [],
bool $flushCookies = false
): array {
$url = $this->getEndpointUrl();
$headers = array_merge($headers, ['Accept: application/json', 'Content-Type: application/json']);
$requestArray = [
'query' => $query,
'variables' => !empty($variables) ? $variables : null,
'operationName' => !empty($operationName) ? $operationName : null
];
$postData = $this->json->jsonEncode($requestArray);
$response = $this->curlClient->postWithFullResponse($url, $postData, $headers, $flushCookies);
$responseHeaders = !empty($response['header']) ? $this->processResponseHeaders($response['header']) : [];
$responseCookies = !empty($response['header']) ? $this->processResponseCookies($response['header']) : [];
$responseBody = $this->processResponse($response['body'], $responseHeaders, $responseCookies);
return ['headers' => $responseHeaders, 'body' => $responseBody, 'cookies' => $responseCookies];
}
/**
* Process errors.
*
* @param array $responseBodyArray
* @param array $responseHeaders
* @param array $responseCookies
* @return void
* @throws ResponseContainsErrorsException
*/
private function processErrors($responseBodyArray, array $responseHeaders = [], array $responseCookies = [])
{
if (isset($responseBodyArray['errors'])) {
$errorMessage = '';
if (is_array($responseBodyArray['errors'])) {
foreach ($responseBodyArray['errors'] as $error) {
if (isset($error['message'])) {
$errorMessage .= $error['message'] . PHP_EOL;
if (isset($error['debugMessage'])) {
$errorMessage .= $error['debugMessage'] . PHP_EOL;
}
}
if (isset($error['trace'])) {
$traceString = $error['trace'];
TestCase::assertNotEmpty($traceString, "trace is empty");
}
}
throw new ResponseContainsErrorsException(
'GraphQL response contains errors: ' . $errorMessage . "\n" . var_export($responseBodyArray, true),
$responseBodyArray,
null,
0,
$responseHeaders,
$responseCookies
);
}
//phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception('GraphQL responded with an unknown error: ' . json_encode($responseBodyArray));
}
}
/**
* Get endpoint url
*
* @return string resource URL
* @throws \Exception
*/
public function getEndpointUrl()
{
return rtrim(TESTS_BASE_URL, '/') . '/graphql';
}
/**
* Parse response headers into associative array
*
* @param string $headers
* @return array
*/
private function processResponseHeaders(string $headers): array
{
$headersArray = [];
$headerLines = preg_split('/((\r?\n)|(\r\n?))/', $headers);
foreach ($headerLines as $headerLine) {
$headerParts = preg_split('/: /', $headerLine, 2);
if (count($headerParts) == 2) {
$headersArray[trim($headerParts[0])] = trim($headerParts[1]);
} elseif (preg_match('/HTTP\/[\.0-9]+/', $headerLine)) {
$headersArray[trim('Status-Line')] = trim($headerLine);
}
}
return $headersArray;
}
/**
* Prepare separate array of cookies.
*
* @param string $headers
* @return array
*/
private function processResponseCookies(string $headers): array
{
$cookiesArray = [];
$headers = preg_split('/((\r?\n)|(\r\n?))/', $headers);
foreach ($headers as $header) {
if (strpos($header, 'Set-Cookie:') === 0) {
$cookie = preg_split('/: /', $header, 2);
if (isset($cookie[1]) && !empty($cookie[1])) {
$cookiesArray[] = $cookie[1];
}
}
}
return $cookiesArray;
}
}
@@ -0,0 +1,229 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\TestCase\GraphQl;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\ObjectManager\ConfigLoader;
use Magento\Framework\ObjectManagerInterface;
use Magento\GraphQl\Model\Query\ContextFactory;
use Magento\GraphQlResolverCache\Model\Resolver\Result\Type as GraphQlResolverCache;
use Magento\PageCache\Model\Cache\Type as FullPageCache;
use Magento\TestFramework\App\State;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ResolverCacheAbstract extends GraphQlAbstract
{
/**
* @var bool
*/
private $isOriginalResolverCacheEnabled;
/**
* @var bool
*/
private $resolverCacheStatusChanged = false;
/**
* @var bool
*/
private $isOriginalFullPageCacheEnabled;
/**
* @var bool
*/
private $fullPageCacheStatusChanged = false;
/**
* @var string
*/
private $initialAppArea;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
// test has to be executed in graphql area
$configLoader = $this->objectManager->get(ConfigLoader::class);
/** @var State $appArea */
$appArea = $this->objectManager->get(State::class);
$this->initialAppArea = $appArea->getAreaCode();
$this->objectManager->configure($configLoader->load(Area::AREA_GRAPHQL));
$this->mockGuestUserInfoContext();
// Enable GraphQL resolver cache
$this->isOriginalResolverCacheEnabled = $this->isCacheEnabled(GraphQlResolverCache::TYPE_IDENTIFIER);
if (!$this->isOriginalResolverCacheEnabled) {
$this->resolverCacheStatusChanged = true;
$this->setCacheTypeStatusEnabled(GraphQlResolverCache::TYPE_IDENTIFIER, true);
}
// Disable full page cache
$this->isOriginalFullPageCacheEnabled = $this->isCacheEnabled(FullPageCache::TYPE_IDENTIFIER);
if ($this->isOriginalFullPageCacheEnabled) {
$this->fullPageCacheStatusChanged = true;
$this->setCacheTypeStatusEnabled(FullPageCache::TYPE_IDENTIFIER, false);
}
parent::setUp();
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
// clean graphql resolver cache and reset to original enablement status
$this->cleanCacheType(GraphQlResolverCache::TYPE_IDENTIFIER);
if ($this->resolverCacheStatusChanged) {
$this->setCacheTypeStatusEnabled(
GraphQlResolverCache::TYPE_IDENTIFIER,
$this->isOriginalResolverCacheEnabled
);
$this->resolverCacheStatusChanged = false;
}
// Reset to original full page cache enablement status
if ($this->fullPageCacheStatusChanged) {
$this->setCacheTypeStatusEnabled(
FullPageCache::TYPE_IDENTIFIER,
$this->isOriginalFullPageCacheEnabled
);
$this->fullPageCacheStatusChanged = false;
}
/** @var ConfigLoader $configLoader */
$configLoader = $this->objectManager->get(ConfigLoader::class);
$this->objectManager->configure($configLoader->load($this->initialAppArea));
$this->objectManager->removeSharedInstance(ContextFactory::class);
$this->objectManager->removeSharedInstance(\Magento\GraphQl\Model\Query\Context::class);
$this->objectManager->removeSharedInstance(\Magento\GraphQl\Model\Query\ContextInterface::class);
parent::tearDown();
}
/**
* Initialize test-scoped user context with $customer
*
* @param CustomerInterface $customer
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function mockCustomerUserInfoContext(CustomerInterface $customer)
{
$userContextMock = $this->getMockBuilder(UserContextInterface::class)
->onlyMethods(['getUserId', 'getUserType'])
->disableOriginalConstructor()
->getMock();
$userContextMock->expects($this->any())
->method('getUserId')
->willReturn($customer->getId());
$userContextMock->expects($this->any())
->method('getUserType')
->willReturn(UserContextInterface::USER_TYPE_CUSTOMER);
/** @var ContextFactory $contextFactory */
$contextFactory = $this->objectManager->get(ContextFactory::class);
$contextFactory->create($userContextMock);
}
/**
* Reset test-scoped user context to guest.
*
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function mockGuestUserInfoContext()
{
$userContextMock = $this->getMockBuilder(UserContextInterface::class)
->onlyMethods(['getUserId', 'getUserType'])
->disableOriginalConstructor()
->getMock();
$userContextMock->expects($this->any())
->method('getUserId')
->willReturn(0);
$userContextMock->expects($this->any())
->method('getUserType')
->willReturn(UserContextInterface::USER_TYPE_GUEST);
// test has to be executed in graphql area
$configLoader = $this->objectManager->get(ConfigLoader::class);
$this->objectManager->configure($configLoader->load(Area::AREA_GRAPHQL));
/** @var ContextFactory $contextFactory */
$contextFactory = $this->objectManager->get(ContextFactory::class);
$contextFactory->create($userContextMock);
}
/**
* Get cache status of the given cache type.
*
* @param string $cacheType
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isCacheEnabled(string $cacheType): bool
{
$appDir = dirname(Bootstrap::getInstance()->getAppTempDir());
$out = '';
// phpcs:ignore Magento2.Security.InsecureFunction
exec("php -f {$appDir}/bin/magento cache:status", $out);
$cacheStatus = implode('| ', $out);
preg_match("/(?<cache_type>$cacheType): (?<enabled>\d+)/", $cacheStatus, $matches);
return !empty($matches) && array_key_exists('enabled', $matches) && $matches['enabled'];
}
/**
* Set cache type status.
*
* @param string $cacheType
* @param bool $enable
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function setCacheTypeStatusEnabled(string $cacheType, bool $enable): void
{
$appDir = dirname(Bootstrap::getInstance()->getAppTempDir());
$out = '';
if ($enable) {
// phpcs:ignore Magento2.Security.InsecureFunction
exec("php -f {$appDir}/bin/magento cache:enable $cacheType", $out);
} else {
// phpcs:ignore Magento2.Security.InsecureFunction
exec("php -f {$appDir}/bin/magento cache:disable $cacheType", $out);
}
}
/**
* Clean given cache type.
*
* @param string $cacheType
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function cleanCacheType(string $cacheType): void
{
$appDir = dirname(Bootstrap::getInstance()->getAppTempDir());
$out = '';
// phpcs:ignore Magento2.Security.InsecureFunction
exec("php -f {$appDir}/bin/magento cache:clean $cacheType", $out);
}
}
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\TestCase\GraphQl;
/**
* Exception thrown when GraphQL response contains errors.
*/
class ResponseContainsErrorsException extends \Exception
{
/**
* @var array
*/
private $responseData;
/**
* @var array
*/
private $responseHeaders;
/**
* @var array
*/
private $responseCookies;
/**
* @param string $message
* @param array $responseData
* @param \Exception|null $cause
* @param int $code
* @param array $responseHeaders
* @param array $responseCookies
*/
public function __construct(
string $message,
array $responseData,
\Exception $cause = null,
int $code = 0,
array $responseHeaders = [],
array $responseCookies = []
) {
parent::__construct($message, $code, $cause);
$this->responseData = $responseData;
$this->responseHeaders = $responseHeaders;
$this->responseCookies = $responseCookies;
}
/**
* Get response data
*
* @return array
*/
public function getResponseData(): array
{
return $this->responseData;
}
/**
* Get response headers
*
* @return array
*/
public function getResponseHeaders(): array
{
return $this->responseHeaders;
}
/**
* Get response cookies
*
* @return array
*/
public function getResponseCookies(): array
{
return $this->responseCookies;
}
}
@@ -0,0 +1,223 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test case for Web API functional tests for Graphql.
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/
abstract class GraphQlAbstract extends WebapiAbstract
{
/**
* The instantiated GraphQL client.
*
* @var \Magento\TestFramework\TestCase\GraphQl\Client
*/
private $graphQlClient;
/**
* @var \Magento\Framework\App\Cache
*/
private $appCache;
/**
* Perform GraphQL query call via GET to the system under test.
*
* @see \Magento\TestFramework\TestCase\GraphQl\Client::call()
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return array|int|string|float|bool GraphQL call results
* @throws \Exception
*/
public function graphQlQuery(
string $query,
array $variables = [],
string $operationName = '',
array $headers = []
) {
return $this->getGraphQlClient()->get(
$query,
$variables,
$operationName,
$this->composeHeaders($headers)
);
}
/**
* Perform GraphQL mutations call via POST to the system under test.
*
* @see \Magento\TestFramework\TestCase\GraphQl\Client::call()
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return array|int|string|float|bool GraphQL call results
* @throws \Exception
*/
public function graphQlMutation(
string $query,
array $variables = [],
string $operationName = '',
array $headers = []
) {
return $this->getGraphQlClient()->post(
$query,
$variables,
$operationName,
$this->composeHeaders($headers)
);
}
/**
* Perform GraphQL query via GET and returns only the response headers
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return array
*/
public function graphQlQueryWithResponseHeaders(
string $query,
array $variables = [],
string $operationName = '',
array $headers = []
): array {
return $this->getGraphQlClient()->getWithResponseHeaders(
$query,
$variables,
$operationName,
$this->composeHeaders($headers)
);
}
/**
* Perform GraphQL query via POST and returns the response headers
*
* @param string $query
* @param array $variables
* @param string $operationName
* @param array $headers
* @return array
*/
public function graphQlMutationWithResponseHeaders(
string $query,
array $variables = [],
string $operationName = '',
array $headers = []
): array {
return $this->getGraphQlClient()->postWithResponseHeaders(
$query,
$variables,
$operationName,
$this->composeHeaders($headers)
);
}
/**
* Compose headers
*
* @param array $headers
* @return string[]
*/
private function composeHeaders(array $headers): array
{
$headersArray = [];
foreach ($headers as $key => $value) {
$headersArray[] = sprintf('%s: %s', $key, $value);
}
return $headersArray;
}
/**
* Clear cache so integration test can alter cached GraphQL schema
*
* @return bool
*/
protected function cleanCache()
{
return $this->getAppCache()->clean(\Magento\Framework\App\Config::CACHE_TAG);
}
/**
* Return app cache setup.
*
* @return \Magento\Framework\App\Cache
*/
private function getAppCache()
{
if (null === $this->appCache) {
$this->appCache = Bootstrap::getObjectManager()->get(\Magento\Framework\App\Cache::class);
}
return $this->appCache;
}
/**
* Get GraphQL adapter (create if requested one does not exist).
*
* @return \Magento\TestFramework\TestCase\GraphQl\Client
*/
private function getGraphQlClient()
{
if ($this->graphQlClient === null) {
$this->graphQlClient = Bootstrap::getObjectManager()->get(
\Magento\TestFramework\TestCase\GraphQl\Client::class
);
}
return $this->graphQlClient;
}
/**
* Compare actual response fields with expected
*
* @param array $actualResponse
* @param array $assertionMap ['response_field_name' => 'response_field_value', ...]
* OR [['response_field' => $field, 'expected_value' => $value], ...]
*/
protected function assertResponseFields($actualResponse, $assertionMap)
{
foreach ($assertionMap as $key => $assertionData) {
$expectedValue = isset($assertionData['expected_value'])
? $assertionData['expected_value']
: $assertionData;
$responseField = isset($assertionData['response_field']) ? $assertionData['response_field'] : $key;
self::assertNotNull(
$expectedValue,
"Value of '{$responseField}' field must not be NULL"
);
self::assertArrayHasKey(
$responseField,
$actualResponse,
"Response array does not contain key '{$responseField}'"
);
self::assertEquals(
$expectedValue,
$actualResponse[$responseField],
"Value of '{$responseField}' field in response does not match expected value: "
. var_export($expectedValue, true)
);
}
}
/**
* Tear down test and flush page cache
*
* @return void
*/
protected function tearDown(): void
{
parent::tearDown();
$appDir = dirname(Bootstrap::getInstance()->getAppTempDir());
$out = '';
// phpcs:ignore Magento2.Security.InsecureFunction
exec("php -f {$appDir}/bin/magento cache:flush full_page", $out);
}
}
@@ -0,0 +1,231 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\HttpClient;
/**
* Generic cURL client wrapper for get/delete/post/put requests
*/
class CurlClient
{
public const EMPTY_REQUEST_BODY = 'Empty body';
/**
* Perform HTTP GET request
*
* @param string $url Resource URL like /V1/Resource1/123
* @param array $data
* @param array $headers
* @return string
*/
public function get($url, $data = [], $headers = [])
{
if (!empty($data)) {
$url .= '?' . http_build_query($data);
}
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET;
$resp = $this->invokeApi($url, $curlOpts, $headers);
return $resp["body"];
}
/**
* Perform a HTTP GET request and return the full response
*
* @param string $url
* @param array $data
* @param array $headers
* @param bool $flushCookies
* @return array
*/
public function getWithFullResponse($url, $data = [], $headers = [], $flushCookies = false): array
{
if (!empty($data)) {
$url .= '?' . http_build_query($data);
}
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET;
if ($flushCookies) {
$curlOpts[CURLOPT_COOKIELIST] = 'ALL';
}
return $this->invokeApi($url, $curlOpts, $headers);
}
/**
* Perform a HTTP POST request and return the full response
*
* @param string $url
* @param array|string $data
* @param array $headers
* @param bool $flushCookies
* @return array
*/
public function postWithFullResponse($url, $data, $headers = [], $flushCookies = false): array
{
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST;
$headers[] = 'Content-Length: ' . strlen($data);
$curlOpts[CURLOPT_POSTFIELDS] = $data;
if ($flushCookies) {
$curlOpts[CURLOPT_COOKIELIST] = 'ALL';
}
return $this->invokeApi($url, $curlOpts, $headers);
}
/**
* Perform HTTP DELETE request
*
* @param string $url
* @param array $headers
* @return string
*/
public function delete($url, $headers = [])
{
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE;
$resp = $this->invokeApi($url, $curlOpts, $headers);
return $resp["body"];
}
/**
* Perform HTTP POST request
*
* @param string $url
* @param array|string $data
* @param array $headers
* @return string
*/
public function post($url, $data, $headers = [])
{
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST;
$headers[] = 'Content-Length: ' . strlen($data);
$curlOpts[CURLOPT_POSTFIELDS] = $data;
$resp = $this->invokeApi($url, $curlOpts, $headers);
return $resp["body"];
}
/**
* Perform HTTP PUT request
*
* @param string $url
* @param array|string $data
* @param array $headers
* @return string
*/
public function put($url, $data, $headers = [])
{
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT;
$headers[] = 'Content-Length: ' . strlen($data);
$curlOpts[CURLOPT_POSTFIELDS] = $data;
$resp = $this->invokeApi($url, $curlOpts, $headers);
return $resp["body"];
}
/**
* Makes the REST api call using passed $curl object
*
* @param string $url
* @param array $additionalCurlOpts cURL Options
* @param array $headers
* @return array
* @throws \Exception
*/
public function invokeApi($url, $additionalCurlOpts, $headers = [])
{
// initialize cURL
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$curl = curl_init($url);
if ($curl === false) {
// phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception("Error Initializing cURL for baseUrl: " . $url);
}
// get cURL options
$curlOpts = $this->getCurlOptions($additionalCurlOpts, $headers);
// add CURL opts
foreach ($curlOpts as $opt => $val) {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
curl_setopt($curl, $opt, $val);
}
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$response = curl_exec($curl);
if ($response === false) {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$error = curl_error($curl);
// phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception($error);
}
$resp = [];
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$resp["header"] = substr($response, 0, $headerSize);
$resp["body"] = substr($response, $headerSize);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$resp["meta"] = curl_getinfo($curl);
if ($resp["meta"] === false) {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$error = curl_error($curl);
// phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception($error);
}
// phpcs:ignore Magento2.Functions.DiscouragedFunction
curl_close($curl);
$meta = $resp["meta"];
if ($meta && $meta['http_code'] >= 400) {
// phpcs:ignore Magento2.Exceptions.DirectThrow
throw new \Exception($resp["body"], $meta['http_code']);
}
return $resp;
}
/**
* Constructs and returns a curl options array
*
* @param array $customCurlOpts Additional / overridden cURL options
* @param array $headers
* @return array
*/
private function getCurlOptions($customCurlOpts = [], $headers = [])
{
// default curl options
$curlOpts = [
CURLOPT_RETURNTRANSFER => true, // return result instead of echoing
CURLOPT_SSL_VERIFYPEER => false, // stop cURL from verifying the peer's certificate
CURLOPT_FOLLOWLOCATION => false, // follow redirects, Location: headers
CURLOPT_MAXREDIRS => 10, // but don't redirect more than 10 times
CURLOPT_HTTPHEADER => [],
CURLOPT_HEADER => 1,
];
// merge headers
$headers = array_merge($curlOpts[CURLOPT_HTTPHEADER], $headers);
if (TESTS_XDEBUG_ENABLED) {
$headers[] = 'Cookie: XDEBUG_SESSION=' . TESTS_XDEBUG_SESSION;
}
$curlOpts[CURLOPT_HTTPHEADER] = $headers;
// merge custom Curl Options & return
foreach ($customCurlOpts as $opt => $val) {
$curlOpts[$opt] = $val;
}
return $curlOpts;
}
}
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\HttpClient;
use Magento\TestFramework\Helper\JsonSerializer;
use Magento\TestFramework\Helper\Bootstrap;
/**
* A Curl client that can be called independently, outside of any Web API controller used by CookieManager tests.
*/
class CurlClientWithCookies
{
const COOKIE_HEADER = 'Set-Cookie: ';
/** @var CurlClient */
protected $curlClient;
/** @var JsonSerializer */
protected $jsonSerializer;
/**
* @param CurlClient $curlClient
* @param \Magento\TestFramework\Helper\JsonSerializer $jsonSerializer
*/
public function __construct(
CurlClient $curlClient,
\Magento\TestFramework\Helper\JsonSerializer $jsonSerializer
) {
$objectManager = Bootstrap::getObjectManager();
$this->curlClient = $curlClient ? : $objectManager->get(CurlClient::class);
$this->jsonSerializer = $jsonSerializer ? : $objectManager->get(JsonSerializer::class);
}
/**
* Compose the resource url
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @return string resource URL
* @throws \Exception
*/
public function constructResourceUrl($resourcePath)
{
return rtrim(TESTS_BASE_URL, '/') . '/' . ltrim($resourcePath, '/');
}
/**
* Perform HTTP GET request
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @param array $data
* @param array $headers
* @return array
*/
public function get($resourcePath, $data = [], $headers = [])
{
$url = $this->constructResourceUrl($resourcePath);
if (!empty($data)) {
$url .= '?' . http_build_query($data);
}
$curlOpts = [];
$curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET;
$curlOpts[CURLOPT_SSLVERSION] = 3;
$response = $this->curlClient->invokeApi($url, $curlOpts, $headers);
$response['cookies'] = $this->cookieParse($response['header']);
return $response;
}
/**
* Takes a string in the form of an HTTP header block, returns cookie data.
*
* Return array is in the form of:
* [
* [
* 'name' = <cookie_name>,
* 'value' = <cookie_value>,
* <cookie_metadata_name> => <cookie_metadata_value> || 'true'
* ],
* ]
*
* @param string $headerBlock
* @return array
*/
private function cookieParse($headerBlock)
{
$header = explode("\r\n", $headerBlock);
$cookies = [];
foreach ($header as $line) {
$line = trim($line);
if (substr($line, 0, strlen(self::COOKIE_HEADER)) == self::COOKIE_HEADER) {
$line = trim(substr($line, strlen(self::COOKIE_HEADER)));
$cookieData = [];
// Check if cookie contains attributes
if (strpos($line, ';') === false) {
// no attributes, just name and value
list($cookieData['name'], $cookieData['value']) = explode('=', $line);
} else {
// has attributes, must parse them out and loop through
list($nvPair, $cookieMetadata) = explode(';', $line, 2);
list($cookieData['name'], $cookieData['value']) = explode('=', $nvPair);
$rawCookieData = explode(';', $cookieMetadata);
foreach ($rawCookieData as $keyValuePairs) {
list($key, $value) = array_merge(explode('=', $keyValuePairs), ['true']);
$cookieData[strtolower(trim($key))] = trim($value);
}
}
$cookies[] = $cookieData;
}
}
return $cookies;
}
}
@@ -0,0 +1,158 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\Webapi\Adapter;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\Authentication\OauthHelper;
/**
* Test client for REST API testing.
*/
class Rest implements \Magento\TestFramework\TestCase\Webapi\AdapterInterface
{
/** @var \Magento\Webapi\Model\Config */
protected $_config;
/** @var \Magento\Integration\Model\Oauth\Consumer */
protected static $_consumer;
/** @var \Magento\Integration\Model\Oauth\Token */
protected static $_token;
/** @var string */
protected static $_consumerKey;
/** @var string */
protected static $_consumerSecret;
/** @var string */
protected static $_verifier;
/** @var \Magento\TestFramework\TestCase\Webapi\Adapter\Rest\RestClient */
protected $restClient;
/** @var \Magento\TestFramework\TestCase\Webapi\Adapter\Rest\DocumentationGenerator */
protected $documentationGenerator;
/** @var string */
protected $defaultStoreCode;
/**
* Initialize dependencies.
*/
public function __construct()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = Bootstrap::getObjectManager();
$this->_config = $objectManager->get(\Magento\Webapi\Model\Config::class);
$this->restClient = $objectManager->get(\Magento\TestFramework\TestCase\Webapi\Adapter\Rest\RestClient::class);
$this->documentationGenerator = $objectManager->get(
\Magento\TestFramework\TestCase\Webapi\Adapter\Rest\DocumentationGenerator::class
);
$this->defaultStoreCode = Bootstrap::getObjectManager()
->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore()
->getCode();
}
/**
* @inheritdoc
*
* @throws \LogicException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function call($serviceInfo, $arguments = [], $storeCode = null, $integration = null)
{
$storeCode = $storeCode !== null ? (string)$storeCode : $this->defaultStoreCode;
$resourcePath = '/' . $storeCode . $this->_getRestResourcePath($serviceInfo);
$httpMethod = $this->_getRestHttpMethod($serviceInfo);
//Get a valid token
$accessCredentials = OauthHelper::getApiAccessCredentials(null, $integration);
/** @var $oAuthClient \Magento\TestFramework\Authentication\Rest\OauthClient */
$oAuthClient = $accessCredentials['oauth_client'];
$urlFormEncoded = false;
// we're always using JSON
$authHeader = [];
$restServiceInfo = $serviceInfo['rest'];
$additionalHeaders = $restServiceInfo['headers'] ?? [];
if (array_key_exists('token', $restServiceInfo)) {
$authHeader = $oAuthClient->buildBearerTokenAuthorizationHeader($restServiceInfo['token']);
} else {
$authHeader = $oAuthClient->buildOauthAuthorizationHeader(
$this->restClient->constructResourceUrl($resourcePath),
$accessCredentials['key'],
$accessCredentials['secret'],
($httpMethod == 'PUT' || $httpMethod == 'POST') && $urlFormEncoded ? $arguments : [],
$httpMethod
);
}
$authHeader = array_merge(
$authHeader,
['Accept: application/json', 'Content-Type: application/json'],
$additionalHeaders
);
switch ($httpMethod) {
case Request::HTTP_METHOD_GET:
$response = $this->restClient->get($resourcePath, [], $authHeader);
break;
case Request::HTTP_METHOD_POST:
$response = $this->restClient->post($resourcePath, $arguments, $authHeader);
break;
case Request::HTTP_METHOD_PUT:
$response = $this->restClient->put($resourcePath, $arguments, $authHeader);
break;
case Request::HTTP_METHOD_DELETE:
$response = $this->restClient->delete($resourcePath, $authHeader);
break;
default:
throw new \LogicException("HTTP method '{$httpMethod}' is not supported.");
}
if (defined('GENERATE_REST_DOCUMENTATION') && GENERATE_REST_DOCUMENTATION) {
$this->documentationGenerator->generateDocumentation($httpMethod, $resourcePath, $arguments, $response);
}
return $response;
}
/**
* Retrieve REST endpoint from $serviceInfo array and return it to the caller.
*
* @param array $serviceInfo
* @return string
* @throws \Exception
*/
protected function _getRestResourcePath($serviceInfo)
{
if (isset($serviceInfo['rest']['resourcePath'])) {
$resourcePath = $serviceInfo['rest']['resourcePath'];
}
if (!isset($resourcePath)) {
throw new \Exception("REST endpoint cannot be identified.");
}
return $resourcePath;
}
/**
* Retrieve HTTP method to be used in REST request.
*
* @param array $serviceInfo
* @return string
* @throws \Exception
*/
protected function _getRestHttpMethod($serviceInfo)
{
if (isset($serviceInfo['rest']['httpMethod'])) {
$httpMethod = $serviceInfo['rest']['httpMethod'];
}
if (!isset($httpMethod)) {
throw new \Exception("REST HTTP method cannot be identified.");
}
return $httpMethod;
}
}
@@ -0,0 +1,239 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\Webapi\Adapter\Rest;
/**
* Generator for documentation
*
*/
class DocumentationGenerator
{
/**
* Generate documentation based on request-response data during REST requests.
*
* @param string $httpMethod
* @param string $resourcePath
* @param array $arguments
* @param array $response
*/
public function generateDocumentation($httpMethod, $resourcePath, $arguments, $response)
{
$content = $this->generateHtmlContent($httpMethod, $resourcePath, $arguments, $response);
$filePath = $this->generateFileName();
if ($filePath === null) {
return;
}
if (!is_writable(dirname($filePath))) {
throw new \RuntimeException('Cannot write to documentation directory.');
} elseif (file_exists($filePath)) {
$fileContent = file_get_contents($filePath);
$endHtml = $this->generateHtmlFooter();
$fileContent = str_replace($endHtml, '', $fileContent);
$content = "{$fileContent}{$content}";
unlink($filePath);
file_put_contents($filePath, $content, FILE_APPEND);
} else {
file_put_contents($filePath, $content, FILE_APPEND);
}
}
/**
* Prepare HTML for the generated documentation.
*
* @param string $httpMethod
* @param string $resourcePath
* @param array $arguments
* @param array $response
* @return string
*/
protected function generateHtmlContent($httpMethod, $resourcePath, $arguments, $response)
{
if (empty($arguments)) {
$arguments = 'This call does not accept a request body.';
$requestParametersHtml = '';
} else {
$requestParameters = $this->retrieveParametersAsHtml($arguments);
$arguments = json_encode($arguments, JSON_PRETTY_PRINT);
$requestParametersHtml = <<<HTML
<table class="docutils field-list" frame="void" rules="none" width="400">
<colgroup>
<col width="35%" class="field-name">
<col width="65%" class="field-body">
</colgroup>
<tbody valign="top">
<tr class="field-odd field">
<th class="field-name">Request parameters:</th>
<td class="field-body">
<ul class="first last simple">
{$requestParameters}
</ul>
</td>
</tr>
</tbody>
</table>
HTML;
}
if (is_array($response)) {
$responseArrayKeys = array_keys($response);
$responseParameters = "Parameters should be specified manually.";
foreach ($responseArrayKeys as $key) {
if (!is_int($key)) {
$responseParameters = '';
break;
}
}
}
if (empty($responseParameters)) {
$responseParameters = $this->retrieveParametersAsHtml($response);
}
$response = json_encode($response, JSON_PRETTY_PRINT);
$responseParametersHtml = <<<HTML
<table class="docutils field-list" frame="void" rules="none" width="400">
<colgroup>
<col width="35%" class="field-name">
<col width="65%" class="field-body">
</colgroup>
<tbody valign="top">
<tr class="field-odd field">
<th class="field-name">Response attributes:</th>
<td class="field-body">
<ul class="first last simple">
{$responseParameters}
</ul>
</td>
</tr>
</tbody>
</table>
HTML;
$resourcePath = urldecode($resourcePath);
$resource = str_replace('/', '-', preg_replace('#/\w*/V\d+/(.*)#', '${1}', $resourcePath));
$lowerCaseResource = strtolower($resource);
$lowerCaseMethod = strtolower($httpMethod);
$beginningHtml = <<<HTML
<div class="col-xs-9" role="main">
<div class="bs-docs-section">
HTML;
$headingHtml = <<<HTML
<h2 class="api2" id="$lowerCaseResource">$resource</h2>
<h3 class="api3" id="$lowerCaseMethod-$lowerCaseResource">$httpMethod $resourcePath</h3>
<h4 class="api4">Request</h4>
HTML;
$responseHtml = <<<HTML
<h4 class="api4" id=”$lowerCaseResource-response>Response</h4>
HTML;
$requestResponseParametersHtml = <<<HTML
<h3 class="api3" id="$lowerCaseResource-parameters">Request and response parameters</h3>
HTML;
$endHtml = $this->generateHtmlFooter();
$content = "{$beginningHtml}{$headingHtml}<pre>{$arguments}</pre>{$responseHtml}<pre>{$response}"
. "</pre>{$requestResponseParametersHtml}{$requestParametersHtml}{$responseParametersHtml}{$endHtml}";
return $content;
}
/**
* Generate the end html text;
*
* @return string
*/
protected function generateHtmlFooter()
{
$endHtml = <<<HTML
<h3 class="api3" id="products-responses">Response codes</h3>
<table class="docutils field-list" frame="void" rules="none" width="400">
<colgroup>
<col width="35%" class="field-name">
<col width="65%" class="field-body">
</colgroup>
<tbody valign="top">
<tr class="field-odd field">
<th class="field-name">Normal response codes:</th>
<td class="field-body">
<ul class="first last simple">
<li><strong>SUCCESS_CODE</strong> - SUCCESS_DESCRIPTION</li>
</ul>
</td>
</tr>
</tbody>
</table>
<table class="docutils field-list" frame="void" rules="none" width="400">
<colgroup>
<col width="35%" class="field-name">
<col width="65%" class="field-body">
</colgroup>
<tbody valign="top">
<tr class="field-odd field">
<th class="field-name">Error response codes:</th>
<td class="field-body">
<ul class="first last simple">
<li><strong>ERROR_CODE</strong> - ERROR_DESCRIPTION</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
HTML;
return $endHtml;
}
/**
* Generate a name of file
*
* @return string|null
* @throws \RuntimeException
*/
protected function generateFileName()
{
$varDir = realpath(__DIR__ . '/../../../../../../..') . '/var';
$documentationDir = $varDir . '/log/rest-documentation/';
$debugBackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$pathToFile = $documentationDir;
$fileName = null;
foreach ($debugBackTrace as $traceItem) {
/** Test invocation trace item is the only item which has 3 elements, other trace items have 5 elements */
if (count($traceItem) == 3) {
/** Remove 'test' prefix from method name, e.g. testCreate => create */
$fileName = lcfirst(substr($traceItem['function'], 4));
/** Remove 'Test' suffix from test class name */
$pathToFile .= str_replace('\\', '/', substr($traceItem['class'], 0, -4)) . '/';
break;
}
}
if (!file_exists($pathToFile)) {
if (!mkdir($pathToFile, 0755, true)) {
throw new \RuntimeException('Unable to create missing directory for REST documentation generation');
}
}
if ($fileName !== null) {
$filePath = $pathToFile . $fileName . '.html';
return $filePath;
}
return null;
}
/**
* Retrieve parameters of response/request
*
* @param array|string $parameters
* @return string
*/
protected function retrieveParametersAsHtml($parameters)
{
$parametersAsHtml = '';
if (is_array($parameters)) {
foreach (array_keys($parameters) as $parameter) {
$parametersAsHtml = $parametersAsHtml . '<li><strong>' . $parameter .
'</strong> (<em>Change type manually!</em>) TBD.</li>';
}
} else {
$parametersAsHtml = '<li><strong>' . 'scalar_value' .
'</strong> (<em>Change type manually!</em>) TBD.</li>';
}
return $parametersAsHtml;
}
}
@@ -0,0 +1,133 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\Webapi\Adapter\Rest;
use Magento\TestFramework\TestCase\HttpClient\CurlClient;
use Magento\TestFramework\Helper\JsonSerializer;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Client for invoking REST API
*/
class RestClient
{
const EMPTY_REQUEST_BODY = 'Empty body';
/**
* @var string REST URL base path
*/
private $restBasePath = '/rest/';
/** @var CurlClient */
private $curlClient;
/** @var JsonSerializer */
private $jsonSerializer;
/**
* CurlClient constructor.
*
* @param CurlClient|null $curlClient
* @param JsonSerializer|null $jsonSerializer
*/
public function __construct(
\Magento\TestFramework\TestCase\HttpClient\CurlClient $curlClient = null,
\Magento\TestFramework\Helper\JsonSerializer $jsonSerializer = null
) {
$objectManager = Bootstrap::getObjectManager();
$this->curlClient = $curlClient ? : $objectManager->get(CurlClient::class);
$this->jsonSerializer = $jsonSerializer ? : $objectManager->get(JsonSerializer::class);
}
/**
* Perform HTTP GET request
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @param array $data
* @param array $headers
* @return mixed
*/
public function get($resourcePath, $data = [], $headers = [])
{
$url = $this->constructResourceUrl($resourcePath);
if (!empty($data)) {
$url .= '?' . http_build_query($data);
}
$responseBody = $this->curlClient->get($url, $data, $headers);
return $this->jsonSerializer->jsonDecode($responseBody);
}
/**
* Perform HTTP POST request
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @param array $data
* @param array $headers
* @return mixed
*/
public function post($resourcePath, $data, $headers = [])
{
$url = $this->constructResourceUrl($resourcePath);
if (in_array("Content-Type: application/json", $headers)) {
// json encode data
if ($data != self::EMPTY_REQUEST_BODY) {
$data = $this->jsonSerializer->jsonEncode($data);
} else {
$data = '';
}
}
$responseBody = $this->curlClient->post($url, $data, $headers);
return $this->jsonSerializer->jsonDecode($responseBody);
}
/**
* Perform HTTP PUT request
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @param array $data
* @param array $headers
* @return mixed
*/
public function put($resourcePath, $data, $headers = [])
{
$url = $this->constructResourceUrl($resourcePath);
if (in_array("Content-Type: application/json", $headers)) {
// json encode data
if ($data != self::EMPTY_REQUEST_BODY) {
$data = $this->jsonSerializer->jsonEncode($data);
} else {
$data = '';
}
}
$responseBody = $this->curlClient->put($url, $data, $headers);
return $this->jsonSerializer->jsonDecode($responseBody);
}
/**
* Perform HTTP DELETE request
*
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @param array $headers
* @return mixed
*/
public function delete($resourcePath, $headers = [])
{
$url = $this->constructResourceUrl($resourcePath);
$responseBody = $this->curlClient->delete($url, $headers);
return $this->jsonSerializer->jsonDecode($responseBody);
}
/**
* @param string $resourcePath Resource URL like /V1/Resource1/123
* @return string resource URL
* @throws \Exception
*/
public function constructResourceUrl($resourcePath)
{
return rtrim(TESTS_BASE_URL, '/') . $this->restBasePath . ltrim($resourcePath, '/');
}
}
@@ -0,0 +1,257 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\Webapi\Adapter;
use Magento\Framework\Api\SimpleDataObjectConverter;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Webapi\Controller\Soap\Request\Handler as SoapHandler;
/**
* Test client for SOAP API testing.
*/
class Soap implements \Magento\TestFramework\TestCase\Webapi\AdapterInterface
{
const WSDL_BASE_PATH = '/soap';
/**
* SOAP client initialized with different WSDLs.
*
* @var \Laminas\Soap\Client[]
*/
protected $_soapClients = ['custom' => [], 'default' => []];
/**
* @var \Magento\Webapi\Model\Soap\Config
*/
protected $_soapConfig;
/**
* @var SimpleDataObjectConverter
*/
protected $_converter;
/**
* Initialize dependencies.
*/
public function __construct()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = Bootstrap::getObjectManager();
$this->_soapConfig = $objectManager->get(\Magento\Webapi\Model\Soap\Config::class);
$this->_converter = $objectManager->get(\Magento\Framework\Api\SimpleDataObjectConverter::class);
ini_set('default_socket_timeout', 120);
}
/**
* @inheritdoc
*/
public function call($serviceInfo, $arguments = [], $storeCode = null, $integration = null)
{
$soapOperation = $this->_getSoapOperation($serviceInfo);
$arguments = $this->_converter->convertKeysToCamelCase($arguments);
$soapResponse = $this->_getSoapClient($serviceInfo, $storeCode)->$soapOperation($arguments);
//Convert to snake case for tests to use same assertion data for both SOAP and REST tests
$result = (is_array($soapResponse) || is_object($soapResponse))
? $this->toSnakeCase($this->_converter->convertStdObjectToArray($soapResponse, true))
: $soapResponse;
/** Remove result wrappers */
$result = isset($result[SoapHandler::RESULT_NODE_NAME]) ? $result[SoapHandler::RESULT_NODE_NAME] : $result;
return $result;
}
/**
* Get proper SOAP client instance that is initialized with WSDL corresponding to requested service interface.
*
* @param string $serviceInfo PHP service interface name, should include version if present
* @param string|null $storeCode
* @return \Laminas\Soap\Client
*/
protected function _getSoapClient($serviceInfo, $storeCode = null)
{
$wsdlUrl = $this->generateWsdlUrl(
[$this->_getSoapServiceName($serviceInfo) . $this->_getSoapServiceVersion($serviceInfo)],
$storeCode
);
/** @var \Laminas\Soap\Client $soapClient */
$soapClient = null;
if (isset($serviceInfo['soap']['token'])) {
$token = $serviceInfo['soap']['token'];
if (array_key_exists($token, $this->_soapClients['custom'])
&& array_key_exists($wsdlUrl, $this->_soapClients['custom'][$token])
) {
$soapClient = $this->_soapClients['custom'][$token][$wsdlUrl];
} else {
if (!array_key_exists($token, $this->_soapClients['custom'])) {
$this->_soapClients['custom'][$token] = [];
}
$soapClient = $this->_soapClients['custom'][$token][$wsdlUrl]
= $this->instantiateSoapClient($wsdlUrl, $token);
}
} else {
if (!isset($this->_soapClients[$wsdlUrl])) {
$this->_soapClients['default'][$wsdlUrl] = $this->instantiateSoapClient($wsdlUrl, null);
}
$soapClient = $this->_soapClients['default'][$wsdlUrl];
}
return $soapClient;
}
/**
* Create SOAP client instance and initialize it with provided WSDL URL.
*
* @param string $wsdlUrl
* @param string $token Authentication token
* @return \Laminas\Soap\Client
*/
public function instantiateSoapClient($wsdlUrl, $token = null)
{
$accessCredentials = $token
? $token
: \Magento\TestFramework\Authentication\OauthHelper::getApiAccessCredentials()['key'];
$opts = ['http' => ['header' => "Authorization: Bearer " . $accessCredentials]];
$context = stream_context_create($opts);
$soapClient = new \Laminas\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
if (TESTS_XDEBUG_ENABLED) {
$soapClient->setCookie('XDEBUG_SESSION', 1);
}
return $soapClient;
}
/**
* Generate WSDL URL.
*
* @param array $services e.g.<pre>
* array(
* 'catalogProductV1',
* 'customerV2'
* );</pre>
* @param string|null $storeCode
* @return string
*/
public function generateWsdlUrl($services, $storeCode = null)
{
/** Sort list of services to avoid having different WSDL URLs for the identical lists of services. */
//TODO: This may change since same resource of multiple versions may be allowed after namespace changes
ksort($services);
if ($storeCode == null) {
$storeCode = Bootstrap::getObjectManager()
->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore()
->getCode();
}
/** TESTS_BASE_URL is initialized in PHPUnit configuration */
$wsdlUrl = rtrim(TESTS_BASE_URL, '/') . self::WSDL_BASE_PATH . '/' . $storeCode . '?wsdl=1&services=';
$wsdlResourceArray = [];
foreach ($services as $serviceName) {
$wsdlResourceArray[] = $serviceName;
}
return $wsdlUrl . implode(",", $wsdlResourceArray);
}
/**
* Retrieve SOAP operation name from available service info.
*
* @param array $serviceInfo
* @return string
* @throws \LogicException
*/
protected function _getSoapOperation($serviceInfo)
{
if (isset($serviceInfo['soap']['operation'])) {
$soapOperation = $serviceInfo['soap']['operation'];
} elseif (isset($serviceInfo['serviceInterface']) && isset($serviceInfo['method'])) {
$soapOperation = $this->_soapConfig->getSoapOperation(
$serviceInfo['serviceInterface'],
$serviceInfo['method']
);
} else {
throw new \LogicException("SOAP operation cannot be identified.");
}
return $soapOperation;
}
/**
* Retrieve service version from available service info.
*
* @param array $serviceInfo
* @return string
* @throws \LogicException
*/
protected function _getSoapServiceVersion($serviceInfo)
{
if (isset($serviceInfo['soap']['operation'])) {
/*
TODO: Need to rework this to remove version call for serviceInfo array with 'operation' key
since version will be part of the service name
*/
return '';
} elseif (isset($serviceInfo['serviceInterface'])) {
preg_match(
\Magento\Webapi\Model\Config::SERVICE_CLASS_PATTERN,
$serviceInfo['serviceInterface'],
$matches
);
if (isset($matches[3])) {
$version = $matches[3];
} else {
//TODO: Need to add this temporary version until version is added back for new MSC based services
$version = 1;
//throw new \LogicException("Service interface name is invalid.");
}
} else {
throw new \LogicException("Service version cannot be identified.");
}
/** Normalize version */
$version = 'V' . ltrim($version, 'vV');
return $version;
}
/**
* Retrieve service name from available service info.
*
* @param array $serviceInfo
* @return string
* @throws \LogicException
*/
protected function _getSoapServiceName($serviceInfo)
{
if (isset($serviceInfo['soap']['service'])) {
$serviceName = $serviceInfo['soap']['service'];
} elseif (isset($serviceInfo['serviceInterface'])) {
$serviceName = $this->_soapConfig->getServiceName($serviceInfo['serviceInterface'], false);
} else {
throw new \LogicException("Service name cannot be identified.");
}
return $serviceName;
}
/**
* Recursively transform array keys from camelCase to snake_case.
*
* Utility method for converting SOAP responses. Webapi framework's SOAP processing outputs
* snake case Data Object properties(ex. item_id) as camel case(itemId) to adhere to the WSDL.
* This method allows tests to use the same data for asserting both SOAP and REST responses.
*
* @param array $objectData An array of data.
* @return array The array with all camelCase keys converted to snake_case.
*/
protected function toSnakeCase(array $objectData)
{
$data = [];
foreach ($objectData as $key => $value) {
$key = strtolower(preg_replace("/(?<=\\w)(?=[A-Z])/", "_$1", $key));
if (is_array($value)) {
$data[$key] = $this->toSnakeCase($value);
} else {
$data[$key] = $value;
}
}
return $data;
}
}
@@ -0,0 +1,44 @@
<?php
/**
* API tests adapter interface.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase\Webapi;
interface AdapterInterface
{
/**
* Perform call to the specified service method.
*
* @param array $serviceInfo <pre>
* array(
* 'rest' => array(
* 'resourcePath' => $resourcePath, // e.g. /products/:id
* 'httpMethod' => $httpMethod, // e.g. GET
* 'token' => '21hasbtlaqy8t3mj73kjh71cxxkqj4aq' // optional : for token based Authentication. Will
* override default Oauth based authentication provided
* by test framework
* ),
* 'soap' => array(
* 'service' => $soapService, // soap service name with Version suffix e.g.
* catalogProductV1, customerV2
* 'operation' => $operation // soap operation name e.g. catalogProductCreate
* 'token' => '21hasbtlaqy8t3mj73kjh71cxxkqj4aq' // optional : for token based Authentication. Will
* override default Oauth based authentication provided
* by test framework
* ),
* OR
* 'serviceInterface' => $phpServiceInterfaceName, // e.g. \Magento\Catalog\Api\ProductInterface
* 'method' => $serviceMethodName // e.g. create
* 'entityId' => $entityId // is used in REST route placeholder (if applicable)
* );
* </pre>
* @param array $arguments
* @param string|null $storeCode if store code not provided, default store code will be used
* @param \Magento\Integration\Model\Integration|null $integration
* @return array|string|int|float|bool
*/
public function call($serviceInfo, $arguments = [], $storeCode = null, $integration = null);
}
@@ -0,0 +1,775 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Webapi\Exception as WebapiException;
use Magento\TestFramework\SkippableTrait;
use Magento\Webapi\Model\Soap\Fault;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test case for Web API functional tests for REST and SOAP.
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class WebapiAbstract extends \PHPUnit\Framework\TestCase
{
use SkippableTrait;
/** TODO: Reconsider implementation of fixture-management methods after implementing several tests */
/**#@+
* Auto tear down options in setFixture
*/
public const AUTO_TEAR_DOWN_DISABLED = 0;
public const AUTO_TEAR_DOWN_AFTER_METHOD = 1;
public const AUTO_TEAR_DOWN_AFTER_CLASS = 2;
/**#@-*/
/**#@+
* Web API adapters that are used to perform actual calls.
*/
public const ADAPTER_SOAP = 'soap';
public const ADAPTER_REST = 'rest';
/**#@-*/
/**
* Application cache model.
*
* @var \Magento\Framework\App\Cache
*/
protected $_appCache;
/**
* The list of models to be deleted automatically in tearDown().
*
* @var array
*/
protected $_modelsToDelete = [];
/**
* Namespace for fixtures is different for each test case.
*
* @var string
*/
protected static $_fixturesNamespace;
/**
* The list of registered fixtures.
*
* @var array
*/
protected static $_fixtures = [];
/**
* Fixtures to be deleted in tearDown().
*
* @var array
*/
protected static $_methodLevelFixtures = [];
/**
* Fixtures to be deleted in tearDownAfterClass().
*
* @var array
*/
protected static $_classLevelFixtures = [];
/**
* Original Magento config values.
*
* @var array
*/
protected $_origConfigValues = [];
/**
* The list of instantiated Web API adapters.
*
* @var \Magento\TestFramework\TestCase\Webapi\AdapterInterface[]
*/
protected $_webApiAdapters;
/**
* The list of available Web API adapters.
*
* @var array
*/
protected $_webApiAdaptersMap = [
self::ADAPTER_SOAP => \Magento\TestFramework\TestCase\Webapi\Adapter\Soap::class,
self::ADAPTER_REST => \Magento\TestFramework\TestCase\Webapi\Adapter\Rest::class,
];
/**
* Initialize fixture namespaces.
* //phpcs:disable
*/
public static function setUpBeforeClass(): void
{
//phpcs:enable
parent::setUpBeforeClass();
self::_setFixtureNamespace();
}
/**
* Run garbage collector for cleaning memory
*
* @return void
* //phpcs:disable
*/
public static function tearDownAfterClass(): void
{
//phpcs:enable
//clear garbage in memory
gc_collect_cycles();
$fixtureNamespace = self::_getFixtureNamespace();
if (isset(self::$_classLevelFixtures[$fixtureNamespace])
&& count(self::$_classLevelFixtures[$fixtureNamespace])
) {
self::_deleteFixtures(self::$_classLevelFixtures[$fixtureNamespace]);
}
//ever disable secure area on class down
self::_enableSecureArea(false);
self::_unsetFixtureNamespace();
parent::tearDownAfterClass();
}
/**
* Call safe delete for models which added to delete list, Restore config values changed during the test
*
* @return void
*/
protected function tearDown(): void
{
$fixtureNamespace = self::_getFixtureNamespace();
if (isset(self::$_methodLevelFixtures[$fixtureNamespace])
&& count(self::$_methodLevelFixtures[$fixtureNamespace])
) {
self::_deleteFixtures(self::$_methodLevelFixtures[$fixtureNamespace]);
}
$this->_callModelsDelete();
$this->_restoreAppConfig();
parent::tearDown();
}
/**
* Perform Web API call to the system under test.
*
* @see \Magento\TestFramework\TestCase\Webapi\AdapterInterface::call()
* @param array $serviceInfo
* @param array $arguments
* @param string|null $webApiAdapterCode
* @param string|null $storeCode
* @param \Magento\Integration\Model\Integration|null $integration
* @return array|int|string|float|bool Web API call results
*/
protected function _webApiCall(
$serviceInfo,
$arguments = [],
$webApiAdapterCode = null,
$storeCode = null,
$integration = null
) {
if ($webApiAdapterCode === null) {
/** Default adapter code is defined in PHPUnit configuration */
$webApiAdapterCode = strtolower(TESTS_WEB_API_ADAPTER);
}
return $this->_getWebApiAdapter($webApiAdapterCode)->call($serviceInfo, $arguments, $storeCode, $integration);
}
/**
* Mark test to be executed for SOAP adapter only.
*
* @param ?string $message
*/
protected function _markTestAsSoapOnly($message = null)
{
if (TESTS_WEB_API_ADAPTER != self::ADAPTER_SOAP) {
$this->markTestSkipped($message ? $message : "The test is intended to be executed for SOAP adapter only.");
}
}
/**
* Mark test to be executed for REST adapter only.
*
* @param ?string $message
*/
protected function _markTestAsRestOnly($message = null)
{
if (TESTS_WEB_API_ADAPTER != self::ADAPTER_REST) {
$this->markTestSkipped($message ? $message : "The test is intended to be executed for REST adapter only.");
}
}
/**
* Set fixture to registry
*
* @param string $key
* @param mixed $fixture
* @param int $tearDown
* @return void
* //phpcs:disable
*/
public static function setFixture($key, $fixture, $tearDown = self::AUTO_TEAR_DOWN_AFTER_METHOD)
{
//phpcs:enable
$fixturesNamespace = self::_getFixtureNamespace();
if (!isset(self::$_fixtures[$fixturesNamespace])) {
self::$_fixtures[$fixturesNamespace] = [];
}
self::$_fixtures[$fixturesNamespace][$key] = $fixture;
if ($tearDown == self::AUTO_TEAR_DOWN_AFTER_METHOD) {
if (!isset(self::$_methodLevelFixtures[$fixturesNamespace])) {
self::$_methodLevelFixtures[$fixturesNamespace] = [];
}
self::$_methodLevelFixtures[$fixturesNamespace][] = $key;
} else {
if ($tearDown == self::AUTO_TEAR_DOWN_AFTER_CLASS) {
if (!isset(self::$_classLevelFixtures[$fixturesNamespace])) {
self::$_classLevelFixtures[$fixturesNamespace] = [];
}
self::$_classLevelFixtures[$fixturesNamespace][] = $key;
}
}
}
/**
* Get fixture by key
*
* @param string $key
* @return mixed
* //phpcs:disable
*/
public static function getFixture($key)
{
//phpcs:enable
$fixturesNamespace = self::_getFixtureNamespace();
if (array_key_exists($key, self::$_fixtures[$fixturesNamespace])) {
return self::$_fixtures[$fixturesNamespace][$key];
}
return null;
}
/**
* Call safe delete for model
*
* @param \Magento\Framework\Model\AbstractModel $model
* @param bool $secure
* @return void
* //phpcs:disable
*/
public static function callModelDelete($model, $secure = false) : void
{
//phpcs:enable
if ($model instanceof \Magento\Framework\Model\AbstractModel && $model->getId()) {
if ($secure) {
self::_enableSecureArea();
}
$model->delete();
if ($secure) {
self::_enableSecureArea(false);
}
}
}
/**
* Call safe delete for model
*
* @param \Magento\Framework\Model\AbstractModel $model
* @param bool $secure
* @return \Magento\TestFramework\TestCase\WebapiAbstract
*/
public function addModelToDelete($model, $secure = false)
{
$this->_modelsToDelete[] = ['model' => $model, 'secure' => $secure];
return $this;
}
/**
* Get Web API adapter (create if requested one does not exist).
*
* @param string $webApiAdapterCode
* @return \Magento\TestFramework\TestCase\Webapi\AdapterInterface
* @throws \LogicException When requested Web API adapter is not declared
*/
protected function _getWebApiAdapter($webApiAdapterCode)
{
if (!isset($this->_webApiAdapters[$webApiAdapterCode])) {
if (!isset($this->_webApiAdaptersMap[$webApiAdapterCode])) {
throw new \LogicException(
sprintf('Declaration of the requested Web API adapter "%s" was not found.', $webApiAdapterCode)
);
}
$this->_webApiAdapters[$webApiAdapterCode] = Bootstrap::getObjectManager()->get(
$this->_webApiAdaptersMap[$webApiAdapterCode]
);
}
return $this->_webApiAdapters[$webApiAdapterCode];
}
/**
* Set fixtures namespace
*
* @throws \RuntimeException
* //phpcs:disable
*/
protected static function _setFixtureNamespace()
{
//phpcs:enable
if (self::$_fixturesNamespace !== null) {
throw new \RuntimeException('Fixture namespace is already set.');
}
self::$_fixturesNamespace = uniqid();
}
/**
* Unset fixtures namespace
* //phpcs:disable
*/
protected static function _unsetFixtureNamespace()
{
//phpcs:enable
$fixturesNamespace = self::_getFixtureNamespace();
unset(self::$_fixtures[$fixturesNamespace]);
self::$_fixturesNamespace = null;
}
/**
* Get fixtures namespace
*
* @throws \RuntimeException
* @return string
* //phpcs:disable
*/
protected static function _getFixtureNamespace()
{
//phpcs:enable
$fixtureNamespace = self::$_fixturesNamespace;
if ($fixtureNamespace === null) {
throw new \RuntimeException('Fixture namespace must be set.');
}
return $fixtureNamespace;
}
/**
* Enable secure/admin area
*
* @param bool $flag
* @return void
* //phpcs:disable
*/
protected static function _enableSecureArea($flag = true)
{
//phpcs:enable
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\Registry::class)->unregister('isSecureArea');
if ($flag) {
$objectManager->get(\Magento\Framework\Registry::class)->register('isSecureArea', $flag);
}
}
/**
* Call delete models from list
*
* @return \Magento\TestFramework\TestCase\WebapiAbstract
*/
protected function _callModelsDelete()
{
if ($this->_modelsToDelete) {
foreach ($this->_modelsToDelete as $key => $modelData) {
/** @var $model \Magento\Framework\Model\AbstractModel */
$model = $modelData['model'];
$this->callModelDelete($model, $modelData['secure']);
unset($this->_modelsToDelete[$key]);
}
}
return $this;
}
/**
* Check if all error messages are expected ones
*
* @param array $expectedMessages
* @param array $receivedMessages
*/
protected function _assertMessagesEqual($expectedMessages, $receivedMessages)
{
foreach ($receivedMessages as $message) {
$this->assertContains($message, $expectedMessages, "Unexpected message: '{$message}'");
}
$expectedErrorsCount = count($expectedMessages);
$this->assertCount($expectedErrorsCount, $receivedMessages, 'Invalid messages quantity received');
}
/**
* Delete array of fixtures
*
* @param array $fixtures
* //phpcs:disable
*/
protected static function _deleteFixtures($fixtures)
{
//phpcs:enable
foreach ($fixtures as $fixture) {
self::deleteFixture($fixture, true);
}
}
/**
* Delete fixture by key
*
* @param string $key
* @param bool $secure
* @return void
* //phpcs:disable
*/
public static function deleteFixture($key, $secure = false)
{
//phpcs:enable
$fixturesNamespace = self::_getFixtureNamespace();
if (array_key_exists($key, self::$_fixtures[$fixturesNamespace])) {
self::callModelDelete(self::$_fixtures[$fixturesNamespace][$key], $secure);
unset(self::$_fixtures[$fixturesNamespace][$key]);
}
}
/** TODO: Remove methods below if not used, otherwise fix them (after having some tests implemented)*/
/**
* Get application cache model
*
* @return \Magento\Framework\App\Cache
*/
protected function _getAppCache()
{
if (null === $this->_appCache) {
//set application path
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\App\Config\ScopeConfigInterface $config */
$config = $objectManager->get(\Magento\Framework\App\Config\ScopeConfigInterface::class);
$options = $config->getOptions();
$currentCacheDir = $options->getCacheDir();
$currentEtcDir = $options->getEtcDir();
/** @var Filesystem $filesystem */
$filesystem = $objectManager->get(\Magento\Framework\Filesystem::class);
$options->setCacheDir($filesystem->getDirectoryRead(DirectoryList::CACHE)->getAbsolutePath());
$options->setEtcDir($filesystem->getDirectoryRead(DirectoryList::CONFIG)->getAbsolutePath());
$this->_appCache = $objectManager->get(\Magento\Framework\App\Cache::class);
//revert paths options
$options->setCacheDir($currentCacheDir);
$options->setEtcDir($currentEtcDir);
}
return $this->_appCache;
}
/**
* Clean config cache of application
*
* @return bool
*/
protected function _cleanAppConfigCache()
{
return $this->_getAppCache()->clean(\Magento\Framework\App\Config::CACHE_TAG);
}
/**
* Update application config data
*
* @param string $path Config path with the form "section/group/node"
* @param string|int|null $value Value of config item
* @param bool $cleanAppCache If TRUE application cache will be refreshed
* @param bool $updateLocalConfig If TRUE local config object will be updated too
* @param bool $restore If TRUE config value will be restored after test run
* @return \Magento\TestFramework\TestCase\WebapiAbstract
* @throws \RuntimeException
*/
protected function _updateAppConfig(
$path,
$value,
$cleanAppCache = true,
$updateLocalConfig = false,
$restore = false
) {
list($section, $group, $node) = explode('/', $path);
if (!$section || !$group || !$node) {
throw new \RuntimeException(
sprintf('Config path must have view as "section/group/node" but now it "%s"', $path)
);
}
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $config \Magento\Config\Model\Config */
$config = $objectManager->create(\Magento\Config\Model\Config::class);
$data[$group]['fields'][$node]['value'] = $value;
$config->setSection($section)->setGroups($data)->save();
if ($restore && !isset($this->_origConfigValues[$path])) {
$this->_origConfigValues[$path] = (string)$objectManager->get(
\Magento\Framework\App\Config\ScopeConfigInterface::class
)->getNode(
$path,
'default'
);
}
//refresh local cache
if ($cleanAppCache) {
if ($updateLocalConfig) {
$objectManager->get(\Magento\Framework\App\Config\ReinitableConfigInterface::class)->reinit();
$objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)->reinitStores();
}
if (!$this->_cleanAppConfigCache()) {
throw new \RuntimeException('Application configuration cache cannot be cleaned.');
}
}
return $this;
}
/**
* Restore config values changed during tests
*/
protected function _restoreAppConfig()
{
foreach ($this->_origConfigValues as $configPath => $origValue) {
$this->_updateAppConfig($configPath, $origValue, true, true);
}
}
/**
* Process rest exception result.
*
* @param \Exception $e
* @return array
* <pre> ex.
* 'message' => "No such entity with %fieldName1 = %value1, %fieldName2 = %value2"
* 'parameters' => [
* "fieldName1" => "email",
* "value1" => "dummy@example.com",
* "fieldName2" => "websiteId",
* "value2" => 0
* ]
*
* </pre>
*/
public function processRestExceptionResult(\Exception $e)
{
$error = json_decode($e->getMessage(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
$error['message'] = $e->getMessage();
}
//Remove line breaks and replace with space
$error['message'] = trim(preg_replace('/\s+/', ' ', $error['message']));
// remove trace and type, will only be present if server is in dev mode
unset($error['trace']);
unset($error['type']);
return $error;
}
/**
* Verify that SOAP fault contains necessary information.
*
* @param \SoapFault $soapFault
* @param string $expectedMessage
* @param string $expectedFaultCode
* @param array $expectedErrorParams
* @param array $expectedWrappedErrors
* @param string $traceString
*/
protected function checkSoapFault(
$soapFault,
$expectedMessage,
$expectedFaultCode,
$expectedErrorParams = [],
$expectedWrappedErrors = [],
$traceString = null
) {
$this->assertStringContainsString(
$expectedMessage,
$soapFault->getMessage(),
"Fault message is invalid."
);
$errorDetailsNode = 'GenericFault';
$errorDetails = isset($soapFault->detail->$errorDetailsNode) ? $soapFault->detail->$errorDetailsNode : null;
if (!empty($expectedErrorParams) || !empty($expectedWrappedErrors)) {
/** Check SOAP fault details */
$this->assertNotNull($errorDetails, "Details must be present.");
$this->_checkFaultParams($expectedErrorParams, $errorDetails);
$this->_checkWrappedErrors($expectedWrappedErrors, $errorDetails);
}
if ($traceString) {
/** Check error trace */
$traceNode = Fault::NODE_DETAIL_TRACE;
$mode = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\App\State::class)
->getMode();
if ($mode == \Magento\Framework\App\State::MODE_DEVELOPER) {
/** Developer mode changes tested behavior and it cannot properly be tested for now */
$this->assertStringContainsString(
$traceString,
$errorDetails->$traceNode,
'Trace Information is incorrect.'
);
} else {
$this->assertNull($errorDetails, "Details are not expected.");
}
}
/** Check SOAP fault code */
$this->assertNotNull($soapFault->faultcode, "Fault code must not be empty.");
$this->assertEquals($expectedFaultCode, $soapFault->faultcode, "Fault code is invalid.");
}
/**
* Check additional error parameters.
*
* @param array $expectedErrorParams
* @param \stdClass $errorDetails
*/
protected function _checkFaultParams($expectedErrorParams, $errorDetails)
{
$paramsNode = Fault::NODE_DETAIL_PARAMETERS;
if ($expectedErrorParams) {
$paramNode = Fault::NODE_DETAIL_PARAMETER;
$paramKey = Fault::NODE_DETAIL_PARAMETER_KEY;
$paramValue = Fault::NODE_DETAIL_PARAMETER_VALUE;
$actualParams = [];
if (isset($errorDetails->$paramsNode->$paramNode)) {
if (is_array($errorDetails->$paramsNode->$paramNode)) {
foreach ($errorDetails->$paramsNode->$paramNode as $param) {
$actualParams[$param->$paramKey] = $param->$paramValue;
}
} else {
$param = $errorDetails->$paramsNode->$paramNode;
$actualParams[$param->$paramKey] = $param->$paramValue;
}
}
$this->assertEquals(
$expectedErrorParams,
$actualParams,
"Parameters in fault details are invalid."
);
} else {
$this->assertFalse(isset($errorDetails->$paramsNode), "Parameters are not expected in fault details.");
}
}
/**
* Check additional wrapped errors.
*
* @param array $expectedWrappedErrors
* @param \stdClass $errorDetails
*/
protected function _checkWrappedErrors($expectedWrappedErrors, $errorDetails)
{
$wrappedErrorsNode = Fault::NODE_DETAIL_WRAPPED_ERRORS;
if ($expectedWrappedErrors) {
$wrappedErrorNode = Fault::NODE_DETAIL_WRAPPED_ERROR;
$actualWrappedErrors = [];
if (isset($errorDetails->$wrappedErrorsNode->$wrappedErrorNode)) {
$errorNode = $errorDetails->$wrappedErrorsNode->$wrappedErrorNode;
if (is_array($errorNode)) {
foreach ($errorNode as $error) {
$actualWrappedErrors[] = $this->getActualWrappedErrors($error);
}
} else {
$actualWrappedErrors[] = $this->getActualWrappedErrors($errorNode);
}
}
$this->assertEquals(
$expectedWrappedErrors,
$actualWrappedErrors,
"Wrapped errors in fault details are invalid."
);
} else {
$this->assertFalse(
isset($errorDetails->$wrappedErrorsNode),
"Wrapped errors are not expected in fault details."
);
}
}
/**
* Get actual wrapped errors.
*
* @param \stdClass $errorNode
* @return array
*/
private function getActualWrappedErrors(\stdClass $errorNode)
{
if (!isset($errorNode->parameters)) {
return [
'message' => $errorNode->message,
];
}
$actualParameters = [];
$parameterNode = $errorNode->parameters->parameter;
if (is_array($parameterNode)) {
foreach ($parameterNode as $parameter) {
$actualParameters[$parameter->key] = $parameter->value;
}
} else {
$actualParameters[$parameterNode->key] = $parameterNode->value;
}
return [
'message' => $errorNode->message,
// Can not rename on parameters due to Backward Compatibility
'params' => $actualParameters,
];
}
/**
* Assert webapi errors.
*
* @param array $serviceInfo
* @param array $data
* @param array $expectedErrorData
* @return void
* @throws \Exception
*/
protected function assertWebApiCallErrors(array $serviceInfo, array $data, array $expectedErrorData)
{
try {
$this->_webApiCall($serviceInfo, $data);
$this->fail('Expected throwing exception');
} catch (\Exception $e) {
if (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) {
self::assertEquals($expectedErrorData, $this->processRestExceptionResult($e));
self::assertEquals(WebapiException::HTTP_BAD_REQUEST, $e->getCode());
} elseif (TESTS_WEB_API_ADAPTER === self::ADAPTER_SOAP) {
$this->assertInstanceOf('SoapFault', $e);
$expectedWrappedErrors = [];
foreach ($expectedErrorData['errors'] as $error) {
// @see \Magento\TestFramework\TestCase\WebapiAbstract::getActualWrappedErrors()
$expectedWrappedError = [
'message' => $error['message'],
];
if (isset($error['parameters'])) {
$expectedWrappedError['params'] = $error['parameters'];
}
$expectedWrappedErrors[] = $expectedWrappedError;
}
$this->checkSoapFault($e, $expectedErrorData['message'], 'env:Sender', [], $expectedWrappedErrors);
} else {
throw $e;
}
}
}
}