ltsecurityinc安防产品在线商城代码
This commit is contained in:
+186
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Annotation;
|
||||
|
||||
use Magento\Config\Model\ResourceModel\Config as ConfigResource;
|
||||
use Magento\Framework\App\Config\MutableScopeConfigInterface;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\TestFramework\App\ApiMutableScopeConfig;
|
||||
use Magento\TestFramework\Config\Model\ConfigStorage;
|
||||
use Magento\TestFramework\Helper\Bootstrap;
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
class ApiConfigFixture extends ConfigFixture
|
||||
{
|
||||
/**
|
||||
* Values need to be deleted form the database
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $valuesToDeleteFromDatabase = [];
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
|
||||
*/
|
||||
protected function setStoreConfigValue(array $matches, $configPathAndValue): void
|
||||
{
|
||||
$storeCode = $matches[0];
|
||||
$parts = preg_split('/\s+/', $configPathAndValue, 3);
|
||||
[$configScope, $configPath, $requiredValue] = $parts + ['', '', ''];
|
||||
/** @var ConfigStorage $configStorage */
|
||||
$configStorage = Bootstrap::getObjectManager()->get(ConfigStorage::class);
|
||||
if (!$configStorage->checkIsRecordExist($configPath, ScopeInterface::SCOPE_STORES, $storeCode)) {
|
||||
$this->valuesToDeleteFromDatabase[$storeCode][$configPath ?? ''] = $requiredValue ?? '';
|
||||
}
|
||||
|
||||
parent::setStoreConfigValue($matches, $configPathAndValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function setGlobalConfigValue($configPathAndValue): void
|
||||
{
|
||||
[$configPath, $requiredValue] = preg_split('/\s+/', $configPathAndValue, 2);
|
||||
$configPath = str_starts_with($configPath, 'default/') ? substr($configPath, 8) : $configPath;
|
||||
/** @var ConfigStorage $configStorage */
|
||||
$configStorage = Bootstrap::getObjectManager()->get(ConfigStorage::class);
|
||||
if (!$configStorage->checkIsRecordExist($configPath)) {
|
||||
$this->valuesToDeleteFromDatabase['global'][$configPath] = $requiredValue;
|
||||
}
|
||||
|
||||
$originalValue = $this->getScopeConfigValue($configPath, ScopeConfigInterface::SCOPE_TYPE_DEFAULT);
|
||||
$this->globalConfigValues[$configPath] = $originalValue;
|
||||
$this->_setConfigValue($configPath, $requiredValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
|
||||
*/
|
||||
protected function setWebsiteConfigValue(array $matches, $configPathAndValue): void
|
||||
{
|
||||
$websiteCode = $matches[0];
|
||||
$parts = preg_split('/\s+/', $configPathAndValue, 3);
|
||||
[$configScope, $configPath, $requiredValue] = $parts + ['', '', ''];
|
||||
/** @var ConfigStorage $configStorage */
|
||||
$configStorage = Bootstrap::getObjectManager()->get(ConfigStorage::class);
|
||||
if (!$configStorage->checkIsRecordExist($configPath, ScopeInterface::SCOPE_WEBSITES, $websiteCode)) {
|
||||
$this->valuesToDeleteFromDatabase[$websiteCode][$configPath ?? ''] = $requiredValue ?? '';
|
||||
}
|
||||
|
||||
parent::setWebsiteConfigValue($matches, $configPathAndValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
|
||||
*/
|
||||
protected function _restoreConfigData()
|
||||
{
|
||||
/** @var ConfigResource $configResource */
|
||||
$configResource = Bootstrap::getObjectManager()->get(ConfigResource::class);
|
||||
/* Restore global values */
|
||||
foreach ($this->globalConfigValues as $configPath => $originalValue) {
|
||||
if (isset($this->valuesToDeleteFromDatabase['global'][$configPath])) {
|
||||
$configResource->deleteConfig($configPath);
|
||||
} else {
|
||||
$this->_setConfigValue($configPath, $originalValue);
|
||||
}
|
||||
}
|
||||
$this->globalConfigValues = [];
|
||||
/* Restore store-scoped values */
|
||||
foreach ($this->storeConfigValues as $storeCode => $originalData) {
|
||||
foreach ($originalData as $configPath => $originalValue) {
|
||||
$storeCode = $storeCode ?: null;
|
||||
if (isset($this->valuesToDeleteFromDatabase[$storeCode][$configPath])) {
|
||||
$scopeId = $this->getIdByScopeType(ScopeInterface::SCOPE_STORES, $storeCode);
|
||||
$configResource->deleteConfig($configPath, ScopeInterface::SCOPE_STORES, $scopeId);
|
||||
} else {
|
||||
$this->setScopeConfigValue(
|
||||
$configPath,
|
||||
(string)$originalValue,
|
||||
ScopeInterface::SCOPE_STORES,
|
||||
$storeCode
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->storeConfigValues = [];
|
||||
/* Restore website-scoped values */
|
||||
foreach ($this->websiteConfigValues as $websiteCode => $originalData) {
|
||||
foreach ($originalData as $configPath => $originalValue) {
|
||||
$websiteCode = $websiteCode ?: null;
|
||||
if (isset($this->valuesToDeleteFromDatabase[$websiteCode][$configPath])) {
|
||||
$scopeId = $this->getIdByScopeType(ScopeInterface::SCOPE_WEBSITES, $websiteCode);
|
||||
$configResource->deleteConfig($configPath, ScopeInterface::SCOPE_WEBSITES, $scopeId);
|
||||
} else {
|
||||
$this->setScopeConfigValue(
|
||||
$configPath,
|
||||
$originalValue,
|
||||
ScopeInterface::SCOPE_WEBSITES,
|
||||
$websiteCode
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->websiteConfigValues = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getMutableScopeConfig(): MutableScopeConfigInterface
|
||||
{
|
||||
return Bootstrap::getObjectManager()
|
||||
->get(ApiMutableScopeConfig::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getScopeConfigValue(string $configPath, string $scopeType, string $scopeCode = null): ?string
|
||||
{
|
||||
/** @var ConfigStorage $configStorage */
|
||||
$configStorage = Bootstrap::getObjectManager()->get(ConfigStorage::class);
|
||||
$result = $configStorage->getValueFromDb($configPath, $scopeType, $scopeCode);
|
||||
|
||||
return $result ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get id by code
|
||||
*
|
||||
* @param string $scopeType
|
||||
* @param string|null $scopeId
|
||||
* @return int
|
||||
*/
|
||||
private function getIdByScopeType(string $scopeType, ?string $scopeId): int
|
||||
{
|
||||
$id = 0;
|
||||
/** @var StoreManagerInterface $storeManager */
|
||||
$storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
|
||||
switch ($scopeType) {
|
||||
case ScopeInterface::SCOPE_WEBSITES:
|
||||
$id = (int)$storeManager->getWebsite($scopeId)->getId();
|
||||
break;
|
||||
case ScopeInterface::SCOPE_STORES:
|
||||
$id = (int)$storeManager->getStore($scopeId)->getId();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Annotation;
|
||||
|
||||
use Magento\Customer\Model\Metadata\AttributeMetadataCache;
|
||||
use Magento\TestFramework\Event\Param\Transaction;
|
||||
use Magento\TestFramework\Helper\Bootstrap;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Implementation of the @magentoApiDataFixture DocBlock annotation.
|
||||
*/
|
||||
class ApiDataFixture extends DataFixture
|
||||
{
|
||||
public const ANNOTATION = 'magentoApiDataFixture';
|
||||
|
||||
/**
|
||||
* Handler for 'startTest' event
|
||||
*
|
||||
* @param TestCase $test
|
||||
*/
|
||||
public function startTest(TestCase $test)
|
||||
{
|
||||
Bootstrap::getInstance()->reinitialize();
|
||||
$this->_applyFixtures($this->_getFixtures($test), $test);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler for 'endTest' event
|
||||
*
|
||||
* @param TestCase $test
|
||||
*/
|
||||
public function endTest(TestCase $test)
|
||||
{
|
||||
$this->_revertFixtures($test);
|
||||
$objectManager = Bootstrap::getObjectManager();
|
||||
$objectManager->get(AttributeMetadataCache::class)->clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getAnnotation(): string
|
||||
{
|
||||
return self::ANNOTATION;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getDbIsolationState(TestCase $test)
|
||||
{
|
||||
return parent::getDbIsolationState($test) ?: ['disabled'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function startTestTransactionRequest(TestCase $test, Transaction $param): void
|
||||
{
|
||||
Bootstrap::getInstance()->reinitialize();
|
||||
parent::startTestTransactionRequest($test, $param);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function endTestTransactionRequest(TestCase $test, Transaction $param): void
|
||||
{
|
||||
parent::endTestTransactionRequest($test, $param);
|
||||
$objectManager = Bootstrap::getObjectManager();
|
||||
$objectManager->get(AttributeMetadataCache::class)->clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getParsers(): array
|
||||
{
|
||||
$parsers = [];
|
||||
// Add magentoDataFixture annotations
|
||||
$parsers[] = Bootstrap::getObjectManager()->create(
|
||||
\Magento\TestFramework\Annotation\Parser\DataFixture::class,
|
||||
['annotation' => DataFixture::ANNOTATION]
|
||||
);
|
||||
return array_merge(
|
||||
parent::getParsers(),
|
||||
$parsers
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework;
|
||||
|
||||
/**
|
||||
* Custom suite loader for adding wrapper for tests.
|
||||
*/
|
||||
class ApiSuiteLoader extends SuiteLoader
|
||||
{
|
||||
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
/**
|
||||
* Application configuration object. Used to access configuration when application is installed.
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\App;
|
||||
|
||||
use Magento\Config\Model\Config\Factory as ConfigFactory;
|
||||
use Magento\Framework\App\Config\MutableScopeConfigInterface;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Store\Api\StoreRepositoryInterface;
|
||||
use Magento\Store\Api\WebsiteRepositoryInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
class ApiMutableScopeConfig implements MutableScopeConfigInterface
|
||||
{
|
||||
/** @var Config */
|
||||
private $testAppConfig;
|
||||
|
||||
/** @var StoreRepositoryInterface */
|
||||
private $storeRepository;
|
||||
|
||||
/** @var WebsiteRepositoryInterface */
|
||||
private $websiteRepository;
|
||||
|
||||
/** @var ConfigFactory */
|
||||
private $configFactory;
|
||||
|
||||
/**
|
||||
* @param ScopeConfigInterface $config
|
||||
* @param StoreRepositoryInterface $storeRepository
|
||||
* @param WebsiteRepositoryInterface $websiteRepository
|
||||
* @param ConfigFactory $configFactory
|
||||
*/
|
||||
public function __construct(
|
||||
ScopeConfigInterface $config,
|
||||
StoreRepositoryInterface $storeRepository,
|
||||
WebsiteRepositoryInterface $websiteRepository,
|
||||
ConfigFactory $configFactory
|
||||
) {
|
||||
$this->testAppConfig = $config;
|
||||
$this->storeRepository = $storeRepository;
|
||||
$this->websiteRepository = $websiteRepository;
|
||||
$this->configFactory = $configFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function isSetFlag($path, $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeCode = null)
|
||||
{
|
||||
return $this->testAppConfig->isSetFlag($path, $scopeType, $scopeCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getValue($path, $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeCode = null)
|
||||
{
|
||||
return $this->testAppConfig->getValue($path, $scopeType, $scopeCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function setValue(
|
||||
$path,
|
||||
$value,
|
||||
$scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
|
||||
$scopeCode = null
|
||||
) {
|
||||
$this->persistConfig($path, $value, $scopeType, $scopeCode);
|
||||
return $this->testAppConfig->setValue($path, $value, $scopeType, $scopeCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean app config cache
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
$this->testAppConfig->clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist config in database
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $value
|
||||
* @param string $scopeType
|
||||
* @param string|null $scopeCode
|
||||
* @return void
|
||||
*/
|
||||
private function persistConfig(string $path, string $value, string $scopeType, ?string $scopeCode): void
|
||||
{
|
||||
$pathParts = explode('/', $path);
|
||||
$store = 0;
|
||||
$configData = [
|
||||
'section' => $pathParts[0],
|
||||
'website' => '',
|
||||
'store' => $store,
|
||||
'groups' => [
|
||||
$pathParts[1] => [
|
||||
'fields' => [
|
||||
$pathParts[2] => [
|
||||
'value' => $value
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
if ($scopeType === ScopeInterface::SCOPE_STORE && $scopeCode !== null) {
|
||||
$store = $this->storeRepository->get($scopeCode)->getId();
|
||||
$configData['store'] = $store;
|
||||
} elseif ($scopeType === ScopeInterface::SCOPE_WEBSITES && $scopeCode !== null) {
|
||||
$website = $this->websiteRepository->get($scopeCode)->getId();
|
||||
$configData['store'] = '';
|
||||
$configData['website'] = $website;
|
||||
}
|
||||
|
||||
$this->configFactory->create(['data' => $configData])->save();
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Assert;
|
||||
|
||||
use PHPUnit\Framework\Assert;
|
||||
|
||||
/**
|
||||
* Check that actual data contains all values from expected data
|
||||
* But actual data can have more values than expected data
|
||||
*/
|
||||
class AssertArrayContains
|
||||
{
|
||||
/**
|
||||
* @param array $expected
|
||||
* @param array $actual
|
||||
* @return void
|
||||
*/
|
||||
public static function assert(array $expected, array $actual)
|
||||
{
|
||||
foreach ($expected as $key => $value) {
|
||||
Assert::assertArrayHasKey(
|
||||
$key,
|
||||
$actual,
|
||||
"Expected value for key '{$key}' is missed"
|
||||
);
|
||||
if (is_array($value)) {
|
||||
self::assert($value, $actual[$key]);
|
||||
} else {
|
||||
Assert::assertEquals(
|
||||
$value,
|
||||
$actual[$key],
|
||||
"Expected value for key '{$key}' doesn't match"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper class for generating OAuth related credentials
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Authentication;
|
||||
|
||||
use Magento\Framework\Exception\IntegrationException;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Oauth\Exception;
|
||||
use Magento\TestFramework\Authentication\Rest\OauthClient;
|
||||
use Magento\TestFramework\Helper\Bootstrap;
|
||||
use OAuth\Common\Consumer\Credentials;
|
||||
use Laminas\Stdlib\Exception\LogicException;
|
||||
use Magento\Integration\Model\Integration;
|
||||
|
||||
/**
|
||||
* Authentication Oauth helper
|
||||
*/
|
||||
class OauthHelper
|
||||
{
|
||||
/** @var array */
|
||||
protected static $_apiCredentials;
|
||||
|
||||
/**
|
||||
* Generate authentication credentials
|
||||
*
|
||||
* @param string $date consumer creation date
|
||||
* @return array
|
||||
* <pre>
|
||||
* array (
|
||||
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //consumer key
|
||||
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //consumer secret
|
||||
* 'verifier' => 'oiudioqueoiquweoiqwueoqwuii'
|
||||
* 'consumer' => $consumer, // retrieved consumer Model
|
||||
* 'token' => $token // retrieved token Model
|
||||
* );
|
||||
* </pre>
|
||||
* @throws LocalizedException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function getConsumerCredentials($date = null)
|
||||
{
|
||||
$integration = self::_createIntegration('all');
|
||||
$objectManager = Bootstrap::getObjectManager();
|
||||
/** @var $oauthService \Magento\Integration\Api\OauthServiceInterface */
|
||||
$oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
|
||||
$consumer = $oauthService->loadConsumer($integration->getConsumerId());
|
||||
$url = TESTS_BASE_URL;
|
||||
$consumer->setCallbackUrl($url);
|
||||
$consumer->setRejectedCallbackUrl($url);
|
||||
if ($date !== null) {
|
||||
$consumer->setCreatedAt($date);
|
||||
}
|
||||
$consumer->save();
|
||||
$token = $objectManager->create(\Magento\Integration\Model\Oauth\Token::class);
|
||||
$verifier = $token->createVerifierToken($consumer->getId())->getVerifier();
|
||||
|
||||
return [
|
||||
'key' => $consumer->getKey(),
|
||||
'secret' => $consumer->getSecret(),
|
||||
'verifier' => $verifier,
|
||||
'consumer' => $consumer,
|
||||
'token' => $token
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an access token to associated to a consumer to access APIs. No resources are available to this consumer.
|
||||
*
|
||||
* @return array comprising of token key and secret
|
||||
* <pre>
|
||||
* array (
|
||||
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
|
||||
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
|
||||
* 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
|
||||
* );
|
||||
* </pre>
|
||||
* @throws LocalizedException
|
||||
* @throws Exception
|
||||
* @throws \OAuth\Common\Http\Exception\TokenResponseException
|
||||
*/
|
||||
public static function getAccessToken()
|
||||
{
|
||||
$consumerCredentials = self::getConsumerCredentials();
|
||||
$credentials = new Credentials($consumerCredentials['key'], $consumerCredentials['secret'], TESTS_BASE_URL);
|
||||
$oAuthClient = new OauthClient($credentials);
|
||||
$requestToken = $oAuthClient->requestRequestToken();
|
||||
$accessToken = $oAuthClient->requestAccessToken(
|
||||
$requestToken->getRequestToken(),
|
||||
$consumerCredentials['verifier'],
|
||||
$requestToken->getRequestTokenSecret()
|
||||
);
|
||||
|
||||
/** TODO: Reconsider return format. It is not aligned with method name. */
|
||||
return [
|
||||
'key' => $accessToken->getAccessToken(),
|
||||
'secret' => $accessToken->getAccessTokenSecret(),
|
||||
'oauth_client' => $oAuthClient
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an access token, tied to integration which has permissions to all API resources in the system.
|
||||
*
|
||||
* @param array $resources list of resources to grant to the integration
|
||||
* @param \Magento\Integration\Model\Integration|null $integrationModel
|
||||
* @return array
|
||||
* <pre>
|
||||
* array (
|
||||
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
|
||||
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
|
||||
* 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
|
||||
* 'integration' => $integration // Integration instance associated with access token
|
||||
* );
|
||||
* </pre>
|
||||
* @throws LocalizedException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function getApiAccessCredentials($resources = null, Integration $integrationModel = null)
|
||||
{
|
||||
if (!self::$_apiCredentials) {
|
||||
$integration = $integrationModel === null ? self::_createIntegration($resources) : $integrationModel;
|
||||
$objectManager = Bootstrap::getObjectManager();
|
||||
/** @var \Magento\Integration\Api\OauthServiceInterface $oauthService */
|
||||
$oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
|
||||
$oauthService->createAccessToken($integration->getConsumerId());
|
||||
$accessToken = $oauthService->getAccessToken($integration->getConsumerId());
|
||||
if (!$accessToken) {
|
||||
throw new LogicException('Access token was not created.');
|
||||
}
|
||||
$consumer = $oauthService->loadConsumer($integration->getConsumerId());
|
||||
$credentials = new Credentials($consumer->getKey(), $consumer->getSecret(), TESTS_BASE_URL);
|
||||
/** @var $oAuthClient OauthClient */
|
||||
$oAuthClient = new OauthClient($credentials);
|
||||
|
||||
self::$_apiCredentials = [
|
||||
'key' => $accessToken->getToken(),
|
||||
'secret' => $accessToken->getSecret(),
|
||||
'oauth_client' => $oAuthClient,
|
||||
'integration' => $integration,
|
||||
];
|
||||
}
|
||||
return self::$_apiCredentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget API access credentials.
|
||||
*/
|
||||
public static function clearApiAccessCredentials()
|
||||
{
|
||||
self::$_apiCredentials = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove fs element with nested elements.
|
||||
*
|
||||
* @param string $dir
|
||||
* @param bool $doSaveRoot
|
||||
*/
|
||||
protected static function _rmRecursive($dir, $doSaveRoot = false)
|
||||
{
|
||||
if (is_dir($dir)) {
|
||||
foreach (glob($dir . '/*') as $object) {
|
||||
if (is_dir($object)) {
|
||||
self::_rmRecursive($object);
|
||||
} else {
|
||||
unlink($object);
|
||||
}
|
||||
}
|
||||
if (!$doSaveRoot) {
|
||||
rmdir($dir);
|
||||
}
|
||||
} else {
|
||||
unlink($dir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create integration instance.
|
||||
*
|
||||
* @param array $resources
|
||||
* @return \Magento\Integration\Model\Integration
|
||||
* @throws LogicException
|
||||
* @throws IntegrationException
|
||||
*/
|
||||
protected static function _createIntegration($resources)
|
||||
{
|
||||
$objectManager = Bootstrap::getObjectManager();
|
||||
/** @var $integrationService \Magento\Integration\Api\IntegrationServiceInterface */
|
||||
$integrationService = $objectManager->get(\Magento\Integration\Api\IntegrationServiceInterface::class);
|
||||
|
||||
$params = ['name' => 'Integration' . microtime()];
|
||||
|
||||
if ($resources === null || $resources == 'all') {
|
||||
$params['all_resources'] = true;
|
||||
} else {
|
||||
$params['resource'] = $resources;
|
||||
}
|
||||
$integration = $integrationService->create($params);
|
||||
$integration->setStatus(\Magento\Integration\Model\Integration::STATUS_ACTIVE)->save();
|
||||
|
||||
/** Magento cache must be cleared to activate just created ACL role. */
|
||||
$varPath = realpath(BP . '/var');
|
||||
if (!$varPath) {
|
||||
throw new LogicException("Magento cache cannot be cleared after new ACL role creation.");
|
||||
} else {
|
||||
$cachePath = $varPath . '/cache';
|
||||
if (is_dir($cachePath)) {
|
||||
self::_rmRecursive($cachePath, true);
|
||||
}
|
||||
}
|
||||
return $integration;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Authentication\Rest;
|
||||
|
||||
use OAuth\Common\Http\Uri\UriInterface;
|
||||
|
||||
/**
|
||||
* Custom Client implementation for cURL
|
||||
*/
|
||||
class CurlClient extends \OAuth\Common\Http\Client\CurlClient
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function retrieveResponse(
|
||||
UriInterface $endpoint,
|
||||
$requestBody,
|
||||
array $extraHeaders = [],
|
||||
$method = 'POST'
|
||||
) {
|
||||
$this->setCurlParameters([CURLOPT_FAILONERROR => true]);
|
||||
return parent::retrieveResponse($endpoint, $requestBody, $extraHeaders, $method);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function normalizeHeaders(&$headers)
|
||||
{
|
||||
array_walk(
|
||||
$headers,
|
||||
function (&$val, $key) {
|
||||
$val = ucfirst(strtolower($key)) . ': ' . $val;
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
|
||||
namespace Magento\TestFramework\Authentication\Rest;
|
||||
|
||||
use Magento\TestFramework\Helper\Bootstrap;
|
||||
use OAuth\Common\Consumer\Credentials;
|
||||
use OAuth\Common\Http\Client\ClientInterface;
|
||||
use OAuth\Common\Http\Exception\TokenResponseException;
|
||||
use OAuth\Common\Http\Uri\Uri;
|
||||
use OAuth\Common\Http\Uri\UriInterface;
|
||||
use OAuth\Common\Storage\TokenStorageInterface;
|
||||
use OAuth\OAuth1\Service\AbstractService;
|
||||
use OAuth\OAuth1\Signature\SignatureInterface;
|
||||
use OAuth\OAuth1\Token\StdOAuth1Token;
|
||||
use OAuth\OAuth1\Token\TokenInterface;
|
||||
|
||||
/**
|
||||
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
|
||||
*/
|
||||
class OauthClient extends AbstractService
|
||||
{
|
||||
/**
|
||||
* The maximum timeout for http request in seconds
|
||||
*/
|
||||
public const DEFAULT_TIMEOUT = 120;
|
||||
|
||||
/** @var string|null */
|
||||
protected $_oauthVerifier = null;
|
||||
|
||||
/**
|
||||
* @param Credentials $credentials
|
||||
* @param ClientInterface|null $httpClient
|
||||
* @param TokenStorageInterface|null $storage
|
||||
* @param SignatureInterface|null $signature
|
||||
* @param UriInterface|null $baseApiUri
|
||||
*/
|
||||
public function __construct(
|
||||
Credentials $credentials,
|
||||
ClientInterface $httpClient = null,
|
||||
TokenStorageInterface $storage = null,
|
||||
SignatureInterface $signature = null,
|
||||
UriInterface $baseApiUri = null
|
||||
) {
|
||||
if (!isset($httpClient)) {
|
||||
$httpClient = new \Magento\TestFramework\Authentication\Rest\CurlClient();
|
||||
$httpClient->setTimeout(self::DEFAULT_TIMEOUT);
|
||||
}
|
||||
if (!isset($storage)) {
|
||||
$storage = new \OAuth\Common\Storage\Memory();
|
||||
}
|
||||
if (!isset($signature)) {
|
||||
$signature = new \Magento\TestFramework\Authentication\Rest\OauthClient\Signature($credentials);
|
||||
}
|
||||
parent::__construct($credentials, $httpClient, $storage, $signature, $baseApiUri);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getRequestTokenEndpoint()
|
||||
{
|
||||
return new Uri(TESTS_BASE_URL . '/oauth/token/request');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAuthorizationEndpoint()
|
||||
{
|
||||
throw new \OAuth\Common\Exception\Exception(
|
||||
'Magento REST API is 2-legged. Current operation is not available.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the access token API endpoint.
|
||||
*
|
||||
* @return UriInterface
|
||||
*/
|
||||
public function getAccessTokenEndpoint()
|
||||
{
|
||||
return new Uri(TESTS_BASE_URL . '/oauth/token/access');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the TestModule1 Rest API endpoint.
|
||||
*
|
||||
* @return UriInterface
|
||||
*/
|
||||
public function getTestApiEndpoint()
|
||||
{
|
||||
$defaultStoreCode = Bootstrap::getObjectManager()->get(\Magento\Store\Model\StoreManagerInterface::class)
|
||||
->getStore()->getCode();
|
||||
return new Uri(TESTS_BASE_URL . '/rest/' . $defaultStoreCode . '/V1/testmodule1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the access token response and returns a TokenInterface.
|
||||
*
|
||||
* @return TokenInterface
|
||||
* @param string $responseBody
|
||||
*/
|
||||
protected function parseAccessTokenResponse($responseBody)
|
||||
{
|
||||
return $this->_parseToken($responseBody);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the request token response and returns a TokenInterface.
|
||||
*
|
||||
* @return TokenInterface
|
||||
* @param string $responseBody
|
||||
* @throws TokenResponseException
|
||||
*/
|
||||
protected function parseRequestTokenResponse($responseBody)
|
||||
{
|
||||
$data = $this->_parseResponseBody($responseBody);
|
||||
if (isset($data['oauth_verifier'])) {
|
||||
$this->_oauthVerifier = $data['oauth_verifier'];
|
||||
}
|
||||
return $this->_parseToken($responseBody);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse response body and create oAuth token object based on parameters provided.
|
||||
*
|
||||
* @param string $responseBody
|
||||
* @return StdOAuth1Token
|
||||
* @throws TokenResponseException
|
||||
*/
|
||||
protected function _parseToken($responseBody)
|
||||
{
|
||||
$data = $this->_parseResponseBody($responseBody);
|
||||
$token = new StdOAuth1Token();
|
||||
$token->setRequestToken($data['oauth_token']);
|
||||
$token->setRequestTokenSecret($data['oauth_token_secret']);
|
||||
$token->setAccessToken($data['oauth_token']);
|
||||
$token->setAccessTokenSecret($data['oauth_token_secret']);
|
||||
$token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
|
||||
unset($data['oauth_token'], $data['oauth_token_secret']);
|
||||
$token->setExtraParams($data);
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse response body and return data in array.
|
||||
*
|
||||
* @param string $responseBody
|
||||
* @return array
|
||||
* @throws \OAuth\Common\Http\Exception\TokenResponseException
|
||||
*/
|
||||
protected function _parseResponseBody($responseBody)
|
||||
{
|
||||
if (!is_string($responseBody)) {
|
||||
throw new TokenResponseException("Response body is expected to be a string.");
|
||||
}
|
||||
parse_str($responseBody, $data);
|
||||
if (null === $data || !is_array($data)) {
|
||||
throw new TokenResponseException('Unable to parse response.');
|
||||
} elseif (isset($data['error'])) {
|
||||
throw new TokenResponseException("Error occurred: '{$data['error']}'");
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve oAuth verifier that was obtained during request token request.
|
||||
*
|
||||
* @return string
|
||||
* @throws \OAuth\Common\Http\Exception\TokenResponseException
|
||||
*/
|
||||
public function getOauthVerifier()
|
||||
{
|
||||
if (empty($this->_oauthVerifier)) {
|
||||
throw new TokenResponseException("oAuth verifier must be obtained during request token request.");
|
||||
}
|
||||
return $this->_oauthVerifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the authorization header for an authenticated API request.
|
||||
*
|
||||
* Fixing this method since parent implementation from lib not sending the oauth_verifier
|
||||
* when requesting access token.
|
||||
*
|
||||
* @param string $method
|
||||
* @param UriInterface $uri the uri the request is headed
|
||||
* @param \OAuth\OAuth1\Token\TokenInterface $token
|
||||
* @param array|null $bodyParams
|
||||
* @return string
|
||||
*/
|
||||
protected function buildAuthorizationHeaderForAPIRequest(
|
||||
$method,
|
||||
UriInterface $uri,
|
||||
TokenInterface $token,
|
||||
$bodyParams = null
|
||||
) {
|
||||
$this->signature->setTokenSecret($token->getAccessTokenSecret());
|
||||
$parameters = $this->getBasicAuthorizationHeaderInfo();
|
||||
if (isset($parameters['oauth_callback'])) {
|
||||
unset($parameters['oauth_callback']);
|
||||
}
|
||||
|
||||
$parameters = array_merge($parameters, ['oauth_token' => $token->getAccessToken()]);
|
||||
$parameters = array_merge($parameters, $bodyParams);
|
||||
$parameters['oauth_signature'] = $this->signature->getSignature($uri, $parameters, $method);
|
||||
|
||||
$authorizationHeader = 'OAuth ';
|
||||
$delimiter = '';
|
||||
|
||||
foreach ($parameters as $key => $value) {
|
||||
$authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
|
||||
$delimiter = ', ';
|
||||
}
|
||||
|
||||
return $authorizationHeader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the oAuth authorization header for an authenticated API request
|
||||
*
|
||||
* @param UriInterface $uri the uri the request is headed
|
||||
* @param \OAuth\OAuth1\Token\TokenInterface $token
|
||||
* @param string $tokenSecret used to verify the passed token
|
||||
* @param array $bodyParams
|
||||
* @param string $method HTTP method to use
|
||||
* @return array
|
||||
*/
|
||||
public function buildOauthAuthorizationHeader($uri, $token, $tokenSecret, $bodyParams, $method = 'GET')
|
||||
{
|
||||
$uri = new Uri($uri);
|
||||
$tokenObj = new StdOAuth1Token();
|
||||
$tokenObj->setAccessToken($token);
|
||||
$tokenObj->setAccessTokenSecret($tokenSecret);
|
||||
$tokenObj->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
|
||||
return [
|
||||
'Authorization: ' . $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $tokenObj, $bodyParams)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the bearer token authorization header
|
||||
*
|
||||
* @param string $token
|
||||
* @return array
|
||||
*/
|
||||
public function buildBearerTokenAuthorizationHeader($token)
|
||||
{
|
||||
return [
|
||||
'Authorization: Bearer ' . $token
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a Test REST api call access using oauth access token
|
||||
*
|
||||
* @param TokenInterface $token The access token.
|
||||
* @param string $method HTTP method.
|
||||
* @return array
|
||||
* @throws TokenResponseException
|
||||
*/
|
||||
public function validateAccessToken($token, $method = 'GET')
|
||||
{
|
||||
//Need to add Accept header else Magento errors out with 503
|
||||
$extraAuthenticationHeaders = ['Accept' => 'application/json'];
|
||||
|
||||
$this->signature->setTokenSecret($token->getAccessTokenSecret());
|
||||
|
||||
$authorizationHeader = [
|
||||
'Authorization' => $this->buildAuthorizationHeaderForAPIRequest(
|
||||
$method,
|
||||
$this->getTestApiEndpoint(),
|
||||
$token,
|
||||
[]
|
||||
),
|
||||
];
|
||||
|
||||
$headers = array_merge($authorizationHeader, $extraAuthenticationHeaders);
|
||||
|
||||
$responseBody = $this->httpClient->retrieveResponse($this->getTestApiEndpoint(), [], $headers, $method);
|
||||
|
||||
return json_decode($responseBody);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function getSignatureMethod()
|
||||
{
|
||||
return 'HMAC-SHA256';
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
|
||||
namespace Magento\TestFramework\Authentication\Rest\OauthClient;
|
||||
|
||||
use OAuth\Common\Http\Uri\UriInterface;
|
||||
|
||||
/**
|
||||
* Signature class for Magento REST API.
|
||||
*/
|
||||
class Signature extends \OAuth\OAuth1\Signature\Signature
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
*
|
||||
* In addition to the original method, allows array parameters for filters.
|
||||
*/
|
||||
public function getSignature(UriInterface $uri, array $params, $method = 'POST')
|
||||
{
|
||||
$queryStringData = !$uri->getQuery() ? [] : array_reduce(
|
||||
explode('&', $uri->getQuery()),
|
||||
function ($carry, $item) {
|
||||
list($key, $value) = explode('=', $item, 2);
|
||||
$carry[rawurldecode($key)] = rawurldecode($value);
|
||||
return $carry;
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
$signatureData = [];
|
||||
foreach (array_merge($queryStringData, $params) as $key => $value) {
|
||||
$signatureData[rawurlencode($key)] = rawurlencode($value);
|
||||
}
|
||||
|
||||
ksort($signatureData);
|
||||
|
||||
// determine base uri
|
||||
$baseUri = $uri->getScheme() . '://' . $uri->getRawAuthority();
|
||||
|
||||
if ('/' == $uri->getPath()) {
|
||||
$baseUri .= $uri->hasExplicitTrailingHostSlash() ? '/' : '';
|
||||
} else {
|
||||
$baseUri .= $uri->getPath();
|
||||
}
|
||||
|
||||
$baseString = strtoupper($method) . '&';
|
||||
$baseString .= rawurlencode($baseUri) . '&';
|
||||
$baseString .= rawurlencode($this->buildSignatureDataString($signatureData));
|
||||
|
||||
return base64_encode($this->hash($baseString));
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function hash($data)
|
||||
{
|
||||
switch (strtoupper($this->algorithm)) {
|
||||
case 'HMAC-SHA256':
|
||||
return hash_hmac('sha256', $data, $this->getSigningKey(), true);
|
||||
default:
|
||||
return parent::hash($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
|
||||
namespace Magento\TestFramework\Bootstrap;
|
||||
|
||||
use Magento\TestFramework\Annotation\ApiConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ConfigFixture;
|
||||
use Magento\TestFramework\Event\Transaction;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
class WebapiDocBlock extends \Magento\TestFramework\Bootstrap\DocBlock
|
||||
{
|
||||
/**
|
||||
* Get list of subscribers.
|
||||
*
|
||||
* In addition, register magentoApiDataFixture and magentoConfigFixture
|
||||
* annotation processors
|
||||
*
|
||||
* @param \Magento\TestFramework\Application $application
|
||||
* @return array
|
||||
*/
|
||||
protected function _getSubscribers(\Magento\TestFramework\Application $application)
|
||||
{
|
||||
$subscribers = parent::_getSubscribers($application);
|
||||
foreach ($subscribers as $key => $subscriber) {
|
||||
if (get_class($subscriber) === ConfigFixture::class || get_class($subscriber) === Transaction::class) {
|
||||
unset($subscribers[$key]);
|
||||
}
|
||||
}
|
||||
$subscribers[] = new \Magento\TestFramework\Event\Transaction(
|
||||
new \Magento\TestFramework\EventManager(
|
||||
[
|
||||
new \Magento\TestFramework\Annotation\DbIsolation(),
|
||||
new \Magento\TestFramework\Annotation\ApiDataFixture(),
|
||||
]
|
||||
)
|
||||
);
|
||||
$subscribers[] = new ApiConfigFixture();
|
||||
|
||||
return $subscribers;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Helper;
|
||||
|
||||
/**
|
||||
* Class for comparing arrays recursively
|
||||
*/
|
||||
class CompareArraysRecursively
|
||||
{
|
||||
/**
|
||||
* Compare arrays recursively regardless of nesting.
|
||||
* Can compare arrays that have both one level and n-level nesting.
|
||||
* ```
|
||||
* [
|
||||
* 'products' => [
|
||||
* 'items' => [
|
||||
* [
|
||||
* 'sku' => 'bundle-product',
|
||||
* 'type_id' => 'bundle',
|
||||
* 'items' => [
|
||||
* [
|
||||
* 'title' => 'Bundle Product Items',
|
||||
* 'sku' => 'bundle-product',
|
||||
* 'options' => [
|
||||
* [
|
||||
* 'price' => 2.75,
|
||||
* 'label' => 'Simple Product',
|
||||
* 'product' => [
|
||||
* 'name' => 'Simple Product',
|
||||
* 'sku' => 'simple',
|
||||
* ]
|
||||
* ]
|
||||
* ]
|
||||
* ]
|
||||
* ];
|
||||
* ```
|
||||
*
|
||||
* @param array $expected
|
||||
* @param array $actual
|
||||
* @return array
|
||||
*/
|
||||
public function execute(array $expected, array $actual): array
|
||||
{
|
||||
$diffResult = [];
|
||||
|
||||
foreach ($expected as $key => $value) {
|
||||
if (array_key_exists($key, $actual)) {
|
||||
if (is_array($value)) {
|
||||
$recursiveDiff = $this->execute($value, $actual[$key]);
|
||||
if (!empty($recursiveDiff)) {
|
||||
$diffResult[$key] = $recursiveDiff;
|
||||
}
|
||||
} else {
|
||||
if (!in_array($value, $actual, true)) {
|
||||
$diffResult[$key] = $value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$diffResult[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $diffResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Helper;
|
||||
|
||||
use Magento\Customer\Api\Data\CustomerInterface;
|
||||
use Magento\Customer\Model\Data\Customer as CustomerData;
|
||||
use Magento\Framework\Reflection\DataObjectProcessor;
|
||||
use Magento\TestFramework\TestCase\WebapiAbstract;
|
||||
use Magento\Framework\Webapi\Rest\Request as RestRequest;
|
||||
|
||||
class Customer extends WebapiAbstract
|
||||
{
|
||||
const RESOURCE_PATH = '/V1/customers';
|
||||
const SERVICE_NAME = 'customerAccountManagementV1';
|
||||
const CUSTOMER_REPOSITORY_SERVICE_NAME = "customerCustomerRepositoryV1";
|
||||
const SERVICE_VERSION = 'V1';
|
||||
|
||||
const CONFIRMATION = 'a4fg7h893e39d';
|
||||
const CREATED_AT = '2013-11-05';
|
||||
const CREATED_IN = 'default';
|
||||
const STORE_NAME = 'Store Name';
|
||||
const DOB = '1970-01-01';
|
||||
const GENDER = 'Male';
|
||||
const GROUP_ID = 1;
|
||||
const MIDDLENAME = 'A';
|
||||
const PREFIX = 'Mr.';
|
||||
const STORE_ID = 1;
|
||||
const SUFFIX = 'Esq.';
|
||||
const TAXVAT = '12';
|
||||
const WEBSITE_ID = 1;
|
||||
|
||||
/** Sample values for testing */
|
||||
const FIRSTNAME = 'Jane';
|
||||
const LASTNAME = 'Doe';
|
||||
const PASSWORD = 'test@123';
|
||||
|
||||
const ADDRESS_CITY1 = 'CityM';
|
||||
const ADDRESS_CITY2 = 'CityX';
|
||||
const ADDRESS_REGION_CODE1 = 'AL';
|
||||
const ADDRESS_REGION_CODE2 = 'AL';
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\Data\AddressInterfaceFactory
|
||||
*/
|
||||
private $customerAddressFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
|
||||
*/
|
||||
private $customerDataFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Framework\Api\DataObjectHelper
|
||||
*/
|
||||
private $dataObjectHelper;
|
||||
|
||||
/** @var DataObjectProcessor */
|
||||
private $dataObjectProcessor;
|
||||
|
||||
public function __construct($name = null, array $data = [], $dataName = '')
|
||||
{
|
||||
parent::__construct($name, $data, $dataName);
|
||||
|
||||
$this->customerAddressFactory = Bootstrap::getObjectManager()->create(
|
||||
\Magento\Customer\Api\Data\AddressInterfaceFactory::class
|
||||
);
|
||||
|
||||
$this->customerDataFactory = Bootstrap::getObjectManager()->create(
|
||||
\Magento\Customer\Api\Data\CustomerInterfaceFactory::class
|
||||
);
|
||||
|
||||
$this->dataObjectHelper = Bootstrap::getObjectManager()->create(
|
||||
\Magento\Framework\Api\DataObjectHelper::class
|
||||
);
|
||||
|
||||
$this->dataObjectProcessor = Bootstrap::getObjectManager()->create(
|
||||
\Magento\Framework\Reflection\DataObjectProcessor::class
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $additional
|
||||
* @return array|bool|float|int|string
|
||||
*/
|
||||
public function createSampleCustomer(array $additional = [])
|
||||
{
|
||||
$serviceInfo = [
|
||||
'rest' => [
|
||||
'resourcePath' => self::RESOURCE_PATH,
|
||||
'httpMethod' => RestRequest::HTTP_METHOD_POST,
|
||||
],
|
||||
'soap' => [
|
||||
'service' => self::SERVICE_NAME,
|
||||
'serviceVersion' => self::SERVICE_VERSION,
|
||||
'operation' => self::SERVICE_NAME . 'CreateAccount',
|
||||
],
|
||||
];
|
||||
|
||||
$customerDataArray = $this->dataObjectProcessor->buildOutputDataArray(
|
||||
$this->createSampleCustomerDataObject($additional),
|
||||
\Magento\Customer\Api\Data\CustomerInterface::class
|
||||
);
|
||||
$requestData = ['customer' => $customerDataArray, 'password' => self::PASSWORD];
|
||||
$customerData = $this->_webApiCall($serviceInfo, $requestData);
|
||||
return $customerData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Existing customer
|
||||
*
|
||||
* @param array $additional
|
||||
* @param int $customerId
|
||||
* @return array|bool|float|int|string
|
||||
*/
|
||||
public function updateSampleCustomer($customerId, array $additional = [])
|
||||
{
|
||||
$serviceInfo = [
|
||||
'rest' => [
|
||||
'resourcePath' => self::RESOURCE_PATH . "/" . $customerId,
|
||||
'httpMethod' => RestRequest::HTTP_METHOD_PUT,
|
||||
],
|
||||
'soap' => [
|
||||
'service' => self::CUSTOMER_REPOSITORY_SERVICE_NAME,
|
||||
'serviceVersion' => self::SERVICE_VERSION,
|
||||
'operation' => self::CUSTOMER_REPOSITORY_SERVICE_NAME . 'save',
|
||||
],
|
||||
];
|
||||
|
||||
$customerDataArray = $this->dataObjectProcessor->buildOutputDataArray(
|
||||
$this->createSampleCustomerDataObject($additional),
|
||||
\Magento\Customer\Api\Data\CustomerInterface::class
|
||||
);
|
||||
$requestData = ['customer' => $customerDataArray, 'password' => self::PASSWORD];
|
||||
$customerData = $this->_webApiCall($serviceInfo, $requestData);
|
||||
return $customerData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $additional
|
||||
* @return array
|
||||
*/
|
||||
private function getCustomerSampleData(array $additional = [])
|
||||
{
|
||||
$customerData = [
|
||||
CustomerData::FIRSTNAME => self::FIRSTNAME,
|
||||
CustomerData::LASTNAME => self::LASTNAME,
|
||||
CustomerData::EMAIL => 'janedoe' . uniqid() . '@example.com',
|
||||
CustomerData::CONFIRMATION => self::CONFIRMATION,
|
||||
CustomerData::CREATED_AT => self::CREATED_AT,
|
||||
CustomerData::CREATED_IN => self::STORE_NAME,
|
||||
CustomerData::DOB => self::DOB,
|
||||
CustomerData::GENDER => self::GENDER,
|
||||
CustomerData::GROUP_ID => self::GROUP_ID,
|
||||
CustomerData::MIDDLENAME => self::MIDDLENAME,
|
||||
CustomerData::PREFIX => self::PREFIX,
|
||||
CustomerData::STORE_ID => self::STORE_ID,
|
||||
CustomerData::SUFFIX => self::SUFFIX,
|
||||
CustomerData::TAXVAT => self::TAXVAT,
|
||||
CustomerData::WEBSITE_ID => self::WEBSITE_ID,
|
||||
'custom_attributes' => [
|
||||
[
|
||||
'attribute_code' => 'disable_auto_group_change',
|
||||
'value' => '0',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
return array_merge($customerData, $additional);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create customer using setters.
|
||||
*
|
||||
* @param array $additional
|
||||
* @return CustomerInterface
|
||||
*/
|
||||
public function createSampleCustomerDataObject(array $additional = [])
|
||||
{
|
||||
$customerAddress1 = $this->customerAddressFactory->create();
|
||||
$customerAddress1->setCountryId('US');
|
||||
$customerAddress1->setIsDefaultBilling(true);
|
||||
$customerAddress1->setIsDefaultShipping(true);
|
||||
$customerAddress1->setPostcode('75477');
|
||||
$customerAddress1->setRegion(
|
||||
Bootstrap::getObjectManager()->create(\Magento\Customer\Api\Data\RegionInterfaceFactory::class)
|
||||
->create()
|
||||
->setRegionCode(self::ADDRESS_REGION_CODE1)
|
||||
->setRegion('Alabama')
|
||||
->setRegionId(1)
|
||||
);
|
||||
$customerAddress1->setStreet(['Green str, 67']);
|
||||
$customerAddress1->setTelephone('3468676');
|
||||
$customerAddress1->setCity(self::ADDRESS_CITY1);
|
||||
$customerAddress1->setFirstname('John');
|
||||
$customerAddress1->setLastname('Smith');
|
||||
$address1 = $this->dataObjectProcessor->buildOutputDataArray(
|
||||
$customerAddress1,
|
||||
\Magento\Customer\Api\Data\AddressInterface::class
|
||||
);
|
||||
|
||||
$customerAddress2 = $this->customerAddressFactory->create();
|
||||
$customerAddress2->setCountryId('US');
|
||||
$customerAddress2->setIsDefaultBilling(false);
|
||||
$customerAddress2->setIsDefaultShipping(false);
|
||||
$customerAddress2->setPostcode('47676');
|
||||
$customerAddress2->setRegion(
|
||||
Bootstrap::getObjectManager()->create(\Magento\Customer\Api\Data\RegionInterfaceFactory::class)
|
||||
->create()
|
||||
->setRegionCode(self::ADDRESS_REGION_CODE2)
|
||||
->setRegion('Alabama')
|
||||
->setRegionId(1)
|
||||
);
|
||||
$customerAddress2->setStreet(['Black str, 48', 'Building D']);
|
||||
$customerAddress2->setTelephone('3234676');
|
||||
$customerAddress2->setCity(self::ADDRESS_CITY2);
|
||||
$customerAddress2->setFirstname('John');
|
||||
$customerAddress2->setLastname('Smith');
|
||||
$address2 = $this->dataObjectProcessor->buildOutputDataArray(
|
||||
$customerAddress2,
|
||||
\Magento\Customer\Api\Data\AddressInterface::class
|
||||
);
|
||||
|
||||
$customerData = $this->getCustomerSampleData(
|
||||
array_merge([CustomerData::KEY_ADDRESSES => [$address1, $address2]], $additional)
|
||||
);
|
||||
$customer = $this->customerDataFactory->create();
|
||||
$this->dataObjectHelper->populateWithArray(
|
||||
$customer,
|
||||
$customerData,
|
||||
\Magento\Customer\Api\Data\CustomerInterface::class
|
||||
);
|
||||
return $customer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Helper;
|
||||
|
||||
/**
|
||||
* Encodes and decodes JSON and checks for errors on these operations
|
||||
*/
|
||||
class JsonSerializer
|
||||
{
|
||||
/**
|
||||
* @var array JSON Error code to error message mapping
|
||||
*/
|
||||
private $jsonErrorMessages = [
|
||||
JSON_ERROR_DEPTH => 'Maximum depth exceeded',
|
||||
JSON_ERROR_STATE_MISMATCH => 'State mismatch',
|
||||
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
|
||||
JSON_ERROR_SYNTAX => 'Syntax error, invalid JSON',
|
||||
];
|
||||
|
||||
/**
|
||||
* Encode a string as a JSON object with error checking
|
||||
*
|
||||
* @param mixed $data
|
||||
* @return string
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function jsonEncode($data)
|
||||
{
|
||||
$ret = json_encode($data);
|
||||
$this->checkJsonError($data);
|
||||
|
||||
// return the json String
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a JSON string with error checking
|
||||
*
|
||||
* @param string $data
|
||||
* @param bool $asArray
|
||||
* @throws \Exception
|
||||
* @return mixed
|
||||
*/
|
||||
public function jsonDecode($data, $asArray = true)
|
||||
{
|
||||
$ret = json_decode($data, $asArray);
|
||||
$this->checkJsonError($data);
|
||||
|
||||
// return the array
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for JSON error in the latest encoding / decoding and throws an exception in case of error
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function checkJsonError()
|
||||
{
|
||||
$jsonError = json_last_error();
|
||||
if ($jsonError !== JSON_ERROR_NONE) {
|
||||
// find appropriate error message
|
||||
$message = 'Unknown JSON Error';
|
||||
if (isset($this->jsonErrorMessages[$jsonError])) {
|
||||
$message = $this->jsonErrorMessages[$jsonError];
|
||||
}
|
||||
|
||||
throw new \Exception(
|
||||
'JSON Encoding / Decoding error: ' . $message . var_export(func_get_arg(0), true),
|
||||
$jsonError
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<?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
|
||||
* @return mixed
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function processResponse(string $response)
|
||||
{
|
||||
$responseArray = $this->json->jsonDecode($response);
|
||||
|
||||
if (!is_array($responseArray)) {
|
||||
//phpcs:ignore Magento2.Exceptions.DirectThrow
|
||||
throw new \Exception('Unknown GraphQL response body: ' . $response);
|
||||
}
|
||||
|
||||
$this->processErrors($responseArray);
|
||||
|
||||
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);
|
||||
$responseBody = $this->processResponse($response['body']);
|
||||
$responseHeaders = !empty($response['header']) ? $this->processResponseHeaders($response['header']) : [];
|
||||
$responseCookies = !empty($response['header']) ? $this->processResponseCookies($response['header']) : [];
|
||||
|
||||
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);
|
||||
$responseBody = $this->processResponse($response['body']);
|
||||
$responseHeaders = !empty($response['header']) ? $this->processResponseHeaders($response['header']) : [];
|
||||
$responseCookies = !empty($response['header']) ? $this->processResponseCookies($response['header']) : [];
|
||||
|
||||
return ['headers' => $responseHeaders, 'body' => $responseBody, 'cookies' => $responseCookies];
|
||||
}
|
||||
|
||||
/**
|
||||
* Process errors
|
||||
*
|
||||
* @param array $responseBodyArray
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function processErrors($responseBodyArray)
|
||||
{
|
||||
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,
|
||||
$responseBodyArray
|
||||
);
|
||||
}
|
||||
//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;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\TestCase\GraphQl;
|
||||
|
||||
/**
|
||||
* Response contains errors exception
|
||||
*/
|
||||
class ResponseContainsErrorsException extends \Exception
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $responseData;
|
||||
|
||||
/**
|
||||
* @param string $message
|
||||
* @param array $responseData
|
||||
* @param \Exception|null $cause
|
||||
* @param int $code
|
||||
*/
|
||||
public function __construct(string $message, array $responseData, \Exception $cause = null, int $code = 0)
|
||||
{
|
||||
parent::__construct($message, $code, $cause);
|
||||
$this->responseData = $responseData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get response data
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getResponseData(): array
|
||||
{
|
||||
return $this->responseData;
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
<?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)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+231
@@ -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;
|
||||
}
|
||||
}
|
||||
+116
@@ -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;
|
||||
}
|
||||
}
|
||||
+158
@@ -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;
|
||||
}
|
||||
}
|
||||
+239
@@ -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;
|
||||
}
|
||||
}
|
||||
+133
@@ -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, '/');
|
||||
}
|
||||
}
|
||||
+257
@@ -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;
|
||||
}
|
||||
}
|
||||
+44
@@ -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,772 @@
|
||||
<?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\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
|
||||
{
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework;
|
||||
|
||||
/**
|
||||
* Provides access to the application for the tests
|
||||
*
|
||||
* Allows installation and uninstallation
|
||||
*/
|
||||
class WebApiApplication extends Application
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
throw new \Exception(
|
||||
"Can't start application: purpose of Web API Application is to use classes and models from the application"
|
||||
. " and don't run it"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function install($cleanup)
|
||||
{
|
||||
if ($cleanup) {
|
||||
$this->cleanup();
|
||||
}
|
||||
|
||||
$installOptions = $this->getInstallConfig();
|
||||
|
||||
/* Install application */
|
||||
if ($installOptions) {
|
||||
$installCmd = 'php -f ' . BP . '/bin/magento setup:install -vvv';
|
||||
$installArgs = [];
|
||||
foreach ($installOptions as $optionName => $optionValue) {
|
||||
if (is_bool($optionValue)) {
|
||||
if (true === $optionValue) {
|
||||
$installCmd .= " --$optionName";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$installCmd .= " --$optionName=%s";
|
||||
$installArgs[] = $optionValue;
|
||||
}
|
||||
$this->_shell->execute($installCmd, $installArgs);
|
||||
}
|
||||
|
||||
$this->runPostInstallCommands();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*
|
||||
* Return empty array of custom directories
|
||||
* @return array
|
||||
*/
|
||||
protected function getCustomDirs()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\WebapiWorkaround\Override;
|
||||
|
||||
use Magento\Framework\App\ObjectManager;
|
||||
use Magento\Framework\Config\ConverterInterface;
|
||||
use Magento\Framework\Config\SchemaLocatorInterface;
|
||||
use Magento\Framework\View\File\CollectorInterface;
|
||||
use Magento\TestFramework\Annotation\AdminConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ApiConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ApiDataFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixtureBeforeTransaction;
|
||||
use Magento\TestFramework\WebapiWorkaround\Override\Config\Converter;
|
||||
use Magento\TestFramework\WebapiWorkaround\Override\Config\FileCollector;
|
||||
use Magento\TestFramework\WebapiWorkaround\Override\Config\SchemaLocator;
|
||||
use Magento\TestFramework\Workaround\Override\Config as IntegrationConfig;
|
||||
|
||||
/**
|
||||
* Provides api tests configuration.
|
||||
*/
|
||||
class Config extends IntegrationConfig
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected const FIXTURE_TYPES = [
|
||||
ApiDataFixture::ANNOTATION,
|
||||
ApiConfigFixture::ANNOTATION,
|
||||
DataFixture::ANNOTATION,
|
||||
DataFixtureBeforeTransaction::ANNOTATION,
|
||||
AdminConfigFixture::ANNOTATION,
|
||||
];
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getConverter(): ConverterInterface
|
||||
{
|
||||
return ObjectManager::getInstance()->create(Converter::class, ['types' => $this::FIXTURE_TYPES]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getSchemaLocator(): SchemaLocatorInterface
|
||||
{
|
||||
return ObjectManager::getInstance()->create(SchemaLocator::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function getFileCollector(): CollectorInterface
|
||||
{
|
||||
return ObjectManager::getInstance()->create(FileCollector::class);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\WebapiWorkaround\Override\Config;
|
||||
|
||||
use Magento\TestFramework\Annotation\AdminConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ApiDataFixture;
|
||||
use Magento\TestFramework\Annotation\ConfigFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixtureBeforeTransaction;
|
||||
use Magento\TestFramework\Workaround\Override\Config\Converter as IntegrationConverter;
|
||||
|
||||
/**
|
||||
* Converter for api tests config
|
||||
*/
|
||||
class Converter extends IntegrationConverter
|
||||
{
|
||||
/**
|
||||
* Fill node attributes values
|
||||
*
|
||||
* @param \DOMElement $fixture
|
||||
* @return array
|
||||
*/
|
||||
protected function fillAttributes(\DOMElement $fixture): array
|
||||
{
|
||||
$result = [];
|
||||
switch ($fixture->nodeName) {
|
||||
case DataFixtureBeforeTransaction::ANNOTATION:
|
||||
case DataFixture::ANNOTATION:
|
||||
case ApiDataFixture::ANNOTATION:
|
||||
$result = $this->fillDataFixtureAttributes($fixture);
|
||||
break;
|
||||
case ConfigFixture::ANNOTATION:
|
||||
$result = $this->fillConfigFixtureAttributes($fixture);
|
||||
break;
|
||||
case AdminConfigFixture::ANNOTATION:
|
||||
$result = $this->fillAdminConfigFixtureAttributes($fixture);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\WebapiWorkaround\Override\Config;
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
use Magento\Framework\Component\DirSearch;
|
||||
use Magento\Framework\View\Design\ThemeInterface;
|
||||
use Magento\Framework\View\File\CollectorInterface;
|
||||
use Magento\Framework\View\File\Factory as FileFactory;
|
||||
|
||||
class FileCollector implements CollectorInterface
|
||||
{
|
||||
/**
|
||||
* @var DirSearch
|
||||
*/
|
||||
private $componentDirSearch;
|
||||
|
||||
/**
|
||||
* @var FileFactory
|
||||
*/
|
||||
private $fileFactory;
|
||||
|
||||
/**
|
||||
* @param DirSearch $dirSearch
|
||||
* @param FileFactory $fileFactory
|
||||
*/
|
||||
public function __construct(
|
||||
DirSearch $dirSearch,
|
||||
FileFactory $fileFactory
|
||||
) {
|
||||
$this->componentDirSearch = $dirSearch;
|
||||
$this->fileFactory = $fileFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve files
|
||||
*
|
||||
* @param \Magento\Framework\View\Design\ThemeInterface $theme
|
||||
* @param string $filePath
|
||||
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
|
||||
* @return \Magento\Framework\View\File[]
|
||||
*/
|
||||
public function getFiles(ThemeInterface $theme, $filePath)
|
||||
{
|
||||
$result = [];
|
||||
$configFiles = $this->componentDirSearch->collectFilesWithContext(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Test/Api/_files/' . $filePath
|
||||
);
|
||||
foreach ($configFiles as $file) {
|
||||
$result[] = $this->fileFactory->create($file->getFullPath(), $file->getComponentName(), null, true);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\WebapiWorkaround\Override\Config;
|
||||
|
||||
use Magento\Framework\Config\SchemaLocatorInterface;
|
||||
|
||||
/**
|
||||
* Schema locator for tests config
|
||||
*/
|
||||
class SchemaLocator implements SchemaLocatorInterface
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getSchema()
|
||||
{
|
||||
return __DIR__ . '/../../etc/overrides.xsd';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getPerFileSchema()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\WebapiWorkaround\Override\Fixture;
|
||||
|
||||
use Magento\TestFramework\Annotation\AdminConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ApiConfigFixture;
|
||||
use Magento\TestFramework\Annotation\ApiDataFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixture;
|
||||
use Magento\TestFramework\Annotation\DataFixtureBeforeTransaction;
|
||||
use Magento\TestFramework\Workaround\Override\Fixture\Applier\AdminConfigFixture as AdminConfigFixtureApplier;
|
||||
use Magento\TestFramework\Workaround\Override\Fixture\Applier\ApplierInterface;
|
||||
use Magento\TestFramework\Workaround\Override\Fixture\Applier\ConfigFixture as ConfigFixtureApplier;
|
||||
use Magento\TestFramework\Workaround\Override\Fixture\Applier\DataFixture as DataFixtureApplier;
|
||||
use Magento\TestFramework\Workaround\Override\Fixture\Resolver as IntegrationResolver;
|
||||
|
||||
/**
|
||||
* Class determines fixture applying according to configurations
|
||||
*/
|
||||
class Resolver extends IntegrationResolver
|
||||
{
|
||||
/**
|
||||
* Get appropriate fixture applier according to fixture type
|
||||
*
|
||||
* @param string $fixtureType
|
||||
* @return ApplierInterface
|
||||
*/
|
||||
protected function getApplierByFixtureType(string $fixtureType): ApplierInterface
|
||||
{
|
||||
switch ($fixtureType) {
|
||||
case ApiDataFixture::ANNOTATION:
|
||||
case DataFixture::ANNOTATION:
|
||||
case DataFixtureBeforeTransaction::ANNOTATION:
|
||||
$applier = $this->objectManager->get(DataFixtureApplier::class);
|
||||
break;
|
||||
case ApiConfigFixture::ANNOTATION:
|
||||
$applier = $this->objectManager->get(ConfigFixtureApplier::class);
|
||||
break;
|
||||
case AdminConfigFixture::ANNOTATION:
|
||||
$applier = $this->objectManager->get(AdminConfigFixtureApplier::class);
|
||||
break;
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported fixture type %s provided', $fixtureType));
|
||||
}
|
||||
|
||||
return $applier;
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
-->
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<xs:element name="overrides">
|
||||
<xs:complexType>
|
||||
<xs:sequence minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="test" type="test" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:complexType name="test">
|
||||
<xs:sequence minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="method" type="method" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoApiDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixtureBeforeTransaction" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoConfigFixture" type="configFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoAdminConfigFixture" type="adminConfigFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
<xs:attribute name="class" type="xs:string" use="required"/>
|
||||
<xs:attribute name="skip" type="xs:boolean"/>
|
||||
<xs:attribute name="skipMessage" type="xs:string"/>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="method">
|
||||
<xs:sequence minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="dataSet" type="dataSet" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoApiDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixtureBeforeTransaction" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoConfigFixture" type="configFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoAdminConfigFixture" type="adminConfigFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
<xs:attribute name="name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="skip" type="xs:boolean"/>
|
||||
<xs:attribute name="skipMessage" type="xs:string"/>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="dataSet">
|
||||
<xs:sequence minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="magentoApiDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixture" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoDataFixtureBeforeTransaction" type="dataFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoConfigFixture" type="configFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="magentoAdminConfigFixture" type="adminConfigFixture" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
<xs:attribute name="name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="skip" type="xs:boolean"/>
|
||||
<xs:attribute name="skipMessage" type="xs:string"/>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="dataFixture">
|
||||
<xs:attribute name="path" type="xs:string" use="required"/>
|
||||
<xs:attribute name="newPath" type="xs:string"/>
|
||||
<xs:attribute name="before" type="xs:string"/>
|
||||
<xs:attribute name="after" type="xs:string"/>
|
||||
<xs:attribute name="remove" type="xs:boolean"/>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="configFixture">
|
||||
<xs:attribute name="path" type="xs:string" use="required"/>
|
||||
<xs:attribute name="scopeType">
|
||||
<xs:simpleType>
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="store"/>
|
||||
<xs:enumeration value="website"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="scopeCode" type="xs:string"/>
|
||||
<xs:attribute name="value" type="xs:string"/>
|
||||
<xs:attribute name="newValue" type="xs:string"/>
|
||||
<xs:attribute name="remove" type="xs:boolean"/>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="adminConfigFixture">
|
||||
<xs:attribute name="path" type="xs:string" use="required"/>
|
||||
<xs:attribute name="value" type="xs:string"/>
|
||||
<xs:attribute name="newValue" type="xs:string"/>
|
||||
<xs:attribute name="remove" type="xs:boolean"/>
|
||||
</xs:complexType>
|
||||
</xs:schema>
|
||||
Reference in New Issue
Block a user