This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
use Magento\Framework\Exception\AuthorizationException;
use Magento\Framework\Webapi\Exception as WebapiException;
/**
* Base class for all Service based routing tests
*/
abstract class BaseService extends \Magento\TestFramework\TestCase\WebapiAbstract
{
/**
* Check a particular adapter and assert unauthorized access
*
* @param array $serviceInfo
* @param array|null $requestData
*/
protected function assertUnauthorizedException($serviceInfo, $requestData = null)
{
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$this->_assertSoapException(
$serviceInfo,
$requestData,
"The consumer isn't authorized to access %resources."
);
} elseif (TESTS_WEB_API_ADAPTER == self::ADAPTER_REST) {
$this->_assertRestUnauthorizedException($serviceInfo, $requestData);
}
}
/**
* Invoke the REST api and assert access is unauthorized
*
* @param array $serviceInfo
* @param array|null $requestData
*/
protected function _assertRestUnauthorizedException($serviceInfo, $requestData = null)
{
try {
$this->_webApiCall($serviceInfo, $requestData);
} catch (\Exception $e) {
$this->assertStringContainsString(
'{"message":"The consumer isn\'t authorized to access %resources.',
$e->getMessage(),
sprintf(
'REST routing did not fail as expected for the method "%s" of service "%s"',
$serviceInfo['rest']['httpMethod'],
$serviceInfo['rest']['resourcePath']
)
);
$this->assertEquals(WebapiException::HTTP_UNAUTHORIZED, $e->getCode());
}
}
/**
* Check a particular adapter and assert the exception
*
* @param array $serviceInfo
* @param array|null $requestData
*/
protected function _assertNoRouteOrOperationException($serviceInfo, $requestData = null)
{
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$this->_assertSoapException($serviceInfo, $requestData);
} elseif (TESTS_WEB_API_ADAPTER == self::ADAPTER_REST) {
$this->_assertNoRestRouteException($serviceInfo, $requestData);
}
}
/**
* Invoke the REST api and assert for test cases that no such REST route exist
*
* @param array $serviceInfo
* @param array|null $requestData
*/
protected function _assertNoRestRouteException($serviceInfo, $requestData = null)
{
try {
$this->_webApiCall($serviceInfo, $requestData);
} catch (\Exception $e) {
$error = json_decode($e->getMessage(), true);
$this->assertEquals('Request does not match any route.', $error['message']);
$this->assertEquals(WebapiException::HTTP_NOT_FOUND, $e->getCode());
}
}
/**
* Invoke the SOAP api and assert for the NoWebApiXmlTestTest test cases that no such SOAP route exists
*
* @param array $serviceInfo
* @param array|null $requestData
* @param string $expectedMessage
*/
protected function _assertSoapException($serviceInfo, $requestData = null, $expectedMessage = '')
{
try {
$this->_webApiCall($serviceInfo, $requestData);
} catch (\Exception $e) {
if (get_class($e) !== 'SoapFault') {
$this->fail(
sprintf(
'Expected SoapFault exception not generated for Service - "%s" and Operation - "%s"',
$serviceInfo['soap']['service'],
$serviceInfo['soap']['operation']
)
);
}
if ($expectedMessage) {
$this->assertStringContainsString($expectedMessage, $e->getMessage());
}
}
}
}
@@ -0,0 +1,122 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Class to test Core Web API routing
*/
namespace Magento\Webapi\Routing;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Integration\Model\Integration;
use Magento\TestFramework\Authentication\OauthHelper;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\Webapi\Adapter\Rest\RestClient;
class CoreRoutingTest extends BaseService
{
public function testBasicRoutingExplicitPath()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/testmodule1/' . $itemId,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'testModule1AllSoapAndRestV1',
'operation' => 'testModule1AllSoapAndRestV1Item',
],
];
$requestData = ['itemId' => $itemId];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals('testProduct1', $item['name'], "Item was retrieved unsuccessfully");
}
public function testDisabledIntegrationAuthorizationException()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/testmodule1/' . $itemId,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'testModule1AllSoapAndRestV1',
'operation' => 'testModule1AllSoapAndRestV1Item',
],
];
$requestData = ['itemId' => $itemId];
/** Disable integration associated with active OAuth credentials. */
$credentials = OauthHelper::getApiAccessCredentials();
/** @var Integration $integration */
$integration = $credentials['integration'];
$originalStatus = $integration->getStatus();
$integration->setStatus(Integration::STATUS_INACTIVE)->save();
try {
$this->assertUnauthorizedException($serviceInfo, $requestData);
} catch (\Exception $e) {
/** Restore original status of integration associated with active OAuth credentials */
$integration->setStatus($originalStatus)->save();
throw $e;
}
$integration->setStatus($originalStatus)->save();
}
public function testExceptionSoapInternalError()
{
$this->_markTestAsSoapOnly();
$serviceInfo = [
'soap' => [
'service' => 'testModule3ErrorV1',
'operation' => 'testModule3ErrorV1ServiceException',
],
];
$this->expectException('SoapFault');
$this->expectExceptionMessage('Generic service exception');
$this->_webApiCall($serviceInfo);
}
public function testRestNoAcceptHeader()
{
$this->_markTestAsRestOnly();
/** @var $curlClient RestClient */
$curlClient = Bootstrap::getObjectManager()->get(
RestClient::class
);
$response = $curlClient->get('/V1/testmodule1/resource1/1', [], ['Accept:']);
$this->assertEquals('testProduct1', $response['name'], "Empty Accept header failed to return response.");
}
/**
* Verifies that exception is thrown when the request contains unexpected parameters.
*
* @return void
*/
public function testRequestParamsUnexpectedValueException(): void
{
$this->_markTestAsRestOnly();
$expectedMessage = "Internal Error. Details are available in Magento log file. Report ID: webapi-";
$unexpectedMessage = "\"%fieldName\" is required. Enter and try again.";
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/testmodule1/withParam',
'httpMethod' => Request::HTTP_METHOD_PUT,
],
];
try {
$this->_webApiCall($serviceInfo);
} catch (\Exception $e) {
$exceptionResult = $this->processRestExceptionResult($e);
$actualMessage = $exceptionResult['message'];
$this->assertStringNotContainsString($unexpectedMessage, $actualMessage);
$this->assertStringContainsString($expectedMessage, $actualMessage);
}
}
}
@@ -0,0 +1,55 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
use Magento\TestModule5\Service\V1\Entity\AllSoapAndRest;
class GettersTest extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
protected $_version;
/**
* @var string
*/
protected $_restResourcePath;
/**
* @var string
*/
protected $_soapService = 'testModule5AllSoapAndRest';
protected function setUp(): void
{
$this->_version = 'V1';
$this->_soapService = "testModule5AllSoapAndRest{$this->_version}";
$this->_restResourcePath = "/{$this->_version}/TestModule5/";
}
public function testGetters()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => $this->_soapService,
'operation' => $this->_soapService . 'Item',
],
];
$requestData = [AllSoapAndRest::ID => $itemId];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($itemId, $item[AllSoapAndRest::ID], 'Item was retrieved unsuccessfully');
$isEnabled = isset($item[AllSoapAndRest::ENABLED]) && $item[AllSoapAndRest::ENABLED] === true;
$this->assertTrue($isEnabled, 'Getter with "is" prefix is processed incorrectly.');
$hasOrder = isset($item[AllSoapAndRest::HAS_ORDERS]) && $item[AllSoapAndRest::HAS_ORDERS] === true;
$this->assertTrue($hasOrder, 'Getter with "has" prefix is processed incorrectly.');
}
}
@@ -0,0 +1,111 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
/**
* Class to test routing with a service that has no webapi.xml
*/
class NoWebApiXmlTest extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
private $_version;
/**
* @var string
*/
private $_restResourcePath;
protected function setUp(): void
{
$this->_version = 'V1';
$this->_restResourcePath = "/{$this->_version}/testModule2NoWebApiXml/";
}
/**
* Test get item
*/
public function testItem()
{
$this->_markTestAsRestOnly();
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
$requestData = ['id' => $itemId];
$this->_assertNoRestRouteException($serviceInfo, $requestData);
}
/**
* Test fetching all items
*/
public function testItems()
{
$this->_markTestAsRestOnly();
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
];
$this->_assertNoRestRouteException($serviceInfo);
}
/**
* Test create item
*/
public function testCreate()
{
$this->_markTestAsRestOnly();
$createdItemName = 'createdItemName';
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
];
$requestData = ['name' => $createdItemName];
$this->_assertNoRestRouteException($serviceInfo, $requestData);
}
/**
* Test update item
*/
public function testUpdate()
{
$this->_markTestAsRestOnly();
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$requestData = ['id' => $itemId];
$this->_assertNoRestRouteException($serviceInfo, $requestData);
}
/**
* Test remove item
*/
public function testRemove()
{
$this->_markTestAsRestOnly();
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
];
$requestData = ['id' => $itemId];
$this->_assertNoRestRouteException($serviceInfo, $requestData);
}
}
@@ -0,0 +1,157 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class to test overriding request body identifier property with id passed in url path parameter
*
* Refer to \Magento\Framework\Webapi\Rest\Request::overrideRequestBodyIdWithPathParam
*/
class RequestIdOverrideTest extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
protected $_version;
/**
* @var string
*/
protected $_restResourcePath;
/**
* @var \Magento\TestModule5\Service\V1\Entity\AllSoapAndRestFactory
*/
protected $itemFactory;
/**
* @var string
*/
protected $_soapService = 'testModule5AllSoapAndRest';
protected function setUp(): void
{
$this->_markTestAsRestOnly('Request Id overriding is a REST based feature.');
$this->_version = 'V1';
$this->_restResourcePath = "/{$this->_version}/TestModule5/";
$this->itemFactory = Bootstrap::getObjectManager()
->create(\Magento\TestModule5\Service\V1\Entity\AllSoapAndRestFactory::class);
}
public function testOverride()
{
$itemId = 1;
$incorrectItemId = 2;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$item = $this->itemFactory->create()
->setEntityId($incorrectItemId)
->setName('test');
$requestData = ['entityItem' => $item->__toArray()];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(
$itemId,
$item[\Magento\TestModule5\Service\V1\Entity\AllSoapAndRest::ID],
'Identifier overriding failed.'
);
}
public function testOverrideNested()
{
$firstItemId = 1;
$secondItemId = 11;
$incorrectItemId = 2;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $firstItemId . '/nestedResource/' . $secondItemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$item = $this->itemFactory->create()
->setEntityId($incorrectItemId)
->setName('test');
$requestData = ['entityItem' => $item->__toArray()];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(
$secondItemId,
$item[\Magento\TestModule5\Service\V1\Entity\AllSoapAndRest::ID],
'Identifier overriding failed for nested resource request.'
);
}
public function testOverrideAdd()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$item = $this->itemFactory->create()
->setName('test');
$requestData = ['entityItem' => $item->__toArray()];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(
$itemId,
$item[\Magento\TestModule5\Service\V1\Entity\AllSoapAndRest::ID],
'Identifier replacing failed.'
);
}
/**
* Test if the framework works if camelCase path parameters are provided instead of valid snake case ones.
* Webapi Framework currently accepts both cases due to shortcoming in Serialization (MAGETWO-29833).
* Unless it is fixed this use case is valid.
*/
public function testAddCaseMismatch()
{
$itemId = 1;
$incorrectItemId = 2;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$requestData = ['entityItem' => ['entityId' => $incorrectItemId, 'name' => 'test']];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(
$itemId,
$item[\Magento\TestModule5\Service\V1\Entity\AllSoapAndRest::ID],
'Identifier overriding failed.'
);
}
public function testOverrideWithScalarValues()
{
$firstItemId = 1;
$secondItemId = 11;
$incorrectItemId = 2;
$serviceInfo = [
'rest' => [
'resourcePath' => "/{$this->_version}/TestModule5/OverrideService/" . $firstItemId
. '/nestedResource/' . $secondItemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$requestData = ['entity_id' => $incorrectItemId, 'name' => 'test', 'orders' => true];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(
$secondItemId,
$item[\Magento\TestModule5\Service\V1\Entity\AllSoapAndRest::ID],
'Identifier overriding failed.'
);
}
}
@@ -0,0 +1,162 @@
<?php
/**
* Test Web API error codes.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Webapi\Exception as WebapiException;
class RestErrorHandlingTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
/**
* @var string
*/
protected $mode;
protected function setUp(): void
{
$this->_markTestAsRestOnly();
$this->mode = Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class)->getMode();
parent::setUp();
}
public function testSuccess()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/errortest/success',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
$item = $this->_webApiCall($serviceInfo);
// TODO: check Http Status = 200, cannot do yet due to missing header info returned
$this->assertEquals('a good id', $item['value'], 'Success case is correct');
}
public function testNotFound()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/errortest/notfound',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
// \Magento\Framework\Api\ResourceNotFoundException
$this->_errorTest(
$serviceInfo,
['resourceY'],
WebapiException::HTTP_NOT_FOUND,
'Resource with ID "%1" not found.'
);
}
public function testUnauthorized()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/errortest/unauthorized',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
// \Magento\Framework\Api\AuthorizationException
$this->_errorTest(
$serviceInfo,
[],
WebapiException::HTTP_UNAUTHORIZED,
"The consumer isn't authorized to access %1.",
['resourceN']
);
}
public function testOtherException()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/errortest/otherException',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
/* TODO : Fix as part MAGETWO-31330
$expectedMessage = $this->mode == \Magento\Framework\App\State::MODE_DEVELOPER
? 'Non service exception'
: 'Internal Error. Details are available in Magento log file. Report ID: webapi-XXX';
*/
$expectedMessage = 'Internal Error. Details are available in Magento log file. Report ID: webapi-XXX';
$this->_errorTest(
$serviceInfo,
[],
WebapiException::HTTP_INTERNAL_ERROR,
$expectedMessage,
null,
'Magento\TestModule3\Service\V1\Error->otherException()' // Check if trace contains proper error source
);
}
/**
* Perform a negative REST api call test case and compare the results with expected values.
*
* @param string $serviceInfo - REST Service information (i.e. resource path and HTTP method)
* @param array $data - Data for the cal
* @param int $httpStatus - Expected HTTP status
* @param string|array $errorMessage - \Exception error message
* @param array $parameters - Optional parameters array, or null if no parameters
* @param string $traceString - Optional trace string to verify
*/
protected function _errorTest(
$serviceInfo,
$data,
$httpStatus,
$errorMessage,
$parameters = [],
$traceString = null
) {
try {
$this->_webApiCall($serviceInfo, $data);
} catch (\Exception $e) {
$this->assertEquals($httpStatus, $e->getCode(), 'Checking HTTP status code');
$body = json_decode($e->getMessage(), true);
$errorMessages = is_array($errorMessage) ? $errorMessage : [$errorMessage];
$actualMessage = $body['message'];
$matches = [];
//Report ID was created dynamically, so we need to replace it with some static value in order to test
if (preg_match('/.*Report\sID\:\s([a-zA-Z0-9\-]*)/', $actualMessage, $matches)) {
$actualMessage = str_replace($matches[1], 'webapi-XXX', $actualMessage);
}
//make sure that the match for a report with an id is found if Internal error was reported
//Refer : \Magento\Framework\Webapi\ErrorProcessor::INTERNAL_SERVER_ERROR_MSG
if (count($matches) > 1) {
$this->assertTrue(!empty($matches[1]), 'Report id missing for internal error.');
}
$this->assertContains(
$actualMessage,
$errorMessages,
"Message is invalid. Actual: '{$actualMessage}'. Expected one of: {'" . implode(
"', '",
$errorMessages
) . "'}"
);
if ($parameters) {
$this->assertEquals($parameters, $body['parameters'], 'Checking body parameters');
}
if ($this->mode == \Magento\Framework\App\State::MODE_DEVELOPER && $traceString) {
// TODO : Fix as part MAGETWO-31330
//$this->assertContains($traceString, $body['trace'], 'Trace information is incorrect.');
}
}
}
}
@@ -0,0 +1,276 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Class to test routing based on Service Versioning(for V1 version of a service)
*/
namespace Magento\Webapi\Routing;
use Magento\Framework\Api\AttributeValue;
use Magento\TestFramework\Authentication\OauthHelper;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestModule1\Service\V1\Entity\Item;
use Magento\TestModule1\Service\V1\Entity\ItemFactory;
class ServiceVersionV1Test extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
protected $_version;
/**
* @var string
*/
protected $_restResourcePath;
/**
* @var string
*/
protected $_soapService = 'testModule1AllSoapAndRest';
/** @var \Magento\Framework\Api\AttributeValueFactory */
protected $valueFactory;
/** @var ItemFactory */
protected $itemFactory;
protected function setUp(): void
{
$this->_version = 'V1';
$this->_soapService = 'testModule1AllSoapAndRestV1';
$this->_restResourcePath = "/{$this->_version}/testmodule1/";
$this->valueFactory = Bootstrap::getObjectManager()->create(
\Magento\Framework\Api\AttributeValueFactory::class
);
$this->itemFactory = Bootstrap::getObjectManager()->create(
\Magento\TestModule1\Service\V1\Entity\ItemFactory::class
);
}
/**
* Test get item
*/
public function testItem()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Item'],
];
$requestData = ['itemId' => $itemId];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals('testProduct1', $item['name'], 'Item was retrieved unsuccessfully');
}
/**
* Test get item with any type
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function testItemAnyType()
{
$this->_markTestAsRestOnly('Test will fail for SOAP because attribute values get converted to strings.');
$customerAttributes = [
Item::CUSTOM_ATTRIBUTE_1 => [
AttributeValue::ATTRIBUTE_CODE => Item::CUSTOM_ATTRIBUTE_1,
AttributeValue::VALUE => '12345',
],
Item::CUSTOM_ATTRIBUTE_2 => [
AttributeValue::ATTRIBUTE_CODE => Item::CUSTOM_ATTRIBUTE_2,
AttributeValue::VALUE => 12345,
],
Item::CUSTOM_ATTRIBUTE_3 => [
AttributeValue::ATTRIBUTE_CODE => Item::CUSTOM_ATTRIBUTE_3,
AttributeValue::VALUE => true,
],
];
$attributeValue1 = $this->valueFactory->create()
->setAttributeCode(Item::CUSTOM_ATTRIBUTE_1)
->setValue('12345');
$attributeValue2 = $this->valueFactory->create()
->setAttributeCode(Item::CUSTOM_ATTRIBUTE_2)
->setValue(12345);
$attributeValue3 = $this->valueFactory->create()
->setAttributeCode(Item::CUSTOM_ATTRIBUTE_3)
->setValue(true);
$item = $this->itemFactory->create()
->setItemId(1)
->setName('testProductAnyType')
->setCustomAttributes([$attributeValue1, $attributeValue2, $attributeValue3]);
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . 'itemAnyType',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'ItemAnyType'],
];
$requestData = $item->__toArray();
$item = $this->_webApiCall($serviceInfo, ['entityItem' => $requestData]);
$this->assertSame(
$attributeValue1->getValue(),
$item['custom_attributes'][0]['value'],
'Serialized attribute value type does\'t match pre-defined type.'
); // string '12345' is expected
$this->assertSame(
$attributeValue2->getValue(),
$item['custom_attributes'][1]['value'],
'Serialized attribute value type does\'t match pre-defined type.'
); // integer 12345 is expected
$this->assertSame(
$attributeValue3->getValue(),
$item['custom_attributes'][2]['value'],
'Serialized attribute value type does\'t match pre-defined type.'
); // boolean true is expected
}
/**
* Test fetching all items
*/
public function testItems()
{
$itemArr = [['item_id' => 1, 'name' => 'testProduct1'], ['item_id' => 2, 'name' => 'testProduct2']];
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Items'],
];
$item = $this->_webApiCall($serviceInfo);
$this->assertEquals($itemArr, $item, 'Items were not retrieved');
}
/**
* Test create item
*/
public function testCreate()
{
$createdItemName = 'createdItemName';
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Create'],
];
$requestData = ['name' => $createdItemName];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($createdItemName, $item['name'], 'Item creation failed');
}
/**
* Test create item with missing proper resources
*/
public function testCreateWithoutResources()
{
$createdItemName = 'createdItemName';
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Create'],
];
$requestData = ['name' => $createdItemName];
// getting new credentials that do not match the api resources
OauthHelper::clearApiAccessCredentials();
OauthHelper::getApiAccessCredentials([]);
try {
$this->assertUnauthorizedException($serviceInfo, $requestData);
} catch (\Exception $e) {
OauthHelper::clearApiAccessCredentials();
throw $e;
}
// to allow good credentials to be restored (this is statically stored on OauthHelper)
OauthHelper::clearApiAccessCredentials();
}
/**
* Test update item
*/
public function testUpdate()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Update'],
];
$requestData = ['entityItem' => ['itemId' => $itemId, 'name' => 'testName']];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals('Updated' . $requestData['entityItem']['name'], $item['name'], 'Item update failed');
}
/**
* Negative Test: Invoking non-existent delete api which is only available in V2
*/
public function testDelete()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Delete'],
];
$requestData = ['itemId' => $itemId, 'name' => 'testName'];
$this->_assertNoRouteOrOperationException($serviceInfo, $requestData);
}
public function testOverwritten()
{
$this->_markTestAsRestOnly();
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . 'overwritten',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
];
$item = $this->_webApiCall($serviceInfo, []);
$this->assertEquals(['item_id' => -55, 'name' => 'testProduct1'], $item);
}
public function testDefaulted()
{
$this->_markTestAsRestOnly();
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . 'testOptionalParam',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
];
$item = $this->_webApiCall($serviceInfo, []);
$this->assertEquals(['item_id' => 3, 'name' => 'Default Name'], $item);
}
public function testDefaultedWithValue()
{
$this->_markTestAsRestOnly();
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . 'testOptionalParam',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
];
$item = $this->_webApiCall($serviceInfo, ['name' => 'Ms. LaGrange']);
$this->assertEquals(['item_id' => 3, 'name' => 'Ms. LaGrange'], $item);
}
}
@@ -0,0 +1,161 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
class ServiceVersionV2Test extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
private $version;
/**
* @var string
*/
private $soapService;
/**
* @var string
*/
private $restResourcePath;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->version = 'V2';
$this->soapService = 'testModule1AllSoapAndRestV2';
$this->restResourcePath = "/{$this->version}/testmodule1/";
}
/**
* Test to assert overriding of the existing 'Item' api in V2 version of the same service
*/
public function testItem()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => ['service' => $this->soapService, 'operation' => $this->soapService . 'Item'],
];
$requestData = ['id' => $itemId];
$item = $this->_webApiCall($serviceInfo, $requestData);
// Asserting for additional attribute returned by the V2 api
$this->assertEquals(1, $item['price'], 'Item was retrieved unsuccessfully from V2');
}
/**
* Test fetching all items
*/
public function testItems()
{
$itemArr = [
['id' => 1, 'name' => 'testProduct1', 'price' => '1'],
['id' => 2, 'name' => 'testProduct2', 'price' => '2'],
];
$serviceInfo = [
'rest' => [
'resourcePath' => $this->restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => ['service' => $this->soapService, 'operation' => $this->soapService . 'Items'],
];
$item = $this->_webApiCall($serviceInfo);
$this->assertEquals($itemArr, $item, 'Items were not retrieved');
}
/**
* Test fetching items when filters are applied
*
* @param string[] $filters
* @param array $expectedResult
* @dataProvider itemsWithFiltersDataProvider
*/
public function testItemsWithFilters($filters, $expectedResult)
{
$restFilter = '';
foreach ($filters as $filterItemKey => $filterMetadata) {
foreach ($filterMetadata as $filterMetaKey => $filterMetaValue) {
$paramsDelimiter = empty($restFilter) ? '?' : '&';
$restFilter .= "{$paramsDelimiter}filters[{$filterItemKey}][{$filterMetaKey}]={$filterMetaValue}";
}
}
$serviceInfo = [
'rest' => [
'resourcePath' => $this->restResourcePath . $restFilter,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => $this->soapService,
'operation' => $this->soapService . 'Items',
],
];
$requestData = [];
if (!empty($filters)) {
$requestData['filters'] = $filters;
}
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($expectedResult, $item, 'Filtration does not seem to work correctly.');
}
public function itemsWithFiltersDataProvider()
{
$firstItem = ['id' => 1, 'name' => 'testProduct1', 'price' => 1];
$secondItem = ['id' => 2, 'name' => 'testProduct2', 'price' => 2];
return [
'Both items filter' => [
[
['field' => 'id', 'conditionType' => 'eq','value' => 1],
['field' => 'id', 'conditionType' => 'eq','value' => 2],
],
[$firstItem, $secondItem],
],
'First item filter' => [[['field' => 'id', 'conditionType' => 'eq','value' => 1]], [$firstItem]],
'Second item filter' => [[['field' => 'id', 'conditionType' => 'eq','value' => 2]], [$secondItem]],
'Empty filter' => [[], [$firstItem, $secondItem]],
];
}
/**
* Test update item
*/
public function testUpdate()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => ['service' => $this->soapService, 'operation' => $this->soapService . 'Update'],
];
$requestData = ['entityItem' => ['id' => $itemId, 'name' => 'testName', 'price' => '4']];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals('Updated' . $requestData['entityItem']['name'], $item['name'], 'Item update failed');
}
/**
* Test to assert presence of new 'delete' api added in V2 version of the same service
*/
public function testDelete()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => ['service' => $this->soapService, 'operation' => $this->soapService . 'Delete'],
];
$requestData = ['id' => $itemId, 'name' => 'testName'];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($itemId, $item['id'], "Item delete failed");
}
}
@@ -0,0 +1,160 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Routing;
use Magento\Framework\Exception\AuthorizationException;
/**
* SOAP error handling test.
*/
class SoapErrorHandlingTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
protected function setUp(): void
{
$this->_markTestAsSoapOnly();
parent::setUp();
}
public function testWebapiException()
{
$serviceInfo = [
'soap' => [
'service' => 'testModule3ErrorV1',
'operation' => 'testModule3ErrorV1WebapiException',
],
];
try {
$this->_webApiCall($serviceInfo);
$this->fail("SoapFault was not raised as expected.");
} catch (\SoapFault $e) {
$this->checkSoapFault(
$e,
'Service not found',
'env:Sender'
);
}
}
public function testUnknownException()
{
$serviceInfo = [
'soap' => [
'service' => 'testModule3ErrorV1',
'operation' => 'testModule3ErrorV1OtherException',
],
];
try {
$this->_webApiCall($serviceInfo);
$this->fail("SoapFault was not raised as expected.");
} catch (\SoapFault $e) {
/** In developer mode message is masked, so checks should be different in two modes */
if (strpos($e->getMessage(), 'Internal Error') === false) {
$this->checkSoapFault(
$e,
'Non service exception',
'env:Receiver',
null,
null,
'Magento\TestModule3\Service\V1\Error->otherException()'
);
} else {
$this->checkSoapFault(
$e,
'Internal Error. Details are available in Magento log file. Report ID:',
'env:Receiver'
);
}
}
}
public function testEmptyInputException()
{
$parameters = [];
$this->_testWrappedError($parameters);
}
public function testSingleWrappedErrorException()
{
$parameters = [
['fieldName' => 'key1', 'value' => 'value1'],
];
$this->_testWrappedError($parameters);
}
public function testMultipleWrappedErrorException()
{
$parameters = [
['fieldName' => 'key1', 'value' => 'value1'],
['fieldName' => 'key2', 'value' => 'value2'],
];
$this->_testWrappedError($parameters);
}
public function testUnauthorized()
{
$serviceInfo = [
'soap' => [
'service' => 'testModule3ErrorV1',
'operation' => 'testModule3ErrorV1AuthorizationException',
'token' => 'invalidToken',
],
];
try {
$this->_webApiCall($serviceInfo);
$this->fail("SoapFault was not raised as expected.");
} catch (\SoapFault $e) {
$this->checkSoapFault(
$e,
"The consumer isn't authorized to access %resources.",
'env:Sender'
);
}
}
protected function _testWrappedError($parameters)
{
$serviceInfo = [
'soap' => [
'service' => 'testModule3ErrorV1',
'operation' => 'testModule3ErrorV1InputException',
],
];
$expectedException = new \Magento\Framework\Exception\InputException();
foreach ($parameters as $error) {
$expectedException->addError(
__('Invalid value of "%value" provided for the %fieldName field.', $error)
);
}
$arguments = [
'wrappedErrorParameters' => $parameters,
];
$expectedErrors = [];
foreach ($expectedException->getErrors() as $key => $error) {
$expectedErrors[$key] = [
'message' => $error->getRawMessage(),
'params' => $error->getParameters(),
];
}
try {
$this->_webApiCall($serviceInfo, $arguments);
$this->fail("SoapFault was not raised as expected.");
} catch (\SoapFault $e) {
$this->checkSoapFault(
$e,
$expectedException->getRawMessage(),
'env:Sender',
$expectedException->getParameters(), // expected error parameters
$expectedErrors // expected wrapped errors
);
}
}
}
@@ -0,0 +1,76 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Class to test routing based on a Service that exposes subset of operations
*/
namespace Magento\Webapi\Routing;
class SubsetTest extends \Magento\Webapi\Routing\BaseService
{
/**
* @var string
*/
protected $_version;
/**
* @var string
*/
protected $_restResourcePath;
/**
* @var string
*/
protected $_soapService;
/**
* @Override
*/
protected function setUp(): void
{
$this->_version = 'V1';
$this->_restResourcePath = "/{$this->_version}/testModule2SubsetRest/";
$this->_soapService = 'testModule2SubsetRestV1';
}
/**
* @Override
* Test get item
*/
public function testItem()
{
$itemId = 1;
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath . $itemId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Item'],
];
$requestData = ['id' => $itemId];
$item = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($itemId, $item['id'], 'Item was retrieved unsuccessfully');
}
/**
* @Override
* Test fetching all items
*/
public function testItems()
{
$itemArr = [['id' => 1, 'name' => 'testItem1'], ['id' => 2, 'name' => 'testItem2']];
$serviceInfo = [
'rest' => [
'resourcePath' => $this->_restResourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => ['service' => $this->_soapService, 'operation' => $this->_soapService . 'Items'],
];
$item = $this->_webApiCall($serviceInfo);
$this->assertEquals($itemArr, $item, 'Items were not retrieved');
}
}