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,236 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;
class AttributeSetManagementTest extends WebapiAbstract
{
/**
* @var array
*/
private $createServiceInfo;
protected function setUp(): void
{
$this->createServiceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => 'catalogAttributeSetManagementV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetManagementV1Create',
],
];
}
public function testCreate()
{
$entityTypeCode = 'catalog_product';
$entityType = $this->getEntityTypeByCode($entityTypeCode);
$attributeSetName = 'new_attribute_set';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 500,
],
'skeletonId' => $entityType->getDefaultAttributeSetId(),
];
$result = $this->_webApiCall($this->createServiceInfo, $arguments);
$this->assertNotNull($result);
$attributeSet = $this->getAttributeSetByName($attributeSetName);
$this->assertNotNull($attributeSet);
$this->assertEquals($attributeSet->getId(), $result['attribute_set_id']);
$this->assertEquals($attributeSet->getAttributeSetName(), $result['attribute_set_name']);
$this->assertEquals($attributeSet->getEntityTypeId(), $result['entity_type_id']);
$this->assertEquals($attributeSet->getEntityTypeId(), $entityType->getId());
$this->assertEquals($attributeSet->getSortOrder(), $result['sort_order']);
$this->assertEquals($attributeSet->getSortOrder(), 500);
// Clean up database
$attributeSet->delete();
}
/**
*/
public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Invalid value');
$entityTypeCode = 'catalog_product';
$entityType = $this->getEntityTypeByCode($entityTypeCode);
$attributeSetName = 'new_attribute_set';
$arguments = [
'attributeSet' => [
'attribute_set_id' => 1,
'attribute_set_name' => $attributeSetName,
'sort_order' => 100,
],
'skeletonId' => $entityType->getDefaultAttributeSetId(),
];
$this->_webApiCall($this->createServiceInfo, $arguments);
}
/**
*/
public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid()
{
$this->expectException(\Exception::class);
$attributeSetName = 'new_attribute_set';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 200,
],
'skeletonId' => 0,
];
$this->_webApiCall($this->createServiceInfo, $arguments);
$this->expectExceptionMessage(
"The attribute set couldn't be created because it's based on a non-existing attribute set."
);
}
/**
*/
public function testCreateThrowsExceptionIfGivenSkeletonIdHasWrongEntityType()
{
$this->expectException(\Exception::class);
$attributeSetName = 'new_attribute_set';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 200,
],
'skeletonId' => 7,
];
$this->_webApiCall($this->createServiceInfo, $arguments);
$this->expectExceptionMessage(
"The attribute set couldn't be created because it's based on a non-product attribute set."
);
}
/**
*/
public function testCreateThrowsExceptionIfGivenSkeletonAttributeSetDoesNotExist()
{
$this->expectException(\Exception::class);
$attributeSetName = 'new_attribute_set';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 300,
],
'skeletonId' => 9999,
];
$this->_webApiCall($this->createServiceInfo, $arguments);
$this->expectExceptionMessage(
"The attribute set couldn't be created because it's based on a non-existing attribute set."
);
}
/**
*/
public function testCreateThrowsExceptionIfAttributeSetNameIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The attribute set name is empty. Enter the name and try again.');
$entityTypeCode = 'catalog_product';
$entityType = $this->getEntityTypeByCode($entityTypeCode);
$attributeSetName = '';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 500,
],
'skeletonId' => $entityType->getDefaultAttributeSetId(),
];
$this->_webApiCall($this->createServiceInfo, $arguments);
}
public function testCreateThrowsExceptionIfAttributeSetWithGivenNameAlreadyExists()
{
$entityTypeCode = 'catalog_product';
$entityType = $this->getEntityTypeByCode($entityTypeCode);
$attributeSetName = 'Default';
$expectedMessage = 'A "Default" attribute set name already exists. Create a new name and try again.';
$arguments = [
'attributeSet' => [
'attribute_set_name' => $attributeSetName,
'sort_order' => 550,
],
'skeletonId' => $entityType->getDefaultAttributeSetId(),
];
try {
$this->_webApiCall($this->createServiceInfo, $arguments);
$this->fail("Expected exception");
} catch (\SoapFault $e) {
$this->assertStringContainsString(
$expectedMessage,
$e->getMessage(),
"SoapFault does not contain expected message."
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals(
$expectedMessage,
$errorObj['message']
);
$this->assertEquals(HTTPExceptionCodes::HTTP_BAD_REQUEST, $e->getCode());
}
}
/**
* Retrieve attribute set based on given name.
* This utility methods assumes that there is only one attribute set with given name,
*
* @param string $attributeSetName
* @return \Magento\Eav\Model\Entity\Attribute\Set|null
*/
protected function getAttributeSetByName($attributeSetName)
{
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */
$attributeSet = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Set::class)
->load($attributeSetName, 'attribute_set_name');
if ($attributeSet->getId() === null) {
return null;
}
return $attributeSet;
}
/**
* Retrieve entity type based on given code.
*
* @param string $entityTypeCode
* @return \Magento\Eav\Model\Entity\Type|null
*/
protected function getEntityTypeByCode($entityTypeCode)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Eav\Model\Entity\Type $entityType */
$entityType = $objectManager->create(\Magento\Eav\Model\Config::class)
->getEntityType($entityTypeCode);
return $entityType;
}
}
@@ -0,0 +1,220 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class AttributeSetRepositoryTest extends WebapiAbstract
{
/**
* @magentoApiDataFixture Magento/Eav/_files/empty_attribute_set.php
*/
public function testGet()
{
$attributeSetName = 'empty_attribute_set';
$attributeSet = $this->getAttributeSetByName($attributeSetName);
$attributeSetId = $attributeSet->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/' . $attributeSetId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1Get',
],
];
$arguments = [
'attributeSetId' => $attributeSetId,
];
$result = $this->_webApiCall($serviceInfo, $arguments);
$this->assertNotNull($result);
$this->assertEquals($attributeSet->getId(), $result['attribute_set_id']);
$this->assertEquals($attributeSet->getAttributeSetName(), $result['attribute_set_name']);
$this->assertEquals($attributeSet->getEntityTypeId(), $result['entity_type_id']);
$this->assertEquals($attributeSet->getSortOrder(), $result['sort_order']);
}
/**
*/
public function testGetThrowsExceptionIfRequestedAttributeSetDoesNotExist()
{
$this->expectException(\Exception::class);
$attributeSetId = 9999;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/' . $attributeSetId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1Get',
],
];
$arguments = [
'attributeSetId' => $attributeSetId,
];
$this->_webApiCall($serviceInfo, $arguments);
}
/**
* @magentoApiDataFixture Magento/Eav/_files/empty_attribute_set.php
*/
public function testSave()
{
$attributeSetName = 'empty_attribute_set';
$attributeSet = $this->getAttributeSetByName($attributeSetName);
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/' . $attributeSet->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1Save',
],
];
$updatedSortOrder = $attributeSet->getSortOrder() + 200;
$arguments = [
'attributeSet' => [
'attribute_set_id' => $attributeSet->getId(),
// name is the same, because it is used by fixture rollback script
'attribute_set_name' => $attributeSet->getAttributeSetName(),
'entity_type_id' => $attributeSet->getEntityTypeId(),
'sort_order' => $updatedSortOrder,
],
];
$result = $this->_webApiCall($serviceInfo, $arguments);
$this->assertNotNull($result);
// Reload attribute set data
$attributeSet = $this->getAttributeSetByName($attributeSetName);
$this->assertEquals($attributeSet->getAttributeSetId(), $result['attribute_set_id']);
$this->assertEquals($attributeSet->getAttributeSetName(), $result['attribute_set_name']);
$this->assertEquals($attributeSet->getEntityTypeId(), $result['entity_type_id']);
$this->assertEquals($updatedSortOrder, $result['sort_order']);
$this->assertEquals($attributeSet->getSortOrder(), $result['sort_order']);
}
/**
* @magentoApiDataFixture Magento/Eav/_files/empty_attribute_set.php
*/
public function testDeleteById()
{
$attributeSetName = 'empty_attribute_set';
$attributeSet = $this->getAttributeSetByName($attributeSetName);
$attributeSetId = $attributeSet->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/' . $attributeSetId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1DeleteById',
],
];
$arguments = [
'attributeSetId' => $attributeSetId,
];
$this->assertTrue($this->_webApiCall($serviceInfo, $arguments));
$this->assertNull($this->getAttributeSetByName($attributeSetName));
}
/**
*/
public function testDeleteByIdThrowsExceptionIfRequestedAttributeSetDoesNotExist()
{
$this->expectException(\Exception::class);
$attributeSetId = 9999;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/' . $attributeSetId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1DeleteById',
],
];
$arguments = [
'attributeSetId' => $attributeSetId,
];
$this->_webApiCall($serviceInfo, $arguments);
}
/**
* @magentoApiDataFixture Magento/Eav/_files/empty_attribute_set.php
*/
public function testGetList()
{
$searchCriteria = [
'searchCriteria' => [
'filter_groups' => [],
'current_page' => 1,
'page_size' => 2
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/attribute-sets/sets/list' . '?' . http_build_query($searchCriteria),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'catalogAttributeSetRepositoryV1',
'serviceVersion' => 'V1',
'operation' => 'catalogAttributeSetRepositoryV1GetList',
],
];
$response = $this->_webApiCall($serviceInfo, $searchCriteria);
$this->assertArrayHasKey('search_criteria', $response);
$this->assertArrayHasKey('total_count', $response);
$this->assertArrayHasKey('items', $response);
$this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
$this->assertTrue($response['total_count'] > 0);
$this->assertTrue(count($response['items']) > 0);
$this->assertNotNull($response['items'][0]['attribute_set_id']);
$this->assertNotNull($response['items'][0]['attribute_set_name']);
}
/**
* Retrieve attribute set based on given name.
* This utility methods assumes that there is only one attribute set with given name,
*
* @param string $attributeSetName
* @return \Magento\Eav\Model\Entity\Attribute\Set|null
*/
protected function getAttributeSetByName($attributeSetName)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */
$attributeSet = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Set::class)
->load($attributeSetName, 'attribute_set_name');
if ($attributeSet->getId() === null) {
return null;
}
return $attributeSet;
}
}
@@ -0,0 +1,160 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;
/**
* BasePriceStorage test.
*/
class BasePriceStorageTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogBasePriceStorageV1';
const SERVICE_VERSION = 'V1';
const SIMPLE_PRODUCT_SKU = 'simple';
/**
* @var \Magento\TestFramework\ObjectManager
*/
private $objectManager;
/**
* Set up.
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* Test get method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGet()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/base-prices-information',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertNotEmpty($response);
$this->assertEquals($product->getPrice(), $response[0]['price']);
$this->assertEquals($product->getSku(), $response[0]['sku']);
}
/**
* Test update method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testUpdate()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/base-prices',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$newPrice = 9999;
$storeId = 0;
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
[
'price' => $newPrice,
'store_id' => $storeId,
'sku' => self::SIMPLE_PRODUCT_SKU,
]
]
]
);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertEmpty($response);
$this->assertEquals($product->getPrice(), $newPrice);
}
/**
* Test update method call with invalid parameters.
*/
public function testUpdateWithInvalidParameters()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/base-prices',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$newPrice = -9999;
$storeId = 9999;
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
[
'sku' => 'not_existing_sku',
'price' => $newPrice,
'store_id' => $storeId,
]
]
]
);
$expectedResponse = [
0 => [
'message' => 'Invalid attribute %fieldName = %fieldValue.',
'parameters' => [
'SKU',
'not_existing_sku',
]
],
1 => [
'message' => 'Invalid attribute %fieldName = %fieldValue.',
'parameters' => [
'Price',
'-9999',
]
],
2 => [
'message' =>
'Requested store is not found. Row ID: SKU = not_existing_sku, Store ID: 9999.',
'parameters' => [
'not_existing_sku',
'9999'
]
]
];
$this->assertEquals($expectedResponse, $response);
}
}
@@ -0,0 +1,186 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
/**
* Class \Magento\Catalog\Api\CartItemRepositoryTest
*/
class CartItemRepositoryTest extends WebapiAbstract
{
public const SERVICE_NAME = 'quoteCartItemRepositoryV1';
public const SERVICE_VERSION = 'V1';
public const SIMPLE_PRODUCT_SKU = 'simple';
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testAddProductToCartWithCustomOptions()
{
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_order_1', 'reserved_order_id');
$cartId = $quote->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/carts/' . $cartId . '/items',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$response = $this->_webApiCall($serviceInfo, $this->getRequestData($cartId));
$this->assertTrue($quote->hasProductId($product->getId()));
$this->assertCount(1, $quote->getAllItems());
/** @var \Magento\Quote\Api\Data\CartItemInterface $item */
$item = $quote->getAllItems()[0];
$this->assertEquals(
[
'item_id' => $item->getItemId(),
'sku' => $item->getSku(),
'qty' => $item->getQty(),
'name' => $item->getName(),
'price' => $item->getPrice(),
'product_type' => $item->getProductType(),
'quote_id' => $item->getQuoteId(),
'product_option' => [
'extension_attributes' => [
'custom_options' => $this->getOptions(),
],
],
],
$response
);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/quote_with_product_and_custom_options.php
*/
public function testGetList()
{
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_order_1', 'reserved_order_id');
$cartId = $quote->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/carts/' . $cartId . '/items',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$response = $this->_webApiCall($serviceInfo, ['cartId' => $cartId]);
$this->assertGreaterThan(0, count($response));
$item = $response[0];
$this->assertNotNull($item['item_id']);
$this->assertArrayHasKey('product_option', $item);
$this->assertArrayHasKey('extension_attributes', $item['product_option']);
$this->assertArrayHasKey('custom_options', $item['product_option']['extension_attributes']);
$this->assertGreaterThan(3, count($item['product_option']['extension_attributes']['custom_options']));
$option = reset($item['product_option']['extension_attributes']['custom_options']);
$this->assertArrayHasKey('option_id', $option);
$this->assertArrayHasKey('option_value', $option);
}
/**
* Receive product options with values
*
* @return array
*/
protected function getOptions()
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$options = [];
/** @var ProductCustomOptionInterface $option */
foreach ($product->getOptions() as $option) {
$options[] = [
'option_id' => $option->getId(),
'option_value' => $this->getOptionRequestValue($option),
];
}
return $options;
}
/**
* @param $cartId
* @return array
*/
protected function getRequestData($cartId)
{
return [
'cartItem' => [
'sku' => self::SIMPLE_PRODUCT_SKU,
'qty' => 1,
'quote_id' => $cartId,
'product_option' => [
'extension_attributes' => [
'custom_options' => $this->getOptions(),
],
],
],
];
}
/**
* Receive option value based on option type
*
* @param ProductCustomOptionInterface $option
* @return null|string
*/
protected function getOptionRequestValue(ProductCustomOptionInterface $option)
{
$returnValue = null;
switch ($option->getType()) {
case 'field':
$returnValue = 'Test value';
break;
case 'date_time':
$returnValue = '2015-09-09 07:16:00';
break;
case 'drop_down':
$returnValue = current($option->getValues())->getOptionTypeId();
break;
case 'radio':
$returnValue = current($option->getValues())->getOptionTypeId();
break;
}
return $returnValue;
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class CategoryAttributeOptionManagementInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogCategoryAttributeOptionManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/categories/attributes';
public function testGetItems()
{
$this->_markTestAsRestOnly('Fix inconsistencies in WSDL and Data interfaces');
$testAttributeCode = 'include_in_menu';
$expectedOptions = [
[
'label' => 'Yes',
'value' => '1',
],
[
'label' => 'No',
'value' => '0',
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $testAttributeCode . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'getItems',
],
];
$response = $this->_webApiCall($serviceInfo, ['attributeCode' => $testAttributeCode]);
$this->assertIsArray($response);
$this->assertEquals($expectedOptions, $response);
}
}
@@ -0,0 +1,94 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
class CategoryAttributeRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogCategoryAttributeRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/categories/attributes';
/**
* @magentoApiDataFixture Magento/Catalog/_files/category_attribute.php
*/
public function testGet()
{
$attributeCode = 'test_attribute_code_666';
$attribute = $this->getAttribute($attributeCode);
$this->assertIsArray($attribute);
$this->assertArrayHasKey('attribute_id', $attribute);
$this->assertArrayHasKey('attribute_code', $attribute);
$this->assertEquals($attributeCode, $attribute['attribute_code']);
}
public function testGetList()
{
$searchCriteria = [
'searchCriteria' => [
'filter_groups' => [
[
'filters' => [
[
'field' => 'frontend_input',
'value' => 'text',
'condition_type' => 'eq',
],
],
],
],
'current_page' => 1,
'page_size' => 2,
],
'entityTypeCode' => \Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE,
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($searchCriteria),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$response = $this->_webApiCall($serviceInfo, $searchCriteria);
$this->assertArrayHasKey('search_criteria', $response);
$this->assertArrayHasKey('total_count', $response);
$this->assertArrayHasKey('items', $response);
$this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
$this->assertTrue($response['total_count'] > 0);
$this->assertTrue(count($response['items']) > 0);
$this->assertNotNull($response['items'][0]['attribute_id']);
}
/**
* @param $attributeCode
* @return array|bool|float|int|string
*/
protected function getAttribute($attributeCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
}
}
@@ -0,0 +1,80 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Represents CategoryLinkManagementTest Class
*/
class CategoryLinkManagementTest extends WebapiAbstract
{
const SERVICE_WRITE_NAME = 'catalogCategoryLinkManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH_SUFFIX = '/V1/categories';
const RESOURCE_PATH_PREFIX = 'products';
private $modelId = 333;
/**
* @magentoApiDataFixture Magento/Catalog/_files/category_product.php
*/
public function testAssignedProducts()
{
$expected = [
[
'sku' => 'simple333',
'position' => '0',
'category_id' => '333',
],
];
$result = $this->getAssignedProducts($this->modelId);
$this->assertEquals($expected, $result);
}
public function testInfoNoSuchEntityException()
{
try {
$this->getAssignedProducts(-1);
} catch (\Exception $e) {
$this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage());
}
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/categories.php
*/
public function testDuplicatedProductsInChildCategories()
{
$result = $this->getAssignedProducts(3, 'all');
$this->assertCount(3, $result);
}
/**
* @param int $id category id
* @param string|null $storeCode
* @return array|string
*/
private function getAssignedProducts(int $id, ?string $storeCode = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH_SUFFIX . '/' . $id . '/' . self::RESOURCE_PATH_PREFIX,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_WRITE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_WRITE_NAME . 'GetAssignedProducts',
],
];
return $this->_webApiCall($serviceInfo, ['categoryId' => $id], null, $storeCode);
}
}
@@ -0,0 +1,150 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
class CategoryLinkRepositoryTest extends WebapiAbstract
{
const SERVICE_WRITE_NAME = 'catalogCategoryLinkRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH_SUFFIX = '/V1/categories';
const RESOURCE_PATH_PREFIX = 'products';
private $categoryId = 333;
/**
* @dataProvider saveDataProvider
* @magentoApiDataFixture Magento/Catalog/_files/products_in_category.php
* @param int $productId
* @param string[] $productLink
* @param int $productPosition
*/
public function testSave($productLink, $productId, $productPosition = 0)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH_SUFFIX
. '/' . $this->categoryId . '/' . self::RESOURCE_PATH_PREFIX,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_WRITE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_WRITE_NAME . 'Save',
],
];
$result = $this->_webApiCall($serviceInfo, ['productLink' => $productLink]);
$this->assertTrue($result);
$this->assertTrue($this->isProductInCategory($this->categoryId, $productId, $productPosition));
}
public function saveDataProvider()
{
return [
[
['sku' => 'simple_with_cross', 'position' => 7, 'category_id' => $this->categoryId],
334,
7,
],
[
['sku' => 'simple_with_cross', 'category_id' => $this->categoryId],
334,
0
],
];
}
/**
* @dataProvider updateProductProvider
* @magentoApiDataFixture Magento/Catalog/_files/products_in_category.php
* @param int $productId
* @param string[] $productLink
* @param int $productPosition
*/
public function testUpdateProduct($productLink, $productId, $productPosition = 0)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH_SUFFIX
. '/' . $this->categoryId . '/' . self::RESOURCE_PATH_PREFIX,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_WRITE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_WRITE_NAME . 'Save',
],
];
$result = $this->_webApiCall($serviceInfo, ['productLink' => $productLink]);
$this->assertTrue($result);
$this->assertFalse($this->isProductInCategory($this->categoryId, $productId, $productPosition));
}
public function updateProductProvider()
{
return [
[
['sku' => 'simple_with_cross', 'position' => 7, 'categoryId' => $this->categoryId],
333,
4,
],
[
['sku' => 'simple_with_cross', 'categoryId' => $this->categoryId],
333,
0
],
];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_in_category.php
*/
public function testDelete()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH_SUFFIX . '/' . $this->categoryId .
'/' . self::RESOURCE_PATH_PREFIX . '/simple',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_WRITE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_WRITE_NAME . 'DeleteByIds',
],
];
$result = $this->_webApiCall(
$serviceInfo,
['sku' => 'simple', 'categoryId' => $this->categoryId]
);
$this->assertTrue($result);
$this->assertFalse($this->isProductInCategory($this->categoryId, 333, 10));
}
/**
* @param int $categoryId
* @param int $productId
* @param int $productPosition
* @return bool
*/
private function isProductInCategory($categoryId, $productId, $productPosition)
{
/** @var \Magento\Catalog\Api\CategoryRepositoryInterface $categoryLoader */
$categoryLoader = Bootstrap::getObjectManager()
->create(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
$category = $categoryLoader->get($categoryId);
$productsPosition = $category->getProductsPosition();
if (isset($productsPosition[$productId]) && $productsPosition[$productId] == $productPosition) {
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Checks the categories/list api
*/
class CategoryListTest extends WebapiAbstract
{
const RESOURCE_PATH = '/V1/categories/list';
const SERVICE_NAME = 'catalogCategoryListV1';
/**
* @magentoApiDataFixture Magento/Catalog/_files/category_tree.php
*/
public function testGetList()
{
$searchCriteria = [
'searchCriteria' => [
'filter_groups' => [
[
'filters' => [
[
'field' => 'name',
'value' => 'Category 1',
'condition_type' => 'eq',
],
[
'field' => 'name',
'value' => 'Category 1.1',
'condition_type' => 'eq',
],
],
],
],
'sort_orders' => [
[
'field' => 'name',
'direction' => 'DESC',
],
],
'current_page' => 1,
'page_size' => 2,
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($searchCriteria),
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$response = $this->_webApiCall($serviceInfo, $searchCriteria);
$this->assertArrayHasKey('search_criteria', $response);
$this->assertArrayHasKey('total_count', $response);
$this->assertArrayHasKey('items', $response);
$this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
$this->assertTrue($response['total_count'] > 0);
$this->assertTrue(count($response['items']) === 2);
$this->assertNotNull($response['items'][0]['name']);
$this->assertEquals('Category 1.1', $response['items'][0]['name']);
$this->assertEquals('Category 1', $response['items'][1]['name']);
}
}
@@ -0,0 +1,195 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\CompareArraysRecursively;
/**
* Tests CategoryManagement
*/
class CategoryManagementTest extends WebapiAbstract
{
const RESOURCE_PATH = '/V1/categories';
const SERVICE_NAME = 'catalogCategoryManagementV1';
/**
* @var CompareArraysRecursively
*/
private $compareArraysRecursively;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->compareArraysRecursively = $objectManager->create(CompareArraysRecursively::class);
}
/**
* Tests getTree operation
*
* @dataProvider treeDataProvider
* @magentoApiDataFixture Magento/Catalog/_files/category_tree.php
*/
public function testTree($rootCategoryId, $depth, $expected)
{
$requestData = ['rootCategoryId' => $rootCategoryId, 'depth' => $depth];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($requestData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'GetTree'
]
];
$result = $this->_webApiCall($serviceInfo, $requestData);
$diff = $this->compareArraysRecursively->execute($expected, $result);
self::assertEquals([], $diff, "Actual categories response doesn't equal expected data");
}
/**
* @return array
*/
public function treeDataProvider(): array
{
return [
[
2,
100,
[
'id' => 2,
'name' => 'Default Category',
'children_data' => [
[
'id' => 400,
'name' => 'Category 1',
'children_data' => [
[
'id' => 401,
'name' => 'Category 1.1',
'children_data' => [
[
'id' => 402,
'name' => 'Category 1.1.1',
'children_data' => [
]
]
]
]
]
]
]
]
],
[
2,
null,
[
'id' => 2,
'name' => 'Default Category',
'children_data' => [
[
'id' => 400,
'name' => 'Category 1',
'children_data' => [
[
'id' => 401,
'name' => 'Category 1.1',
'children_data' => [
[
'id' => 402,
'name' => 'Category 1.1.1',
'children_data' => [
]
]
]
]
]
]
]
]
],
[
400,
1,
[
'id' => 400,
'name' => 'Category 1',
'children_data' => [
[
'id' => 401,
'name' => 'Category 1.1',
'children_data' => [
]
]
]
]
],
[
400,
0,
[
'id' => 400,
'name' => 'Category 1',
'children_data' => [
]
]
],
];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category_tree.php
* @dataProvider updateMoveDataProvider
*/
public function testUpdateMove($categoryId, $parentId, $afterId, $expectedPosition)
{
$expectedPath = '1/2/400/' . $categoryId;
$categoryData = ['categoryId' => $categoryId, 'parentId' => $parentId, 'afterId' => $afterId];
$serviceInfo =
[
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $categoryId . '/move',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Move'
]
];
$this->assertTrue($this->_webApiCall($serviceInfo, $categoryData));
/** @var \Magento\Catalog\Model\Category $model */
$readService = Bootstrap::getObjectManager()->create(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
$model = $readService->get($categoryId);
$this->assertEquals($expectedPath, $model->getPath());
$this->assertEquals($expectedPosition, $model->getPosition());
$this->assertEquals($parentId, $model->getParentId());
}
public function updateMoveDataProvider()
{
return [
[402, 400, null, 2],
[402, 400, 401, 2],
[402, 400, 999, 2],
[402, 400, 0, 1]
];
}
}
@@ -0,0 +1,696 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Authorization\Model\Role;
use Magento\Authorization\Model\RoleFactory;
use Magento\Authorization\Model\Rules;
use Magento\Authorization\Model\RulesFactory;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Test\Fixture\Category as CategoryFixture;
use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator;
use Magento\Integration\Api\AdminTokenServiceInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\UrlRewrite\Model\Storage\DbStorage;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
/**
* Test repository web API.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CategoryRepositoryTest extends WebapiAbstract
{
private const RESOURCE_PATH = '/V1/categories';
private const SERVICE_NAME = 'catalogCategoryRepositoryV1';
/**
* @var int
*/
private $modelId = 333;
/**
* @var RoleFactory
*/
private $roleFactory;
/**
* @var RulesFactory
*/
private $rulesFactory;
/**
* @var AdminTokenServiceInterface
*/
private $adminTokens;
/**
* @var string[]
*/
private $createdCategories;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->roleFactory = Bootstrap::getObjectManager()->get(RoleFactory::class);
$this->rulesFactory = Bootstrap::getObjectManager()->get(RulesFactory::class);
$this->adminTokens = Bootstrap::getObjectManager()->get(AdminTokenServiceInterface::class);
$this->fixtures = Bootstrap::getObjectManager()->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category_backend.php
*/
public function testGet()
{
$expected = [
'parent_id' => 2,
'path' => '1/2/333',
'position' => 1,
'level' => 2,
'available_sort_by' => ['position', 'name'],
'include_in_menu' => true,
'name' => 'Category 1',
'id' => 333,
'is_active' => true,
];
$result = $this->getInfoCategory($this->modelId);
$this->assertArrayHasKey('created_at', $result);
$this->assertArrayHasKey('updated_at', $result);
$this->assertArrayHasKey('children', $result);
$this->assertArrayHasKey('custom_attributes', $result);
unset($result['created_at'], $result['updated_at'], $result['children'], $result['custom_attributes']);
ksort($expected);
ksort($result);
$this->assertEquals($expected, $result);
}
public function testInfoNoSuchEntityException()
{
try {
$this->getInfoCategory(-1);
} catch (\Exception $e) {
$this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage());
}
}
/**
* Load category data.
*
* @param int $id
* @return array
*/
protected function getInfoCategory($id)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $id,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Get',
],
];
return $this->_webApiCall($serviceInfo, ['categoryId' => $id]);
}
/**
* Test for create category process
*
* @magentoApiDataFixture Magento/Catalog/Model/Category/_files/service_category_create.php
*/
public function testCreate()
{
$categoryData = $this->getSimpleCategoryData(['name' => 'Test Category Name']);
$result = $this->createCategory($categoryData);
$this->assertGreaterThan(0, $result['id']);
foreach (['name', 'parent_id', 'available_sort_by'] as $fieldName) {
$this->assertEquals(
$categoryData[$fieldName],
$result[$fieldName],
sprintf('"%s" field value is invalid', $fieldName)
);
}
$this->createdCategories = [$result['id']];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category.php
*/
public function testDelete()
{
/** @var DbStorage $storage */
$storage = Bootstrap::getObjectManager()->get(DbStorage::class);
$categoryId = $this->modelId;
$data = [
UrlRewrite::ENTITY_ID => $categoryId,
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE
];
/** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite $urlRewrite */
$urlRewrite = $storage->findOneByData($data);
// Assert that a url rewrite is auto-generated for the category created from the data fixture
$this->assertEquals(1, $urlRewrite->getIsAutogenerated());
$this->assertEquals($categoryId, $urlRewrite->getEntityId());
$this->assertEquals(CategoryUrlRewriteGenerator::ENTITY_TYPE, $urlRewrite->getEntityType());
$this->assertEquals('category-1.html', $urlRewrite->getRequestPath());
// Assert deleting category is successful
$this->assertTrue($this->deleteCategory($this->modelId));
// After the category is deleted, assert that the associated url rewrite is also auto-deleted
$this->assertNull($storage->findOneByData($data));
}
public function testDeleteNoSuchEntityException()
{
try {
$this->deleteCategory(-1);
} catch (\Exception $e) {
$this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage());
}
}
/**
* @dataProvider deleteSystemOrRootDataProvider
*
* @param int $categoryId
* @param string $exceptionMsg
* @return void
*/
public function testDeleteSystemOrRoot(int $categoryId, string $exceptionMsg): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage($exceptionMsg);
$this->deleteCategory($categoryId);
}
/**
* @return array
*/
public function deleteSystemOrRootDataProvider(): array
{
return [
'system_category' => [
'category_id' => Category::TREE_ROOT_ID,
'exception_message' => $this->buildExceptionMessage(Category::TREE_ROOT_ID),
],
'root_category' => [
'category_id' => 2,
'exception_message' => $this->buildExceptionMessage(2),
],
];
}
/**
* Build response error message
*
* @param int $categoryId
* @return string
*/
private function buildExceptionMessage(int $categoryId): string
{
$translatedMsg = (string)__('Cannot delete category with id %1');
return TESTS_WEB_API_ADAPTER === self::ADAPTER_REST
? sprintf('{"message":"%s","parameters":["%u"]}', $translatedMsg, $categoryId)
: $translatedMsg;
}
#[
DataFixture(CategoryFixture::class, as: 'category'),
]
public function testUpdate()
{
$categoryId = $this->fixtures->get('category')->getId();
$categoryData = [
'name' => 'Update Category Test',
'is_active' => false,
'custom_attributes' => [
[
'attribute_code' => 'description',
'value' => "Update Category Description Test",
],
],
];
$result = $this->updateCategory($categoryId, $categoryData);
$this->assertEquals($categoryId, $result['id']);
/** @var Category $model */
$model = Bootstrap::getObjectManager()->get(Category::class);
$category = $model->load($categoryId);
$this->assertFalse((bool)$category->getIsActive(), 'Category "is_active" must equal to false');
$this->assertEquals("Update Category Test", $category->getName());
$this->assertEquals("Update Category Description Test", $category->getDescription());
$this->createdCategories = [$categoryId];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category.php
*/
public function testUpdateWithDefaultSortByAttribute()
{
$categoryId = 333;
$categoryData = [
'name' => 'Update Category Test With default_sort_by Attribute',
'is_active' => true,
"available_sort_by" => [],
'custom_attributes' => [
[
'attribute_code' => 'default_sort_by',
'value' => ["name"],
],
],
];
$result = $this->updateCategory($categoryId, $categoryData);
$this->assertEquals($categoryId, $result['id']);
/** @var Category $model */
$model = Bootstrap::getObjectManager()->get(Category::class);
$category = $model->load($categoryId);
$this->assertTrue((bool)$category->getIsActive(), 'Category "is_active" must equal to true');
$this->assertEquals("Update Category Test With default_sort_by Attribute", $category->getName());
$this->assertEquals("name", $category->getDefaultSortBy());
$this->createdCategories = [$categoryId];
}
#[
DataFixture(CategoryFixture::class, as: 'category'),
]
public function testUpdateUrlKey()
{
$this->_markTestAsRestOnly('Functionality available in REST mode only.');
$categoryId = $this->fixtures->get('category')->getId();
$categoryData = [
'name' => 'Update Category Test Old Name',
'custom_attributes' => [
[
'attribute_code' => 'url_key',
'value' => "Update Category Test Old Name",
],
],
];
$result = $this->updateCategory($categoryId, $categoryData);
$this->assertEquals($categoryId, $result['id']);
$categoryData = [
'name' => 'Update Category Test New Name',
'custom_attributes' => [
[
'attribute_code' => 'url_key',
'value' => "Update Category Test New Name",
],
[
'attribute_code' => 'save_rewrites_history',
'value' => 1,
],
],
];
$result = $this->updateCategory($categoryId, $categoryData);
$this->assertEquals($categoryId, $result['id']);
/** @var Category $model */
$model = Bootstrap::getObjectManager()->get(Category::class);
$category = $model->load($categoryId);
$this->assertEquals("Update Category Test New Name", $category->getName());
// check for the url rewrite for the new name
$storage = Bootstrap::getObjectManager()->get(DbStorage::class);
$data = [
UrlRewrite::ENTITY_ID => $categoryId,
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::REDIRECT_TYPE => 0,
];
$urlRewrite = $storage->findOneByData($data);
// Assert that a url rewrite is auto-generated for the category created from the data fixture
$this->assertNotNull($urlRewrite);
$this->assertEquals(1, $urlRewrite->getIsAutogenerated());
$this->assertEquals($categoryId, $urlRewrite->getEntityId());
$this->assertEquals(CategoryUrlRewriteGenerator::ENTITY_TYPE, $urlRewrite->getEntityType());
$this->assertEquals('update-category-test-new-name.html', $urlRewrite->getRequestPath());
// check for the forward from the old name to the new name
$storage = Bootstrap::getObjectManager()->get(DbStorage::class);
$data = [
UrlRewrite::ENTITY_ID => $categoryId,
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::REDIRECT_TYPE => 301,
];
$urlRewrite = $storage->findOneByData($data);
$this->assertNotNull($urlRewrite);
$this->assertEquals(0, $urlRewrite->getIsAutogenerated());
$this->assertEquals($categoryId, $urlRewrite->getEntityId());
$this->assertEquals(CategoryUrlRewriteGenerator::ENTITY_TYPE, $urlRewrite->getEntityType());
$this->assertEquals('update-category-test-old-name.html', $urlRewrite->getRequestPath());
$this->deleteCategory($categoryId);
}
protected function getSimpleCategoryData($categoryData = [])
{
return [
'parent_id' => '2',
'name' => isset($categoryData['name'])
? $categoryData['name'] : uniqid('Category-', true),
'is_active' => '1',
'include_in_menu' => '1',
'available_sort_by' => ['position', 'name'],
'custom_attributes' => [
['attribute_code' => 'url_key', 'value' => ''],
['attribute_code' => 'description', 'value' => 'Custom description'],
['attribute_code' => 'meta_title', 'value' => ''],
['attribute_code' => 'meta_keywords', 'value' => ''],
['attribute_code' => 'meta_description', 'value' => ''],
['attribute_code' => 'display_mode', 'value' => 'PRODUCTS'],
['attribute_code' => 'landing_page', 'value' => '0'],
['attribute_code' => 'is_anchor', 'value' => '0'],
['attribute_code' => 'custom_use_parent_settings', 'value' => '0'],
['attribute_code' => 'custom_apply_to_products', 'value' => '0'],
['attribute_code' => 'custom_design', 'value' => ''],
['attribute_code' => 'custom_design_from', 'value' => ''],
['attribute_code' => 'custom_design_to', 'value' => ''],
['attribute_code' => 'page_layout', 'value' => ''],
]
];
}
/**
* Create category process
*
* @param array $category
* @param string|null $token
* @return array
*/
protected function createCategory(array $category, ?string $token = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if ($token) {
$serviceInfo['rest']['token'] = $serviceInfo['soap']['token'] = $token;
}
$requestData = ['category' => $category];
return $this->_webApiCall($serviceInfo, $requestData);
}
/**
* @param int $id
* @return bool
* @throws \Exception
*/
protected function deleteCategory($id)
{
$serviceInfo =
[
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $id,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'DeleteByIdentifier',
],
];
return $this->_webApiCall($serviceInfo, ['categoryId' => $id]);
}
/**
* Update given category via web API.
*
* @param int $id
* @param array $data
* @param string|null $token
* @return array
*/
protected function updateCategory($id, $data, ?string $token = null)
{
$serviceInfo =
[
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $id,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if ($token) {
$serviceInfo['rest']['token'] = $serviceInfo['soap']['token'] = $token;
}
$data['id'] = $id;
return $this->_webApiCall($serviceInfo, ['id' => $id, 'category' => $data]);
}
/**
* Update admin role resources list.
*
* @param string $roleName
* @param string[] $resources
* @return void
*/
private function updateRoleResources(string $roleName, array $resources): void
{
/** @var Role $role */
$role = $this->roleFactory->create();
$role->load($roleName, 'role_name');
/** @var Rules $rules */
$rules = $this->rulesFactory->create();
$rules->setRoleId($role->getId());
$rules->setResources($resources);
$rules->saveRel();
}
/**
* Extract error returned by the server.
*
* @param \Throwable $exception
* @return string
*/
private function extractCallExceptionMessage(\Throwable $exception): string
{
if ($restResponse = json_decode($exception->getMessage(), true)) {
//REST
return $restResponse['message'];
} else {
//SOAP
return $exception->getMessage();
}
}
/**
* Test design settings authorization
*
* @magentoApiDataFixture Magento/User/_files/user_with_custom_role.php
* @throws \Throwable
* @return void
*/
public function testSaveDesign(): void
{
//Updating our admin user's role to allow saving categories but not their design settings.
$roleName = 'test_custom_role';
$this->updateRoleResources($roleName, ['Magento_Catalog::categories']);
//Using the admin user with custom role.
$token = $this->adminTokens->createAdminAccessToken(
'customRoleUser',
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$categoryData = $this->getSimpleCategoryData();
$categoryData['custom_attributes'][] = ['attribute_code' => 'custom_layout_update_file', 'value' => 'test'];
//Creating new category with design settings.
$exceptionMessage = null;
try {
$this->createCategory($categoryData, $token);
} catch (\Throwable $exception) {
$exceptionMessage = $this->extractCallExceptionMessage($exception);
}
//We don't have the permissions.
$this->assertEquals('Not allowed to edit the category\'s design attributes', $exceptionMessage);
//Updating the user role to allow access to design properties.
$this->updateRoleResources($roleName, ['Magento_Catalog::categories', 'Magento_Catalog::edit_category_design']);
//Making the same request with design settings.
$categoryData = $this->getSimpleCategoryData();
foreach ($categoryData['custom_attributes'] as &$attribute) {
if ($attribute['attribute_code'] === 'custom_design') {
$attribute['value'] = 'test';
break;
}
}
$result = $this->createCategory($categoryData, $token);
$this->assertArrayHasKey('id', $result);
//Category must be saved.
$categorySaved = $this->getInfoCategory($result['id']);
$savedCustomDesign = null;
foreach ($categorySaved['custom_attributes'] as $customAttribute) {
if ($customAttribute['attribute_code'] === 'custom_design') {
$savedCustomDesign = $customAttribute['value'];
break;
}
}
$this->assertEquals('test', $savedCustomDesign);
$categoryData = $categorySaved;
//Updating our role to remove design properties access.
$this->updateRoleResources($roleName, ['Magento_Catalog::categories']);
//Updating the category but with the same design properties values.
//Omitting existing design attribute and keeping it's existing value
$attributes = $categoryData['custom_attributes'];
foreach ($attributes as $index => $attrData) {
if ($attrData['attribute_code'] === 'custom_design') {
unset($categoryData['custom_attributes'][$index]);
break;
}
}
unset($attributes, $index, $attrData);
$result = $this->updateCategory($categoryData['id'], $categoryData, $token);
//We haven't changed the design so operation is successful.
$this->assertArrayHasKey('id', $result);
//Changing a design property.
$categoryData['custom_attributes'][] = ['attribute_code' => 'custom_design', 'value' => 'test2'];
$exceptionMessage = null;
try {
$this->updateCategory($categoryData['id'], $categoryData, $token);
} catch (\Throwable $exception) {
$exceptionMessage = $this->extractCallExceptionMessage($exception);
}
//We don't have permissions to do that.
$this->assertEquals('Not allowed to edit the category\'s design attributes', $exceptionMessage);
$this->createdCategories = [$result['id']];
}
/**
* Check if repository does not override default values for attributes out of request
*/
#[
DataFixture(CategoryFixture::class, as: 'category'),
]
public function testUpdateScopeAttribute()
{
$categoryId = $this->fixtures->get('category')->getId();
$categoryData = [
'name' => 'Scope Specific Value',
];
$result = $this->updateCategoryForSpecificStore($categoryId, $categoryData);
$this->assertEquals($categoryId, $result['id']);
/** @var Category $model */
$model = Bootstrap::getObjectManager()->get(Category::class);
$category = $model->load($categoryId);
/** @var ScopeOverriddenValue $scopeOverriddenValue */
$scopeOverriddenValue = Bootstrap::getObjectManager()->get(ScopeOverriddenValue::class);
self::assertTrue($scopeOverriddenValue->containsValue(
CategoryInterface::class,
$category,
'name',
Store::DISTRO_STORE_ID
), 'Name is not saved for specific store');
self::assertFalse($scopeOverriddenValue->containsValue(
CategoryInterface::class,
$category,
'is_active',
Store::DISTRO_STORE_ID
), 'is_active is overridden for default store');
self::assertFalse($scopeOverriddenValue->containsValue(
CategoryInterface::class,
$category,
'url_key',
Store::DISTRO_STORE_ID
), 'url_key is overridden for default store');
$this->deleteCategory($categoryId);
}
/**
* Update given category via web API for specific store code.
*
* @param int $id
* @param array $data
* @param string|null $token
* @param string $storeCode
* @return array
*/
protected function updateCategoryForSpecificStore(
int $id,
array $data,
?string $token = null,
string $storeCode = 'default'
) {
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $id,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if ($token) {
$serviceInfo['rest']['token'] = $serviceInfo['soap']['token'] = $token;
}
$data['id'] = $id;
return $this->_webApiCall($serviceInfo, ['id' => $id, 'category' => $data], null, $storeCode);
}
/**
* @inheritDoc
*
* @return void
*/
protected function tearDown(): void
{
if (!empty($this->createdCategories)) {
// delete category to clean up auto-generated url rewrites
foreach ($this->createdCategories as $categoryId) {
$this->deleteCategory($categoryId);
}
}
parent::tearDown();
}
}
@@ -0,0 +1,189 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;
/**
* Catalog Cost Storage API test.
*/
class CostStorageTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogCostStorageV1';
const SERVICE_VERSION = 'V1';
const SIMPLE_PRODUCT_SKU = 'simple';
/**
* @var \Magento\TestFramework\ObjectManager
*/
private $objectManager;
/**
* Set up.
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* Test get method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGet()
{
$cost = 3057;
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productRepository->save($productRepository->get(self::SIMPLE_PRODUCT_SKU)->setData('cost', $cost));
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/cost-information',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertNotEmpty($response);
$this->assertEquals($cost, (int)$product->getCost());
}
/**
* Test update method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testUpdate()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/cost',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$storeId = 0;
$newCost = 31337;
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
[
'cost' => $newCost,
'store_id' => $storeId,
'sku' => self::SIMPLE_PRODUCT_SKU,
]
]
]
);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertEmpty($response);
$this->assertEquals($newCost, (int)$product->getCost());
}
/**
* Test update method call without SKU.
*/
public function testUpdateWithInvalidParameters()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/cost',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$newCost = -9999;
$storeId = 9999;
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
[
'sku' => 'not_existing_sku',
'cost' => $newCost,
'store_id' => $storeId
]
]
]
);
$expectedResponse = [
0 => [
'message' => 'Invalid attribute %fieldName = %fieldValue.',
'parameters' => [
'SKU',
'not_existing_sku',
]
],
1 => [
'message' => 'Invalid attribute Cost = -9999. Row ID: SKU = not_existing_sku, Store ID: 9999.',
'parameters' => [
'-9999',
'not_existing_sku',
'9999'
]
],
2 => [
'message' => 'Requested store is not found. Row ID: SKU = not_existing_sku, Store ID: 9999.',
'parameters' => [
'not_existing_sku',
'9999'
]
]
];
$this->assertEquals($expectedResponse, $response);
}
/**
* Test delete method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testDelete()
{
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productRepository->save($productRepository->get(self::SIMPLE_PRODUCT_SKU)->setData('cost', 777));
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/cost-delete',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Delete',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertTrue($response);
$this->assertNull($product->getCost());
}
}
@@ -0,0 +1,129 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class OrderItemRepositoryTest extends WebapiAbstract
{
const RESOURCE_PATH = '/V1/orders/items';
const SERVICE_VERSION = 'V1';
const SERVICE_NAME = 'salesOrderItemRepositoryV1';
const ORDER_INCREMENT_ID = '100000001';
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/order_item_with_product_and_custom_options.php
*/
public function testGet()
{
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(\Magento\Sales\Model\Order::class);
$order->loadByIncrementId(self::ORDER_INCREMENT_ID);
$orderItem = current($order->getItems());
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $orderItem->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'get',
],
];
$response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]);
$this->assertIsArray($response);
$this->assertOrderItem($orderItem, $response);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/order_item_with_product_and_custom_options.php
*/
public function testGetList()
{
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(\Magento\Sales\Model\Order::class);
$order->loadByIncrementId(self::ORDER_INCREMENT_ID);
/** @var $searchCriteriaBuilder \Magento\Framework\Api\SearchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->create(\Magento\Framework\Api\SearchCriteriaBuilder::class);
/** @var $filterBuilder \Magento\Framework\Api\FilterBuilder */
$filterBuilder = $this->objectManager->create(\Magento\Framework\Api\FilterBuilder::class);
$searchCriteriaBuilder->addFilters(
[
$filterBuilder->setField('order_id')
->setValue($order->getId())
->create(),
]
);
$requestData = ['searchCriteria' => $searchCriteriaBuilder->create()->__toArray()];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($requestData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'getList',
],
];
$response = $this->_webApiCall($serviceInfo, $requestData);
$this->assertIsArray($response);
$this->assertArrayHasKey('items', $response);
$this->assertCount(1, $response['items']);
$this->assertIsArray($response['items'][0]);
$this->assertOrderItem(current($order->getItems()), $response['items'][0]);
}
/**
* @param \Magento\Sales\Model\Order\Item $orderItem
* @param array $response
* @return void
*/
protected function assertOrderItem(\Magento\Sales\Model\Order\Item $orderItem, array $response)
{
$expected = $orderItem->getBuyRequest()->getOptions();
$this->assertArrayHasKey('product_option', $response);
$this->assertArrayHasKey('extension_attributes', $response['product_option']);
$this->assertArrayHasKey('custom_options', $response['product_option']['extension_attributes']);
$actualOptions = $response['product_option']['extension_attributes']['custom_options'];
$expectedOptions = [];
foreach ($expected as $optionId => $optionValue) {
if (is_array($optionValue)) {
$optionValue = implode(',', $optionValue);
}
$expectedOptions[] = [
'option_id' => $optionId,
'option_value' => $optionValue,
];
}
$this->assertEquals($expectedOptions, $actualOptions);
}
}
@@ -0,0 +1,191 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
class ProductAttributeGroupRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeGroupRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attribute-sets';
/**
* @magentoApiDataFixture Magento/Catalog/_files/empty_attribute_group.php
*/
public function testCreateGroup()
{
$attributeSetId = 1;
$groupData = $this->createGroupData($attributeSetId);
$groupData['attribute_group_name'] = 'empty_attribute_group_updated';
$result = $this->createGroup($attributeSetId, $groupData);
$this->assertArrayHasKey('attribute_group_id', $result);
$this->assertNotNull($result['attribute_group_id']);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/empty_attribute_group.php
*/
public function testDeleteGroup()
{
$group = $this->getGroupByName('empty_attribute_group');
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "/groups/" . $group->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'DeleteById',
],
];
$this->assertTrue($this->_webApiCall($serviceInfo, ['groupId' => $group->getId()]));
}
/**
*/
public function testCreateGroupWithAttributeSetThatDoesNotExist()
{
$this->expectException(\Exception::class);
$attributeSetId = -1;
$this->createGroup($attributeSetId);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/empty_attribute_group.php
*/
public function testUpdateGroup()
{
$attributeSetId = 1;
$group = $this->getGroupByName('empty_attribute_group');
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeSetId . '/groups',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$newGroupData = $this->createGroupData($attributeSetId);
$newGroupData['attribute_group_name'] = 'empty_attribute_group_updated';
$newGroupData['attribute_group_id'] = $group->getId();
$result = $this->_webApiCall($serviceInfo, ['group' => $newGroupData]);
$this->assertArrayHasKey('attribute_group_id', $result);
$this->assertEquals($group->getId(), $result['attribute_group_id']);
$this->assertArrayHasKey('attribute_group_name', $result);
$this->assertEquals($newGroupData['attribute_group_name'], $result['attribute_group_name']);
}
public function testGetList()
{
$searchCriteria = [
'searchCriteria' => [
'filter_groups' => [
[
'filters' => [
[
'field' => 'attribute_set_id',
'value' => 1,
'condition_type' => 'eq',
],
],
],
],
'current_page' => 1,
'page_size' => 2,
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/groups/list' . '?' . http_build_query($searchCriteria),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$response = $this->_webApiCall($serviceInfo, $searchCriteria);
$this->assertArrayHasKey('search_criteria', $response);
$this->assertArrayHasKey('total_count', $response);
$this->assertArrayHasKey('items', $response);
$this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
$this->assertTrue($response['total_count'] > 0);
$this->assertTrue(count($response['items']) > 0);
$this->assertNotNull($response['items'][0]['attribute_group_name']);
$this->assertNotNull($response['items'][0]['attribute_group_id']);
}
/**
* @param $attributeSetId
* @return array|bool|float|int|string
*/
protected function createGroup($attributeSetId, $groupData = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/groups',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
return $this->_webApiCall(
$serviceInfo,
['group' => $groupData ? $groupData : $this->createGroupData($attributeSetId)]
);
}
/**
* @param $attributeSetId
* @return array
*/
protected function createGroupData($attributeSetId)
{
return [
'attribute_group_name' => 'empty_attribute_group',
'attribute_set_id' => $attributeSetId
];
}
/**
* Retrieve attribute group based on given name.
* This utility methods assumes that there is only one attribute group with given name,
*
* @param string $groupName
* @return \Magento\Eav\Model\Entity\Attribute\Group|null
*/
protected function getGroupByName($groupName)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Eav\Model\Entity\Attribute\Group */
$attributeGroup = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Group::class)
->load($groupName, 'attribute_group_name');
if ($attributeGroup->getId() === null) {
return null;
}
return $attributeGroup;
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright 2023 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Catalog\Test\Fixture\Attribute;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\TestCase\WebapiAbstract;
#[
DataFixture(
Attribute::class,
[
'entity_type_id' => CategorySetup::CATALOG_PRODUCT_ENTITY_TYPE_ID,
'attribute_code' => 'product_custom_attribute',
'is_filterable' => false,
'frontend_input' => 'select',
'backend_type' => 'int',
]
),
]
class ProductAttributeIsFilterableManagementTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogProductAttributeIsFilterableManagementV1';
private const SERVICE_VERSION = 'V1';
private const RESOURCE_PATH = '/V1/products/attributes/%s/is-filterable';
/**
* @return void
*/
public function testGet(): void
{
$isFilterable = $this->getAttributeIsFilterable('product_custom_attribute');
$this->assertEquals(0, $isFilterable);
}
/**
* @return void
*/
public function testSet(): void
{
$attributeCode = 'product_custom_attribute';
$isFilterableIntValue = 2;
$serviceInfo = [
'rest' => [
'resourcePath' => sprintf(self::RESOURCE_PATH, $attributeCode) . '/' . $isFilterableIntValue,
'httpMethod' => Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Set',
],
];
$response = $this->_webApiCall(
$serviceInfo,
[
'attributeCode' => $attributeCode,
'isFilterable' => $isFilterableIntValue,
]
);
$this->assertTrue($response);
$this->assertEquals(
$isFilterableIntValue,
$this->getAttributeIsFilterable($attributeCode)
);
}
/**
* @param string $attributeCode
* @return int
*/
private function getAttributeIsFilterable(string $attributeCode): int
{
$serviceInfo = [
'rest' => [
'resourcePath' => sprintf(self::RESOURCE_PATH, $attributeCode),
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
}
}
@@ -0,0 +1,190 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;
class ProductAttributeManagementTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attribute-sets';
public function testGetAttributes()
{
$attributeSetId = 4;
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeSetId . '/attributes',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetAttributes',
],
];
$attributes = $this->_webApiCall($serviceInfo, ['attributeSetId' => $attributeSetId]);
$this->assertTrue(count($attributes) > 0);
$this->assertArrayHasKey('attribute_code', $attributes[0]);
$this->assertArrayHasKey('attribute_id', $attributes[0]);
$this->assertArrayHasKey('default_frontend_label', $attributes[0]);
$this->assertNotNull($attributes[0]['attribute_code']);
$this->assertNotNull($attributes[0]['attribute_id']);
$this->assertNotNull($attributes[0]['default_frontend_label']);
}
public function testAssignAttribute()
{
$this->assertNotNull(
$this->_webApiCall(
$this->getAssignServiceInfo(),
$this->getAttributeData()
)
);
}
public function testAssignAttributeWrongAttributeSet()
{
$payload = $this->getAttributeData();
$payload['attributeSetId'] = -1;
$expectedMessage = 'The AttributeSet with a "%1" ID doesn\'t exist. Verify the attributeSet and try again.';
try {
$this->_webApiCall($this->getAssignServiceInfo(), $payload);
$this->fail("Expected exception");
} catch (\SoapFault $e) {
$this->assertStringContainsString(
$expectedMessage,
$e->getMessage(),
"SoapFault does not contain expected message."
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals($expectedMessage, $errorObj['message']);
$this->assertEquals([$payload['attributeSetId']], $errorObj['parameters']);
$this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode());
}
}
public function testAssignAttributeWrongAttributeGroup()
{
$payload = $this->getAttributeData();
$payload['attributeGroupId'] = -1;
$expectedMessage = 'The group with the "%1" ID doesn\'t exist. Verify the ID and try again.';
try {
$this->_webApiCall($this->getAssignServiceInfo(), $payload);
$this->fail("Expected exception");
} catch (\SoapFault $e) {
$this->assertStringContainsString(
$expectedMessage,
$e->getMessage(),
"SoapFault does not contain expected message."
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals($expectedMessage, $errorObj['message']);
$this->assertEquals([$payload['attributeGroupId']], $errorObj['parameters']);
$this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode());
}
}
public function testAssignAttributeWrongAttribute()
{
$payload = $this->getAttributeData();
$payload['attributeCode'] = 'badCode';
$expectedMessage =
'The attribute with a "%1" attributeCode doesn\'t exist. Verify the attribute and try again.';
try {
$this->_webApiCall($this->getAssignServiceInfo(), $payload);
$this->fail("Expected exception");
} catch (\SoapFault $e) {
$this->assertStringContainsString(
$expectedMessage,
$e->getMessage(),
"SoapFault does not contain expected message."
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals($expectedMessage, $errorObj['message']);
$this->assertEquals([$payload['attributeCode']], $errorObj['parameters']);
$this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode());
}
}
public function testUnassignAttribute()
{
$payload = $this->getAttributeData();
//Assign attribute to attribute set
/** @var \Magento\Eav\Model\AttributeManagement $attributeManagement */
$attributeManagement = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\AttributeManagement::class);
$attributeManagement->assign(
\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE,
$payload['attributeSetId'],
$payload['attributeGroupId'],
$payload['attributeCode'],
$payload['sortOrder']
);
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH .
'/' . $payload['attributeSetId'] .
'/attributes/' .
$payload['attributeCode'],
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Unassign',
],
];
$this->assertTrue(
$this->_webApiCall(
$serviceInfo,
[
'attributeSetId' => $payload['attributeSetId'],
'attributeCode' => $payload['attributeCode'],
]
)
);
}
protected function getAttributeData()
{
return [
'attributeSetId' => 4,
'attributeGroupId' => 8,
'attributeCode' => 'cost',
'sortOrder' => 3,
];
}
protected function getAssignServiceInfo()
{
return [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/attributes',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Assign',
],
];
}
}
@@ -0,0 +1,898 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Framework\Api\Data\ImageContentInterface;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Framework\ObjectManagerInterface;
/**
* Class ProductAttributeMediaGalleryManagementInterfaceTest
*/
class ProductAttributeMediaGalleryManagementInterfaceTest extends WebapiAbstract
{
public const RESOURCE_PATH = '/V1/products/';
public const SERVICE_NAME = 'catalogProductAttributeMediaGalleryManagementV1';
public const SERVICE_VERSION = 'V1';
/**
* Default create service request information (product with SKU 'simple' is used)
*
* @var array
*/
protected $createServiceInfo;
/**
* Default update service request information (product with SKU 'simple' is used)
*
* @var array
*/
protected $updateServiceInfo;
/**
* Default delete service request information (product with SKU 'simple' is used)
*
* @var array
*/
protected $deleteServiceInfo;
/**
* @var string
*/
protected $testImagePath;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->createServiceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH.'simple/media',
'httpMethod' => Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME ,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'Create',
],
];
$this->updateServiceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH.'simple/media',
'httpMethod' => Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => 'catalogProductAttributeMediaGalleryManagementV1',
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'Update',
],
];
$this->deleteServiceInfo = [
'rest' => [
'httpMethod' => Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'Remove',
],
];
$this->testImagePath = __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test_image.jpg';
$this->fixtures = $this->objectManager->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* Retrieve product that was updated by test
*
* @return \Magento\Catalog\Model\Product
*/
protected function getTargetSimpleProduct()
{
return $this->objectManager->get(ProductFactory::class)->create()->load(1);
}
/**
* Retrieve target product image ID
*
* Target product must have single image if this function is used
*
* @return int
*/
protected function getTargetGalleryEntryId()
{
$mediaGallery = $this->getTargetSimpleProduct()->getData('media_gallery');
$image = array_shift($mediaGallery['images']);
return (int)$image['value_id'];
}
/**
* Test create() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreate()
{
$requestData = [
'id' => null,
'media_type' => ImageEntryConverter::MEDIA_TYPE_CODE,
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
ImageContentInterface::BASE64_ENCODED_DATA => base64_encode(file_get_contents($this->testImagePath)),
ImageContentInterface::TYPE => 'image/jpeg',
ImageContentInterface::NAME => 'test_image.jpg'
]
];
$actualResult = $this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
$targetProduct = $this->getTargetSimpleProduct();
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(1, $mediaGallery['images']);
$updatedImage = array_shift($mediaGallery['images']);
$this->assertEquals($actualResult, $updatedImage['value_id']);
$this->assertEquals('Image Text', $updatedImage['label']);
$this->assertEquals(1, $updatedImage['position']);
$this->assertEquals(0, $updatedImage['disabled']);
$this->assertStringStartsWith('/t/e/test_image', $updatedImage['file']);
$this->assertEquals($updatedImage['file'], $targetProduct->getData('image'));
}
/**
* Test create() method without file
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateWithoutFileExtension()
{
$requestData = [
'id' => null,
'media_type' => ImageEntryConverter::MEDIA_TYPE_CODE,
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
ImageContentInterface::BASE64_ENCODED_DATA => base64_encode(file_get_contents($this->testImagePath)),
ImageContentInterface::TYPE => 'image/jpeg',
ImageContentInterface::NAME => 'test_image'
]
];
$actualResult = $this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
$targetProduct = $this->getTargetSimpleProduct();
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(1, $mediaGallery['images']);
$updatedImage = array_shift($mediaGallery['images']);
$this->assertEquals($actualResult, $updatedImage['value_id']);
$this->assertEquals('Image Text', $updatedImage['label']);
$this->assertEquals(1, $updatedImage['position']);
$this->assertEquals(0, $updatedImage['disabled']);
$this->assertStringStartsWith('/t/e/test_image', $updatedImage['file']);
$this->assertEquals($updatedImage['file'], $targetProduct->getData('image'));
}
/**
* Test create() method with not default store id
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateWithNotDefaultStoreId()
{
$requestData = [
'id' => null,
'media_type' => ImageEntryConverter::MEDIA_TYPE_CODE,
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => base64_encode(file_get_contents($this->testImagePath)),
'type' => 'image/jpeg',
'name' => 'test_image.jpg',
]
];
$actualResult = $this->_webApiCall(
$this->createServiceInfo,
[
'sku' => 'simple',
'entry' => $requestData,
'storeId' => 1,
]
);
$targetProduct = $this->getTargetSimpleProduct();
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(1, $mediaGallery['images']);
$updatedImage = array_shift($mediaGallery['images']);
// Values for not default store view were provided
$this->assertEquals('Image Text', $updatedImage['label']);
$this->assertEquals($actualResult, $updatedImage['value_id']);
$this->assertEquals(1, $updatedImage['position']);
$this->assertEquals(0, $updatedImage['disabled']);
$this->assertStringStartsWith('/t/e/test_image', $updatedImage['file']);
$this->assertEquals($updatedImage['file'], $targetProduct->getData('image'));
// No values for default store view were provided
$this->assertNull($updatedImage['label_default']);
$this->assertEquals(1, $updatedImage['position_default']);
$this->assertEquals(0, $updatedImage['disabled_default']);
}
/**
* Test update() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testUpdate()
{
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get('simple');
$imageId = (int)$product->getMediaGalleryImages()->getFirstItem()->getValueId();
$requestData = [
'sku' => 'simple',
'entry' => [
'id' => $this->getTargetGalleryEntryId(),
'label' => 'Updated Image Text',
'position' => 10,
'types' => ['thumbnail'],
'disabled' => true,
'media_type' => 'image',
],
];
$this->updateServiceInfo['rest']['resourcePath'] = $this->updateServiceInfo['rest']['resourcePath']
. '/' . $this->getTargetGalleryEntryId();
$this->assertTrue($this->_webApiCall($this->updateServiceInfo, $requestData, null, 'all'));
$updatedImage = $this->assertMediaGalleryData($imageId, '/m/a/magento_image.jpg', 'Updated Image Text');
$this->assertEquals(10, $updatedImage['position_default']);
$this->assertEquals(1, $updatedImage['disabled_default']);
}
/**
* Update media gallery entity with new image.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
* @return void
*/
public function testUpdateWithNewImage(): void
{
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get('simple');
$imageId = (int)$product->getMediaGalleryImages()->getFirstItem()->getValueId();
$requestData = [
'sku' => 'simple',
'entry' => [
'id' => $this->getTargetGalleryEntryId(),
'label' => 'Updated Image Text',
'position' => 10,
'types' => ['thumbnail'],
'disabled' => true,
'media_type' => 'image',
'content' => [
'base64_encoded_data' => 'iVBORw0KGgoAAAANSUhEUgAAAP8AAADGCAMAAAAqo6adAAAAA1BMVEUAAP79f'
. '+LBAAAASElEQVR4nO3BMQEAAADCoPVPbQwfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA+BsYAAAF7hZJ0AAAAAElFTkSuQmCC',
'type' => 'image/png',
'name' => 'testname_updated.png',
],
],
];
$this->updateServiceInfo['rest']['resourcePath'] = $this->updateServiceInfo['rest']['resourcePath']
. '/' . $this->getTargetGalleryEntryId();
$this->assertTrue($this->_webApiCall($this->updateServiceInfo, $requestData, null, 'all'));
$updatedImage = $this->assertMediaGalleryData($imageId, '/t/e/testname_updated.png', 'Updated Image Text');
$this->assertEquals(10, $updatedImage['position_default']);
$this->assertEquals(1, $updatedImage['disabled_default']);
}
/**
* Test update() method with not default store id
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testUpdateWithNotDefaultStoreId()
{
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get('simple');
$imageId = (int)$product->getMediaGalleryImages()->getFirstItem()->getValueId();
$requestData = [
'sku' => 'simple',
'entry' => [
'id' => $this->getTargetGalleryEntryId(),
'label' => 'Updated Image Text',
'position' => 10,
'types' => ['thumbnail'],
'disabled' => true,
'media_type' => 'image',
]
];
$this->updateServiceInfo['rest']['resourcePath'] = $this->updateServiceInfo['rest']['resourcePath']
. '/' . $this->getTargetGalleryEntryId();
$this->assertTrue($this->_webApiCall($this->updateServiceInfo, $requestData, null, 'default'));
$updatedImage = $this->assertMediaGalleryData($imageId, '/m/a/magento_image.jpg', 'Image Alt Text');
$this->assertEquals(1, $updatedImage['position_default']);
$this->assertEquals(0, $updatedImage['disabled_default']);
}
/**
* Check that Media Gallery data is correct.
*
* @param int $imageId
* @param string $file
* @param string $label
* @return array
*/
private function assertMediaGalleryData(int $imageId, string $file, string $label): array
{
$targetProduct = $this->getTargetSimpleProduct();
$this->assertEquals($file, $targetProduct->getData('thumbnail'));
$this->assertEquals('no_selection', $targetProduct->getData('image'));
$this->assertEquals('no_selection', $targetProduct->getData('small_image'));
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(1, $mediaGallery['images']);
$updatedImage = array_shift($mediaGallery['images']);
$this->assertEquals($imageId, $updatedImage['value_id']);
$this->assertEquals('Updated Image Text', $updatedImage['label']);
$this->assertEquals($file, $updatedImage['file']);
$this->assertEquals(10, $updatedImage['position']);
$this->assertEquals(1, $updatedImage['disabled']);
$this->assertEquals($label, $updatedImage['label_default']);
return $updatedImage;
}
/**
* Test delete() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image_without_types.php
*/
public function testDelete()
{
$entryId = $this->getTargetGalleryEntryId();
$this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/simple/media/{$entryId}";
$requestData = [
'sku' => 'simple',
'entryId' => $this->getTargetGalleryEntryId(),
];
$this->assertTrue($this->_webApiCall($this->deleteServiceInfo, $requestData));
$targetProduct = $this->getTargetSimpleProduct();
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(0, $mediaGallery['images']);
}
/**
* Test create() method if provided content is not base64 encoded
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateThrowsExceptionIfProvidedContentIsNotBase64Encoded()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The image content must be valid base64 encoded data.');
$encodedContent = 'not_a_base64_encoded_content';
$requestData = [
'id' => null,
'media_type' => 'image',
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => $encodedContent,
'type' => 'image/jpeg',
'name' => 'test_image.jpg',
]
];
$this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
}
/**
* Test create() method if provided content is not an image
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateThrowsExceptionIfProvidedContentIsNotAnImage()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The image content must be valid base64 encoded data.');
$encodedContent = base64_encode('not_an_image');
$requestData = [
'id' => null,
'media_type' => 'image',
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => $encodedContent,
'type' => 'image/jpeg',
'name' => 'test_image.jpg',
]
];
$this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
}
/**
* Test create() method if provided image has wrong MIME type
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateThrowsExceptionIfProvidedImageHasWrongMimeType()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The image MIME type is not valid or not supported.');
$encodedContent = base64_encode(file_get_contents($this->testImagePath));
$requestData = [
'id' => null,
'media_type' => 'image',
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => $encodedContent,
'type' => 'wrong_mime_type',
'name' => 'test_image.jpg',
]
];
$this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
}
/**
* Test create method if target product does not exist
*
*/
public function testCreateThrowsExceptionIfTargetProductDoesNotExist()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'The product that was requested doesn\'t exist. Verify the product and try again.'
);
$this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media';
$requestData = [
'id' => null,
'media_type' => 'image',
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => base64_encode(file_get_contents($this->testImagePath)),
'type' => 'image/jpeg',
'name' => 'test_image.jpg',
]
];
$this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
}
/**
* Test create() method if provided image name contains forbidden characters
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCreateThrowsExceptionIfProvidedImageNameContainsForbiddenCharacters()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Provided image name contains forbidden characters.');
$requestData = [
'id' => null,
'media_type' => 'image',
'label' => 'Image Text',
'position' => 1,
'types' => ['image'],
'disabled' => false,
'content' => [
'base64_encoded_data' => base64_encode(file_get_contents($this->testImagePath)),
'type' => 'image/jpeg',
'name' => 'test/\\{}|:"<>', // Cannot contain \ / : * ? " < > |
]
];
$this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
}
/**
* Test update() method if target product does not exist
*
*/
public function testUpdateThrowsExceptionIfTargetProductDoesNotExist()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'The product that was requested doesn\'t exist. Verify the product and try again.'
);
$this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media'
. '/' . 'wrong-sku';
$requestData = [
'sku' => 'wrong_product_sku',
'entry' => [
'id' => 9999,
'media_type' => 'image',
'label' => 'Updated Image Text',
'position' => 1,
'types' => ['thumbnail'],
'disabled' => true,
],
];
$this->_webApiCall($this->updateServiceInfo, $requestData, null, 'all');
}
/**
* Test update() method if there is no image with given id
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testUpdateThrowsExceptionIfThereIsNoImageWithGivenId()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.');
$requestData = [
'sku' => 'simple',
'entry' => [
'id' => 9999,
'media_type' => 'image',
'label' => 'Updated Image Text',
'position' => 1,
'types' => ['thumbnail'],
'disabled' => true,
],
];
$this->updateServiceInfo['rest']['resourcePath'] = $this->updateServiceInfo['rest']['resourcePath']
. '/' . $this->getTargetGalleryEntryId();
$this->_webApiCall($this->updateServiceInfo, $requestData, null, 'all');
}
/**
* Test delete() method if target product does not exist
*
*/
public function testDeleteThrowsExceptionIfTargetProductDoesNotExist()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'The product that was requested doesn\'t exist. Verify the product and try again.'
);
$this->deleteServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media/9999';
$requestData = [
'sku' => 'wrong_product_sku',
'entryId' => 9999,
];
$this->_webApiCall($this->deleteServiceInfo, $requestData);
}
/**
* Test delete() method if there is no image with given id
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testDeleteThrowsExceptionIfThereIsNoImageWithGivenId()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.');
$this->deleteServiceInfo['rest']['resourcePath'] = '/V1/products/simple/media/9999';
$requestData = [
'sku' => 'simple',
'entryId' => 9999,
];
$this->_webApiCall($this->deleteServiceInfo, $requestData);
}
#[
DataFixture(StoreFixture::class, as: 'store2'),
DataFixture(ProductFixture::class, ['media_gallery_entries' => [[], []]], as: 'product')
]
public function testDeleteThrowsExceptionIfTheImageCannotBeRemoved(): void
{
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->fixtures->get('product');
$mediaGalleryEntries = $product->getMediaGalleryEntries();
$this->assertCount(2, $mediaGalleryEntries);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The image cannot be removed as it has been assigned to the other image role');
$entry = array_shift($mediaGalleryEntries);
$requestData = [
'sku' => $product->getSku(),
'entryId' => $entry->getId(),
];
$this->deleteServiceInfo['rest']['resourcePath'] = strtr('/V1/products/sku/media/entryId', $requestData);
$this->_webApiCall($this->deleteServiceInfo, $requestData);
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get($product->getSku(), forceReload: true);
$mediaGalleryEntries = $product->getMediaGalleryEntries();
$this->assertCount(2, $mediaGalleryEntries);
}
/**
* Test get() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testGet()
{
$productSku = 'simple';
/** @var ProductRepository $repository */
$repository = $this->objectManager->create(ProductRepository::class);
$product = $repository->get($productSku);
$image = current($product->getMediaGallery('images'));
$imageId = $image['value_id'];
$expected = [
'label' => $image['label'],
'media_type' => $image['media_type'],
'position' => $image['position'],
'disabled' => (bool)$image['disabled'],
'file' => $image['file'],
'types' => ['image', 'small_image', 'thumbnail'],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . $productSku . '/media/' . $imageId,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'Get',
],
];
$requestData = [
'sku' => $productSku,
'entryId' => $imageId,
];
$data = $this->_webApiCall($serviceInfo, $requestData);
$actual = (array)$data;
$this->assertEquals($expected['label'], $actual['label']);
$this->assertEquals($expected['position'], $actual['position']);
$this->assertEquals($expected['file'], $actual['file']);
$this->assertEquals($expected['types'], $actual['types']);
$this->assertEquals($expected['media_type'], $actual['media_type']);
$this->assertEquals($expected['disabled'], (bool)$actual['disabled']);
}
/**
* Test getList() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
*/
public function testGetList()
{
$productSku = 'simple'; //from fixture
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . urlencode($productSku) . '/media',
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'GetList',
],
];
$requestData = [
'sku' => $productSku,
];
$imageList = $this->_webApiCall($serviceInfo, $requestData);
$image = reset($imageList);
$this->assertEquals('/m/a/magento_image.jpg', $image['file']);
$this->assertNotEmpty($image['types']);
$imageTypes = $image['types'];
$this->assertContains('image', $imageTypes);
$this->assertContains('small_image', $imageTypes);
$this->assertContains('thumbnail', $imageTypes);
}
/**
* Test getList() method for absent sku
*/
public function testGetListForAbsentSku()
{
$productSku = 'absent_sku_' . time();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . urlencode($productSku) . '/media',
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME.'GetList',
],
];
$requestData = [
'sku' => $productSku,
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$this->expectException('SoapFault');
$this->expectExceptionMessage(
"The product that was requested doesn't exist. Verify the product and try again."
);
} else {
$this->expectException('Exception');
$this->expectExceptionCode(404);
}
$this->_webApiCall($serviceInfo, $requestData);
}
/**
* Test addProductVideo() method
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testAddProductVideo()
{
$videoContent = [
'media_type' => 'external-video',
'video_provider' => 'vimeo',
'video_url' => 'https://vimeo.com/testUrl',
'video_title' => 'Vimeo Test Title',
'video_description' => 'test description',
'video_metadata' => 'video meta data'
];
$requestData = [
'id' => null,
'media_type' => 'external-video',
'label' => 'Image Text',
'position' => 1,
'types' => null,
'disabled' => false,
'content' => [
ImageContentInterface::BASE64_ENCODED_DATA => base64_encode(file_get_contents($this->testImagePath)),
ImageContentInterface::TYPE => 'image/jpeg',
ImageContentInterface::NAME => 'test_image.jpg'
],
'extension_attributes' => [
'video_content' => $videoContent
]
];
$actualResult = $this->_webApiCall($this->createServiceInfo, ['sku' => 'simple', 'entry' => $requestData]);
$targetProduct = $this->getTargetSimpleProduct();
$mediaGallery = $targetProduct->getData('media_gallery');
$this->assertCount(1, $mediaGallery['images']);
$updatedImage = array_shift($mediaGallery['images']);
$this->assertEquals($actualResult, $updatedImage['value_id']);
$this->assertEquals('Image Text', $updatedImage['label']);
$this->assertEquals(1, $updatedImage['position']);
$this->assertEquals(0, $updatedImage['disabled']);
$this->assertStringStartsWith('/t/e/test_image', $updatedImage['file']);
$this->assertEquals($videoContent, array_intersect_key($updatedImage, $videoContent));
}
/**
* Check content attribute in getList method
*
* @return void
*/
#[
DataFixture(ProductFixture::class, ['media_gallery_entries' => [[]]], as: 'product'),
]
public function testContentAttributeInGetList(): void
{
$productSku = $this->fixtures->get('product')->getSku();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH.$productSku."/media",
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'getList',
],
];
$requestData = [
'sku' => $productSku,
];
$response = $this->_webApiCall($serviceInfo, $requestData);
$this->assertArrayHasKey('content', $response[0]);
}
/**
* Check content attribute in getList method
*
* @return void
*/
#[
DataFixture(ProductFixture::class, ['media_gallery_entries' => [[]]], as: 'product'),
]
public function testContentAttributeInGet(): void
{
$product = $this->fixtures->get('product');
$productSku = $product->getSku();
$entryId = $product->getMediaGalleryEntries()[0]->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH.$productSku."/media/".$entryId,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'get',
],
];
$requestData = [
'sku' => $productSku,
'entryId' => $entryId,
];
$response = $this->_webApiCall($serviceInfo, $requestData);
$this->assertArrayHasKey('content', $response);
}
}
@@ -0,0 +1,223 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Api\Data\AttributeOptionLabelInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Class to test Eav Option Management functionality
*/
class ProductAttributeOptionManagementInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeOptionManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attributes';
/**
* Test to get attribute options
*/
public function testGetItems()
{
$testAttributeCode = 'quantity_and_stock_status';
$expectedOptions = [
[
AttributeOptionInterface::VALUE => '1',
AttributeOptionInterface::LABEL => 'In Stock',
],
[
AttributeOptionInterface::VALUE => '0',
AttributeOptionInterface::LABEL => 'Out of Stock',
],
];
$response = $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_GET,
'getItems',
['attributeCode' => $testAttributeCode]
);
$this->assertIsArray($response);
$this->assertEquals($expectedOptions, $response);
}
/**
* Test to add attribute option
*
* @param array $optionData
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php
* @dataProvider addDataProvider
*/
public function testAdd(array $optionData)
{
$testAttributeCode = 'select_attribute';
$response = $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_POST,
'add',
[
'attributeCode' => $testAttributeCode,
'option' => $optionData,
]
);
$this->assertTrue(is_numeric($response));
/* Check new option labels by stores */
$expectedStoreLabels = [
'all' => $optionData[AttributeOptionLabelInterface::LABEL],
'default' => $optionData[AttributeOptionInterface::STORE_LABELS][0][AttributeOptionLabelInterface::LABEL],
];
foreach ($expectedStoreLabels as $store => $label) {
$option = $this->getAttributeOption($testAttributeCode, $label, $store);
$this->assertNotNull($option);
$this->assertEquals($response, $option['value']);
}
}
/**
* Data provider for adding attribute option
*
* @return array
*/
public function addDataProvider(): array
{
$optionPayload = [
AttributeOptionInterface::LABEL => 'new color',
AttributeOptionInterface::SORT_ORDER => 100,
AttributeOptionInterface::IS_DEFAULT => true,
AttributeOptionInterface::STORE_LABELS => [
[
AttributeOptionLabelInterface::LABEL => 'DE label',
AttributeOptionLabelInterface::STORE_ID => 1,
],
],
AttributeOptionInterface::VALUE => ''
];
return [
'option_without_value_node' => [
$optionPayload
],
'option_with_value_node_that_starts_with_text' => [
array_merge($optionPayload, [AttributeOptionInterface::VALUE => 'some_text'])
],
'option_with_value_node_that_starts_with_a_number' => [
array_merge($optionPayload, [AttributeOptionInterface::VALUE => '123_some_text'])
],
'option_with_value_node_that_is_a_number' => [
array_merge($optionPayload, [AttributeOptionInterface::VALUE => '123'])
],
];
}
/**
* Test to delete attribute option
*
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php
*/
public function testDelete()
{
$attributeCode = 'select_attribute';
$optionList = $this->getAttributeOptions($attributeCode);
$this->assertGreaterThan(0, count($optionList));
$lastOption = array_pop($optionList);
$this->assertNotEmpty($lastOption['value']);
$optionId = $lastOption['value'];
$response = $this->webApiCallAttributeOptions(
$attributeCode,
Request::HTTP_METHOD_DELETE,
'delete',
[
'attributeCode' => $attributeCode,
'optionId' => $optionId,
],
$optionId
);
$this->assertTrue($response);
$updatedOptions = $this->getAttributeOptions($attributeCode);
$this->assertEquals($optionList, $updatedOptions);
}
/**
* Perform Web API call to the system under test
*
* @param string $attributeCode
* @param string $httpMethod
* @param string $soapMethod
* @param array $arguments
* @param null $storeCode
* @param null $optionId
* @return array|bool|float|int|string
*/
private function webApiCallAttributeOptions(
string $attributeCode,
string $httpMethod,
string $soapMethod,
array $arguments = [],
$optionId = null,
$storeCode = null
) {
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode . '/options'
. ($optionId ? '/' .$optionId : ''),
'httpMethod' => $httpMethod,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . $soapMethod,
],
];
return $this->_webApiCall($serviceInfo, $arguments, null, $storeCode);
}
/**
* @param string $testAttributeCode
* @param string|null $storeCode
* @return array|bool|float|int|string
*/
private function getAttributeOptions(string $testAttributeCode, ?string $storeCode = null)
{
return $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_GET,
'getItems',
['attributeCode' => $testAttributeCode],
null,
$storeCode
);
}
/**
* @param string $attributeCode
* @param string $optionLabel
* @param string|null $storeCode
* @return array|null
*/
private function getAttributeOption(
string $attributeCode,
string $optionLabel,
?string $storeCode = null
): ?array {
$attributeOptions = $this->getAttributeOptions($attributeCode, $storeCode);
$option = null;
/** @var array $attributeOption */
foreach ($attributeOptions as $attributeOption) {
if ($attributeOption['label'] === $optionLabel) {
$option = $attributeOption;
break;
}
}
return $option;
}
}
@@ -0,0 +1,234 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Api\Data\AttributeOptionLabelInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Class to test update Product Attribute Options
*/
class ProductAttributeOptionUpdateInterfaceTest extends WebapiAbstract
{
private const SERVICE_NAME_UPDATE = 'catalogProductAttributeOptionUpdateV1';
private const SERVICE_NAME = 'catalogProductAttributeOptionManagementV1';
private const SERVICE_VERSION = 'V1';
private const RESOURCE_PATH = '/V1/products/attributes';
/**
* Test to update attribute option
*
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php
*/
public function testUpdate()
{
$testAttributeCode = 'select_attribute';
$optionData = [
AttributeOptionInterface::LABEL => 'Fixture Option Changed',
AttributeOptionInterface::VALUE => 'option_value',
AttributeOptionInterface::STORE_LABELS => [
[
AttributeOptionLabelInterface::LABEL => 'Store Label Changed',
AttributeOptionLabelInterface::STORE_ID => 1,
],
],
];
$existOptionLabel = 'Fixture Option';
$existAttributeOption = $this->getAttributeOption($testAttributeCode, $existOptionLabel, 'all');
$optionId = $existAttributeOption['value'];
$response = $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_PUT,
'update',
[
'attributeCode' => $testAttributeCode,
'optionId' => $optionId,
'option' => $optionData,
],
$optionId
);
$this->assertTrue($response);
/* Check update option labels by stores */
$expectedStoreLabels = [
'all' => $optionData[AttributeOptionLabelInterface::LABEL],
'default' => $optionData[AttributeOptionInterface::STORE_LABELS][0][AttributeOptionLabelInterface::LABEL],
];
foreach ($expectedStoreLabels as $store => $label) {
$this->assertNotNull($this->getAttributeOption($testAttributeCode, $label, $store));
}
}
/**
* Test to update option with already exist exception
*
* Test to except case when the two options has a same label
*
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php
*/
public function testUpdateWithAlreadyExistsException()
{
$this->expectExceptionMessage("Admin store attribute option label '%1' is already exists.");
$testAttributeCode = 'select_attribute';
$newOptionData = [
AttributeOptionInterface::LABEL => 'New Option',
AttributeOptionInterface::VALUE => 'new_option_value',
];
$newOptionId = $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_POST,
'add',
[
'attributeCode' => $testAttributeCode,
'option' => $newOptionData,
]
);
$editOptionData = [
AttributeOptionInterface::LABEL => 'Fixture Option',
AttributeOptionInterface::VALUE => $newOptionId,
];
$this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_PUT,
'update',
[
'attributeCode' => $testAttributeCode,
'optionId' => $newOptionId,
'option' => $editOptionData,
],
$newOptionId
);
}
/**
* Test to update option with not exist exception
*
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php
*/
public function testUpdateWithNotExistsException()
{
$this->expectExceptionMessage("The '%1' attribute doesn't include an option id '%2'.");
$testAttributeCode = 'select_attribute';
$newOptionData = [
AttributeOptionInterface::LABEL => 'New Option',
AttributeOptionInterface::VALUE => 'new_option_value'
];
$newOptionId = (int)$this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_POST,
'add',
[
'attributeCode' => $testAttributeCode,
'option' => $newOptionData,
]
);
$newOptionId++;
$editOptionData = [
AttributeOptionInterface::LABEL => 'New Option Changed',
AttributeOptionInterface::VALUE => $newOptionId
];
$this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_PUT,
'update',
[
'attributeCode' => $testAttributeCode,
'optionId' => $newOptionId,
'option' => $editOptionData,
],
$newOptionId
);
}
/**
* Perform Web API call to the system under test
*
* @param string $attributeCode
* @param string $httpMethod
* @param string $soapMethod
* @param array $arguments
* @param null $storeCode
* @param null $optionId
* @return array|bool|float|int|string
*/
private function webApiCallAttributeOptions(
string $attributeCode,
string $httpMethod,
string $soapMethod,
array $arguments = [],
$optionId = null,
$storeCode = null
) {
$resourcePath = self::RESOURCE_PATH . "/{$attributeCode}/options";
if ($optionId) {
$resourcePath .= '/' . $optionId;
}
$serviceName = $soapMethod === 'update' ? self::SERVICE_NAME_UPDATE : self::SERVICE_NAME;
$serviceInfo = [
'rest' => [
'resourcePath' => $resourcePath,
'httpMethod' => $httpMethod,
],
'soap' => [
'service' => $serviceName,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => $serviceName . $soapMethod,
],
];
return $this->_webApiCall($serviceInfo, $arguments, null, $storeCode);
}
/**
* @param string $attributeCode
* @param string $optionLabel
* @param string|null $storeCode
* @return array|null
*/
private function getAttributeOption(
string $attributeCode,
string $optionLabel,
?string $storeCode = null
): ?array {
$attributeOptions = $this->getAttributeOptions($attributeCode, $storeCode);
$option = null;
/** @var array $attributeOption */
foreach ($attributeOptions as $attributeOption) {
if ($attributeOption['label'] === $optionLabel) {
$option = $attributeOption;
break;
}
}
return $option;
}
/**
* @param string $testAttributeCode
* @param string|null $storeCode
* @return array|bool|float|int|string
*/
private function getAttributeOptions(string $testAttributeCode, ?string $storeCode = null)
{
return $this->webApiCallAttributeOptions(
$testAttributeCode,
Request::HTTP_METHOD_GET,
'getItems',
['attributeCode' => $testAttributeCode],
null,
$storeCode
);
}
}
@@ -0,0 +1,547 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;
/**
* API tests for \Magento\Catalog\Model\Product\Attribute\Repository.
*/
class ProductAttributeRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attributes';
/**
* @var array
*/
private $createdAttributes = [];
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
* @return void
*/
public function testGet()
{
$attributeCode = 'test_attribute_code_333';
$attribute = $this->getAttribute($attributeCode);
$this->assertIsArray($attribute);
$this->assertArrayHasKey('attribute_id', $attribute);
$this->assertArrayHasKey('attribute_code', $attribute);
$this->assertEquals($attributeCode, $attribute['attribute_code']);
}
/**
* @return void
*/
public function testGetList()
{
$searchCriteria = [
'searchCriteria' => [
'filter_groups' => [
[
'filters' => [
[
'field' => 'frontend_input',
'value' => 'textarea',
'condition_type' => 'eq',
],
],
],
],
'current_page' => 1,
'page_size' => 2,
],
'entityTypeCode' => \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE,
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($searchCriteria),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$response = $this->_webApiCall($serviceInfo, $searchCriteria);
$this->assertArrayHasKey('search_criteria', $response);
$this->assertArrayHasKey('total_count', $response);
$this->assertArrayHasKey('items', $response);
$this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
$this->assertTrue($response['total_count'] > 0);
$this->assertTrue(count($response['items']) > 0);
$this->assertNotNull($response['items'][0]['default_frontend_label']);
$this->assertNotNull($response['items'][0]['attribute_id']);
}
/**
* Test create attribute
*
* @dataProvider attributeCodeDataProvider
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
* @param string $attributeCode
* @return void
*/
public function testCreate(string $attributeCode): void
{
$attribute = $this->createAttribute($attributeCode);
$expectedData = [
'attribute_code' => $attributeCode,
'is_required' => true,
'entity_type_id' => "4",
"frontend_input" => "select",
"is_visible_on_front" => true,
"is_searchable" => true,
"is_visible_in_advanced_search" => true,
"is_filterable" => true,
"is_filterable_in_search" => true,
];
$this->assertEquals('default_label', $attribute['default_frontend_label']);
$this->assertEquals('front_lbl_store1', $attribute['frontend_labels'][0]['label']);
foreach ($expectedData as $key => $value) {
$this->assertEquals($value, $attribute[$key]);
}
//Validate options
//'Blue' should be first as it has sort_order = 0
$this->assertEquals('Default Blue', $attribute['options'][1]['label']);
$this->assertArrayHasKey('default_value', $attribute);
//'Blue' should be set as default
$this->assertEquals($attribute['default_value'], $attribute['options'][1]['value']);
$this->assertEquals('Default Red', $attribute['options'][2]['label']);
}
/**
* @return array
*/
public function attributeCodeDataProvider(): array
{
return [
[str_repeat('az_7', 15)],
[uniqid('label_attr_code')],
];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
* @return void
*/
public function testCreateWithExceptionIfAttributeAlreadyExists()
{
$attributeCode = 'test_attribute_code_333';
try {
$this->createAttribute($attributeCode);
$this->fail("Expected exception");
// phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
} catch (\SoapFault $e) {
//Expects soap exception
} catch (\Exception $e) {
$this->assertEquals(HTTPExceptionCodes::HTTP_BAD_REQUEST, $e->getCode());
}
}
/**
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
* @return void
*/
public function testUpdate()
{
$attributeCode = uniqid('label_attr_code');
$attribute = $this->createAttribute($attributeCode);
//Make sure that 'Blue' is set as default
$this->assertEquals($attribute['default_value'], $attribute['options'][1]['value']);
$attributeData = [
'attribute' => [
'attribute_id' => $attribute['attribute_id'],
'attribute_code' => $attributeCode,
'entity_type_id' => 4,
'is_used_in_grid' => true,
//Update existing
'default_frontend_label' => 'default_label_new',
'frontend_labels' => [
//Update existing
['store_id' => 0, 'label' => 'front_lbl_store0_new'],
['store_id' => 1, 'label' => 'front_lbl_store1_new'],
],
"options" => [
//Update existing
[
"value" => $attribute['options'][1]['value'],
"label" => "New Label",
"store_labels" => [
[
"store_id" => 1,
"label" => "Default Blue Updated"
]
]
],
//Add new option
[
"label" => "Green",
"value" => "",
"sort_order" => 200,
"is_default" => true,
"store_labels" => [
[
"store_id" => 0,
"label" => "Admin Green"
],
[
"store_id" => 1,
"label" => "Default Green"
]
]
]
],
'is_required' => false,
'frontend_input' => 'select',
],
];
$result = $this->updateAttribute($attributeCode, $attributeData);
$this->assertEquals($attribute['attribute_id'], $result['attribute_id']);
$this->assertTrue($result['is_used_in_grid']);
$this->assertEquals($attributeCode, $result['attribute_code']);
$this->assertEquals('default_label_new', $result['default_frontend_label']);
$this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']);
//New option set as default
$this->assertEquals($result['options'][3]['value'], $result['default_value']);
$this->assertEquals("Default Blue Updated", $result['options'][1]['label']);
}
/**
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
* @return void
*/
public function testUpdateWithNoDefaultLabelAndAdminStorelabel()
{
$attributeCode = uniqid('label_attr_code');
$attribute = $this->createAttribute($attributeCode);
$attributeData = [
'attribute' => [
'attribute_id' => $attribute['attribute_id'],
'attribute_code' => $attributeCode,
'entity_type_id' => 4,
'is_used_in_grid' => true,
'frontend_labels' => [
//Update existing
['store_id' => 0, 'label' => 'front_lbl_store0_new'],
['store_id' => 1, 'label' => 'front_lbl_store1_new'],
],
'is_required' => false,
'frontend_input' => 'select',
],
];
$result = $this->updateAttribute($attributeCode, $attributeData);
$this->assertEquals($attribute['attribute_id'], $result['attribute_id']);
$this->assertTrue($result['is_used_in_grid']);
$this->assertEquals($attributeCode, $result['attribute_code']);
$this->assertEquals('front_lbl_store0_new', $result['default_frontend_label']);
$this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']);
}
/**
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
* @return void
*/
public function testUpdateWithNoDefaultLabelAndNoAdminStoreLabel()
{
$attributeCode = uniqid('label_attr_code');
$attribute = $this->createAttribute($attributeCode);
$attributeData = [
'attribute' => [
'attribute_id' => $attribute['attribute_id'],
'attribute_code' => $attributeCode,
'entity_type_id' => 4,
'is_used_in_grid' => true,
'frontend_labels' => [
//Update existing
['store_id' => 1, 'label' => 'front_lbl_store1_new'],
],
'is_required' => false,
'frontend_input' => 'select',
],
];
$result = $this->updateAttribute($attributeCode, $attributeData);
$this->assertEquals($attribute['attribute_id'], $result['attribute_id']);
$this->assertTrue($result['is_used_in_grid']);
$this->assertEquals($attributeCode, $result['attribute_code']);
$this->assertEquals('default_label', $result['default_frontend_label']);
$this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']);
}
/**
* @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
* @return void
*/
public function testUpdateWithNewOption()
{
$attributeCode = uniqid('label_attr_code');
$attribute = $this->createAttribute($attributeCode);
$attributeData = [
'attribute' => [
'attribute_id' => $attribute['attribute_id'],
'attribute_code' => $attributeCode,
'entity_type_id' => 4,
'is_required' => true,
'frontend_labels' => [
['store_id' => 0, 'label' => 'front_lbl_new'],
],
"options" => [
[
"value" => 'option',
"label" => "New Label",
"store_labels" => [
[
"store_id" => 1,
"label" => "new label"
]
]
],
],
'frontend_input' => 'select',
]
];
$output = $this->updateAttribute($attributeCode, $attributeData);
$this->assertCount(4, $output['options']);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
* @return void
*/
public function testDeleteById()
{
$attributeCode = 'test_attribute_code_333';
$this->assertTrue($this->deleteAttribute($attributeCode));
}
/**
* Trying to delete system attribute.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_system_attribute.php
* @return void
*/
public function testDeleteSystemAttributeById(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The system attribute can\'t be deleted.');
$attributeCode = 'test_attribute_code_333';
$this->deleteAttribute($attributeCode);
}
/**
* @return void
*/
public function testDeleteNoSuchEntityException()
{
$attributeCode = 'some_test_code';
$expectedMessage =
'The attribute with a "%1" attributeCode doesn\'t exist. Verify the attribute and try again.';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'deleteById',
],
];
try {
$this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
$this->fail("Expected exception");
} catch (\SoapFault $e) {
$this->assertStringContainsString(
$expectedMessage,
$e->getMessage(),
"SoapFault does not contain expected message."
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals($expectedMessage, $errorObj['message']);
$this->assertEquals([$attributeCode], $errorObj['parameters']);
$this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode());
}
}
/**
* @param $attributeCode
* @return array|bool|float|int|string
*/
protected function createAttribute($attributeCode)
{
$attributeData = [
'attribute' => [
'attribute_code' => $attributeCode,
'entity_type_id' => '4',
"default_frontend_label" => 'default_label',
'frontend_labels' => [
['store_id' => 0, 'label' => 'front_lbl_store0'],
['store_id' => 1, 'label' => 'front_lbl_store1'],
],
'is_required' => true,
"default_value" => "",
"frontend_input" => "select",
"is_visible_on_front" => true,
"is_searchable" => true,
"is_visible_in_advanced_search" => true,
"is_filterable" => true,
"is_filterable_in_search" => true,
"options" => [
[
"label" => "Red",
"value" => "",
"sort_order" => 100,
"is_default" => false,
"store_labels" => [
[
"store_id" => 0,
"label" => "Admin Red"
],
[
"store_id" => 1,
"label" => "Default Red"
]
]
],
[
"label" => "Blue",
"value" => "",
"sort_order" => 0,
"is_default" => true,
"store_labels" => [
[
"store_id" => 0,
"label" => "Admin Blue"
],
[
"store_id" => 1,
"label" => "Default Blue"
]
]
]
]
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$attribute = $this->_webApiCall($serviceInfo, $attributeData);
if (isset($attribute['attribute_id']) && $attribute['attribute_id']) {
$this->createdAttributes[] = $attributeCode;
}
return $attribute;
}
/**
* @param $attributeCode
* @return array|bool|float|int|string
*/
protected function getAttribute($attributeCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
}
/**
* Delete attribute by code
*
* @param $attributeCode
* @return array|bool|float|int|string
*/
protected function deleteAttribute($attributeCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'deleteById',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
}
/**
* Update attribute by code
*
* @param $attributeCode
* @return array|bool|float|int|string
*/
protected function updateAttribute($attributeCode, $attributeData)
{
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$attributeData['attribute']['attributeCode'] = $attributeCode;
}
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
return $this->_webApiCall($serviceInfo, $attributeData);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
foreach ($this->createdAttributes as $attributeCode) {
$this->deleteAttribute($attributeCode);
}
}
}
@@ -0,0 +1,36 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
class ProductAttributeTypesListTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeTypesListV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attributes';
public function testGetItems()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/types',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetItems',
],
];
$types = $this->_webApiCall($serviceInfo);
$this->assertTrue(count($types) > 0);
$this->assertArrayHasKey('value', $types[0]);
$this->assertArrayHasKey('label', $types[0]);
$this->assertNotNull($types[0]['value']);
$this->assertNotNull($types[0]['label']);
}
}
@@ -0,0 +1,156 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductCustomAttributeWrongTypeTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/';
const SIMPLE_PRODUCT_SKU = 'simple';
/**
* Execute per test cleanup
*/
protected function tearDown(): void
{
$this->deleteProductBySku(self::SIMPLE_PRODUCT_SKU);
parent::tearDown();
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_new.php
*/
public function testCustomAttributeWrongType()
{
$this->expectException(\Exception::class);
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . 'simple',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$this->expectException('Exception');
$this->expectExceptionMessage('Attribute "meta_title" has invalid value.');
} else {
$this->expectException('Exception');
$this->expectExceptionMessage('Attribute \"meta_title\" has invalid value.');
}
$this->_webApiCall($serviceInfo, $this->getRequestData());
}
protected function getRequestData()
{
return [
"product"=> [
"sku"=> 'simple',
"name"=> "SimpleProd",
"attribute_set_id"=> 4,
"price"=> 555,
"status"=> 1,
"visibility"=> 4,
"type_id"=> "simple",
"created_at"=> "2016-03-28 07=>49=>39",
"updated_at"=> "2016-03-29 06=>45=>30",
"weight"=> 434,
"extension_attributes"=> [
"stock_item"=> [
"item_id"=> 1,
"product_id"=> 1,
"stock_id"=> 1,
"qty"=> 1000,
"is_in_stock"=> true,
"is_qty_decimal"=> false,
"show_default_notification_message"=> false,
"use_config_min_qty"=> true,
"min_qty"=> 0,
"use_config_min_sale_qty"=> 1,
"min_sale_qty"=> 1,
"use_config_max_sale_qty"=> true,
"max_sale_qty"=> 10000,
"use_config_backorders"=> true,
"backorders"=> 0,
"use_config_notify_stock_qty"=> true,
"notify_stock_qty"=> 1,
"use_config_qty_increments"=> true,
"qty_increments"=> 0,
"use_config_enable_qty_inc"=> false,
"enable_qty_increments"=> false,
"use_config_manage_stock"=> true,
"manage_stock"=> true,
"low_stock_date"=> null,
"is_decimal_divided"=> false,
"stock_status_changed_auto"=> 0
]
],
"product_links"=> [],
"options"=> [
[
"product_sku"=> "simple",
"option_id"=> 1,
"title"=> "simple",
"type"=> "drop_down",
"sort_order"=> 1,
"is_require"=> true,
"max_characters"=> 0,
"image_size_x"=> 0,
"image_size_y"=> 0,
"values"=> [
[
"title"=> "sadasdad",
"sort_order"=> 1,
"price"=> 555,
"price_type"=> "fixed",
"sku"=> "dfsdfsdf",
"option_type_id"=> 1
]
]
]
],
"media_gallery_entries"=> [],
"tier_prices"=> [],
"custom_attributes"=> [
[
"attribute_code"=> "meta_title",
"value"=> [1,2,3]
],
],
],
];
}
protected function deleteProductBySku($productSku)
{
$resourcePath = self::RESOURCE_PATH . $productSku;
$serviceInfo = [
'rest' => [
'resourcePath' => $resourcePath,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'deleteById',
],
];
$requestData = ["sku" => $productSku];
$response = $this->_webApiCall($serviceInfo, $requestData);
return $response;
}
}
@@ -0,0 +1,450 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Catalog\Model\ProductRepository;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductCustomOptionRepositoryTest extends WebapiAbstract
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
const SERVICE_NAME = 'catalogProductCustomOptionRepositoryV1';
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->productFactory = $this->objectManager->get(\Magento\Catalog\Model\ProductFactory::class);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
*/
public function testRemove()
{
$sku = 'simple';
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(
\Magento\Catalog\Model\ProductRepository::class
);
/** @var \Magento\Catalog\Model\Product $product */
$product = $productRepository->get($sku, false, null, true);
$customOptions = $product->getOptions();
$optionId = array_pop($customOptions)->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => "/V1/products/$sku/options/$optionId",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'DeleteByIdentifier',
],
];
$this->assertTrue($this->_webApiCall($serviceInfo, ['sku' => $sku, 'optionId' => $optionId]));
/** @var \Magento\Catalog\Model\Product $product */
$product = $productRepository->get($sku, false, null, true);
$this->assertNull($product->getOptionById($optionId));
$this->assertCount(9, $product->getOptions());
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
*/
public function testGet()
{
$productSku = 'simple';
/** @var \Magento\Catalog\Api\ProductCustomOptionRepositoryInterface $service */
$service = Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductCustomOptionRepositoryInterface::class);
$options = $service->getList('simple');
$option = current($options);
$optionId = $option->getOptionId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $productSku . "/options/" . $optionId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Get',
],
];
$option = $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'optionId' => $optionId]);
unset($option['product_sku']);
unset($option['option_id']);
$excepted = include '_files/product_options.php';
$this->assertEquals($excepted[0], $option);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function testGetList()
{
$this->_markTestAsRestOnly('Fix inconsistencies in WSDL and Data interfaces');
$productSku = 'simple';
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $productSku . "/options",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$options = $this->_webApiCall($serviceInfo, ['sku' => $productSku]);
/** Unset dynamic data */
foreach ($options as $key => $value) {
unset($options[$key]['product_sku']);
unset($options[$key]['option_id']);
if (!empty($options[$key]['values'])) {
foreach ($options[$key]['values'] as $newKey => $valueData) {
unset($options[$key]['values'][$newKey]['option_type_id']);
}
}
}
$excepted = include '_files/product_options.php';
$this->assertEquals(count($excepted), count($options));
//in order to make assertion result readable we need to check each element separately
foreach ($excepted as $index => $value) {
$this->assertEquals($value, $options[$index]);
}
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_without_options.php
* @magentoAppIsolation enabled
* @dataProvider optionDataProvider
* @param array $optionData
*/
public function testSave($optionData)
{
$productSku = 'simple';
/** @var \Magento\Catalog\Model\ProductRepository $productRepository */
$productRepository = $this->objectManager->create(
\Magento\Catalog\Model\ProductRepository::class
);
$optionDataPost = $optionData;
$optionDataPost['product_sku'] = $productSku;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
$result = $this->_webApiCall($serviceInfo, ['option' => $optionDataPost]);
$product = $productRepository->get($productSku);
unset($result['product_sku']);
unset($result['option_id']);
if (!empty($result['values'])) {
foreach (array_keys($result['values']) as $key) {
unset($result['values'][$key]['option_type_id']);
}
}
$this->assertEquals($optionData, $result);
$this->assertTrue($product->getHasOptions() == 1);
if ($optionDataPost['is_require']) {
$this->assertTrue($product->getRequiredOptions() == 1);
}
}
public function optionDataProvider()
{
$fixtureOptions = [];
$fixture = include '_files/product_options.php';
foreach ($fixture as $item) {
$fixtureOptions[$item['type']] = [
'optionData' => $item,
];
}
return $fixtureOptions;
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_without_options.php
* @magentoAppIsolation enabled
* @dataProvider optionNegativeDataProvider
*/
public function testAddNegative($optionData)
{
$productSku = 'simple';
$optionDataPost = $optionData;
$optionDataPost['product_sku'] = $productSku;
$serviceInfo = [
'rest' => [
'resourcePath' => "/V1/products/options",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
if ($optionDataPost['title'] === null || $optionDataPost['title'] === '') {
$this->expectException('SoapFault');
$this->expectExceptionMessage('Missed values for option required fields');
} else {
$this->expectException('SoapFault');
$this->expectExceptionMessage('Invalid option');
}
} else {
$this->expectException('Exception');
$this->expectExceptionCode(400);
}
$this->_webApiCall($serviceInfo, ['option' => $optionDataPost]);
}
public function optionNegativeDataProvider()
{
$fixtureOptions = [];
$fixture = include '_files/product_options_negative.php';
foreach ($fixture as $key => $item) {
$fixtureOptions[$key] = [
'optionData' => $item,
];
}
return $fixtureOptions;
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
*/
public function testUpdate()
{
$productSku = 'simple';
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(
\Magento\Catalog\Model\ProductRepository::class
);
$options = $productRepository->get($productSku, true)->getOptions();
$option = array_shift($options);
$optionId = $option->getOptionId();
$optionDataPost = [
'product_sku' => $productSku,
'title' => $option->getTitle() . "_updated",
'type' => $option->getType(),
'sort_order' => (int)$option->getSortOrder(),
'is_require' => (bool)$option->getIsRequire(),
'price' => $option->getPrice(),
'price_type' => $option->getPriceType(),
'sku' => $option->getSku(),
'max_characters' => 500,
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/options/' . $optionId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$optionDataPost['option_id'] = $optionId;
$updatedOption = $this->_webApiCall(
$serviceInfo,
['id' => $optionId, 'option' => $optionDataPost]
);
unset($optionDataPost['option_id']);//update change option id now
} else {
$updatedOption = $this->_webApiCall($serviceInfo, ['option' => $optionDataPost]);
}
unset($updatedOption['values']);
unset($updatedOption['option_id']);//update change option id now
$this->assertEquals($optionDataPost, $updatedOption);
}
/**
* @param string $optionType
* @param bool $includedExisting
* @param int $expectedOptionValuesCount
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
* @dataProvider validOptionDataProvider
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function testUpdateOptionAddingNewValue($optionType, $includedExisting, $expectedOptionValuesCount)
{
$fixtureOption = null;
$valueData = [
'price' => 100500,
'price_type' => 'fixed',
'sku' => 'new option sku ' . $optionType,
'title' => 'New Option Title',
'sort_order' => 100,
];
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(
\Magento\Catalog\Model\ProductRepository::class
);
/** @var \Magento\Catalog\Model\Product $product */
$product = $productRepository->get('simple', false, null, true);
/**@var $option \Magento\Catalog\Model\Product\Option */
foreach ($product->getOptions() as $option) {
if ($option->getType() == $optionType) {
$fixtureOption = $option;
break;
}
}
$values = [];
$values[] = $valueData;
// Keeps the existing Option Values when adding a new Option Value
if ($includedExisting) {
foreach ($option->getValues() as $key => $value) {
$values[] =
[
'price' => $value->getPrice(),
'price_type' => $value->getPriceType(),
'sku' => $value->getSku(),
'title' => $value->getTitle(),
'sort_order' => $value->getSortOrder(),
];
}
}
$data = [
'product_sku' => $option->getProductSku(),
'title' => $option->getTitle(),
'type' => $option->getType(),
'is_require' => $option->getIsRequire(),
'sort_order' => $option->getSortOrder(),
'values' => $values,
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/options/' . $fixtureOption->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'Save',
],
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$data['option_id'] = $fixtureOption->getId();
$valueObject = $this->_webApiCall(
$serviceInfo,
[ 'option_id' => $fixtureOption->getId(), 'option' => $data]
);
} else {
$valueObject = $this->_webApiCall($serviceInfo, ['option' => $data]);
}
$values = reset($valueObject['values']);
$this->assertEquals($valueData['price'], $values['price']);
$this->assertEquals($valueData['price_type'], $values['price_type']);
$this->assertEquals($valueData['sku'], $values['sku']);
$this->assertEquals('New Option Title', $values['title']);
$this->assertEquals(100, $values['sort_order']);
$product = $productRepository->get('simple', false, null, true);
// Assert correct number of Option Values after Option is updated
foreach ($product->getOptions() as $option) {
if ($option->getId() === $fixtureOption->getId()) {
$this->assertEquals($expectedOptionValuesCount, count($option->getValues()));
}
}
}
public function validOptionDataProvider()
{
return [
'drop_down including previous values' => ['drop_down', true, 3],
'drop_down with new value only' => ['drop_down', false, 1],
'checkbox including previous values' => ['checkbox', true, 3],
'checkbox with new value only' => ['checkbox', false, 1],
'radio including previous values' => ['radio', true, 3],
'multiple with new value only' => ['multiple', false, 1],
];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
* @magentoAppIsolation enabled
* @dataProvider optionNegativeUpdateDataProvider
* @param array $optionData
* @param string $message
* @param int $exceptionCode
*/
public function testUpdateNegative($optionData, $message, $exceptionCode)
{
$this->_markTestAsRestOnly();
$productSku = 'simple';
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(ProductRepository::class);
$options = $productRepository->get($productSku, true)->getOptions();
$option = array_shift($options);
$optionId = $option->getOptionId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/options/' . $optionId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
];
$this->expectException('Exception');
$this->expectExceptionMessage($message);
$this->expectExceptionCode($exceptionCode);
$this->_webApiCall($serviceInfo, ['option' => $optionData]);
}
/**
* @return array
*/
public function optionNegativeUpdateDataProvider()
{
return include '_files/product_options_update_negative.php';
}
}
@@ -0,0 +1,43 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductCustomOptionTypeListTest extends WebapiAbstract
{
const RESOURCE_PATH = '/V1/products/options/';
const SERVICE_NAME = 'catalogProductCustomOptionTypeListV1';
/**
* @magentoAppIsolation enabled
*/
public function testGetTypes()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "types",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => 'V1',
'operation' => self::SERVICE_NAME . 'GetItems',
],
];
$types = $this->_webApiCall($serviceInfo);
$excepted = [
'label' => __('Drop-down'),
'code' => 'drop_down',
'group' => __('Select'),
];
$this->assertGreaterThanOrEqual(10, count($types));
$this->assertContainsEquals($excepted, $types);
}
}
@@ -0,0 +1,151 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* @magentoAppIsolation enabled
*/
class ProductLinkManagementInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductLinkManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_crosssell.php
*/
public function testGetLinkedProductsCrossSell()
{
$productSku = 'simple_with_cross';
$linkType = 'crosssell';
$this->assertLinkedProducts($productSku, $linkType);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_related.php
*/
public function testGetLinkedProductsRelated()
{
$productSku = 'simple_with_cross';
$linkType = 'related';
$this->assertLinkedProducts($productSku, $linkType);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_upsell.php
*/
public function testGetLinkedProductsUpSell()
{
$productSku = 'simple_with_upsell';
$linkType = 'upsell';
$this->assertLinkedProducts($productSku, $linkType);
}
/**
* @param string $productSku
* @param int $linkType
*/
protected function assertLinkedProducts($productSku, $linkType)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . $productSku . '/links/' . $linkType,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetLinkedItemsByType',
],
];
$actual = $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'type' => $linkType]);
$this->assertArrayHasKey(0, $actual);
$this->assertEquals('simple', $actual[0]['linked_product_type']);
$this->assertEquals('simple', $actual[0]['linked_product_sku']);
$this->assertEquals(1, $actual[0]['position']);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_related.php
* @magentoApiDataFixture Magento/Catalog/_files/product_virtual_in_stock.php
*/
public function testAssign()
{
$linkType = 'related';
$productSku = 'simple';
$linkData = [
'linked_product_type' => 'virtual',
'linked_product_sku' => 'virtual-product',
'position' => 100,
'sku' => 'simple',
'link_type' => 'related',
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . $productSku . '/links',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'SetProductLinks',
],
];
$arguments = [
'sku' => $productSku,
'items' => [$linkData],
'type' => $linkType,
];
$this->_webApiCall($serviceInfo, $arguments);
$actual = $this->getLinkedProducts($productSku, 'related');
array_walk(
$actual,
function (&$item) {
/** @var \Magento\Catalog\Api\Data\ProductLinkInterface $item */
$item = $item->__toArray();
}
);
$this->assertEquals([$linkData], $actual);
}
/**
* Get list of linked products
*
* @param string $sku
* @param string $linkType
* @return \Magento\Catalog\Api\Data\ProductLinkInterface[]
*/
protected function getLinkedProducts($sku, $linkType)
{
/** @var \Magento\Catalog\Model\ProductLink\Management $linkManagement */
$linkManagement = $this->objectManager->get(\Magento\Catalog\Api\ProductLinkManagementInterface::class);
$linkedProducts = $linkManagement->getLinkedItemsByType($sku, $linkType);
return $linkedProducts;
}
}
@@ -0,0 +1,178 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Model\ProductLink\Link;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Class checks product relations functionality
*
* @see \Magento\Catalog\Api\ProductLinkRepositoryInterface
*/
class ProductLinkRepositoryInterfaceTest extends WebapiAbstract
{
/**
* @var string
*/
const SERVICE_NAME = 'catalogProductLinkRepositoryV1';
/**
* @var string
*/
const SERVICE_VERSION = 'V1';
/**
* @var string
*/
const RESOURCE_PATH = '/V1/products/';
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductLinkManagementInterface
*/
private $linkManagement;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->linkManagement = $this->objectManager->get(ProductLinkManagementInterface::class);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_related_multiple.php
*
* @return void
*/
public function testDelete(): void
{
$productSku = 'simple_with_cross';
$linkType = 'related';
$this->deleteApiCall($productSku, $linkType, 'simple');
$linkedProducts = $this->linkManagement->getLinkedItemsByType($productSku, $linkType);
$this->assertCount(1, $linkedProducts);
$product = current($linkedProducts);
$this->assertEquals('simple_with_cross_two', $product->getLinkedProductSku());
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*
* @return void
*/
public function testDeleteNotExistedProductLink(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage((string)__("Product %1 doesn't have linked %2 as %3"));
$this->deleteApiCall('simple', 'related', 'not_exists_product');
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_related.php
*
* @return void
*/
public function testSave(): void
{
$productSku = 'simple_with_cross';
$linkType = 'related';
$data = [
'entity' => [
Link::KEY_SKU => 'simple_with_cross',
Link::KEY_LINK_TYPE => 'related',
Link::KEY_LINKED_PRODUCT_SKU => 'simple',
Link::KEY_LINKED_PRODUCT_TYPE => 'simple',
Link::KEY_POSITION => 1000,
],
];
$this->saveApiCall($productSku, $data);
$actual = $this->linkManagement->getLinkedItemsByType($productSku, $linkType);
$this->assertCount(1, $actual, 'Invalid actual linked products count');
$this->assertEquals(1000, $actual[0]->getPosition(), 'Product position is not updated');
}
/**
* Get service info for api call
*
* @param string $resourcePath
* @param string $httpMethod
* @param string $operation
* @return array
*/
private function getServiceInfo(string $resourcePath, string $httpMethod, string $operation): array
{
return [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . $resourcePath,
'httpMethod' => $httpMethod,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . $operation,
],
];
}
/**
* Make api call to delete product link
*
* @param string $productSku
* @param string $linkType
* @param string $linkedSku
* @return array|int|string|float|bool
*/
private function deleteApiCall(string $productSku, string $linkType, string $linkedSku)
{
$serviceInfo = $this->getServiceInfo(
$productSku . '/links/' . $linkType . '/' . $linkedSku,
Request::HTTP_METHOD_DELETE,
'DeleteById'
);
return $this->_webApiCall(
$serviceInfo,
[
'sku' => $productSku,
'type' => $linkType,
'linkedProductSku' => $linkedSku,
]
);
}
/**
* Make api call to save product link
*
* @param string $productSku
* @param array $data
* @return array|bool|float|int|string
*/
private function saveApiCall(string $productSku, array $data)
{
$serviceInfo = $this->getServiceInfo(
$productSku . '/links',
Request::HTTP_METHOD_PUT,
'Save'
);
return $this->_webApiCall($serviceInfo, $data);
}
}
@@ -0,0 +1,53 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Catalog\Model\Product\Link;
class ProductLinkTypeListTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'catalogProductLinkTypeListV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/';
public function testGetItems()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . 'links/types',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetItems',
],
];
$actual = $this->_webApiCall($serviceInfo);
$expectedItems = ['name' => 'related', 'code' => Link::LINK_TYPE_RELATED];
$this->assertContainsEquals($expectedItems, $actual);
}
public function testGetItemAttributes()
{
$linkType = 'related';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . 'links/' . $linkType . '/attributes',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetItemAttributes',
],
];
$actual = $this->_webApiCall($serviceInfo, ['type' => $linkType]);
$expected = [['code' => 'position', 'type' => 'int']];
$this->assertEquals($expected, $actual);
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductMediaAttributeManagementTest extends WebapiAbstract
{
/**
* @magentoApiDataFixture Magento/Catalog/_files/attribute_set_with_image_attribute.php
*/
public function testGetList()
{
$attributeSetName = 'attribute_set_with_media_attribute';
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/media/types/' . $attributeSetName,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => 'catalogProductMediaAttributeManagementV1',
'serviceVersion' => 'V1',
'operation' => 'catalogProductMediaAttributeManagementV1GetList',
],
];
$requestData = [
'attributeSetName' => $attributeSetName,
];
$mediaAttributes = $this->_webApiCall($serviceInfo, $requestData);
$this->assertNotEmpty($mediaAttributes);
$attribute = $this->getAttributeByCode($mediaAttributes, 'funny_image');
$this->assertNotNull($attribute);
$this->assertEquals('Funny image', $attribute['default_frontend_label']);
$this->assertEquals(1, $attribute['is_user_defined']);
}
/**
* Retrieve attribute based on given attribute code
*
* @param array $attributeList
* @param string $attributeCode
* @return array|null
*/
protected function getAttributeByCode($attributeList, $attributeCode)
{
foreach ($attributeList as $attribute) {
if ($attributeCode == $attribute['attribute_code']) {
return $attribute;
}
}
return null;
}
}
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Api\SortOrderBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductRenderListInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductRenderListV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products-render-info/';
/**
* Test get list of products render information: prices, buttons data, etc...
*
* @magentoApiDataFixture Magento/Catalog/_files/product_virtual.php
* @magentoApiDataFixture Magento/Catalog/_files/product_special_price.php
* @dataProvider productRenderInfoProvider
* @param array $expectedRenderInfo
* @return void
*/
public function testGetList(array $expectedRenderInfo)
{
$expectedIds = [21, 31];
/** @var FilterBuilder $filterBuilder */
$filterBuilder = Bootstrap::getObjectManager()->create(FilterBuilder::class);
/** @var SortOrderBuilder $sortOrderBuilder */
$sortOrderBuilder = Bootstrap::getObjectManager()->create(SortOrderBuilder::class);
$sortOrder = $sortOrderBuilder
->setField('entity_id')
->setDirection(SortOrder::SORT_ASC)
->create();
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()
->create(SearchCriteriaBuilder::class);
$filter1 = $filterBuilder
->setField('entity_id')
->setValue(implode(",", $expectedIds))
->setConditionType('in')
->create();
$searchCriteriaBuilder->addFilters([$filter1])
->addSortOrder($sortOrder);
$searchData['search_criteria'] = $searchCriteriaBuilder->create()->__toArray();
$searchData['store_id'] = 1;
$searchData['currency_code'] = 'USD';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "?" . http_build_query($searchData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$result = $this->_webApiCall($serviceInfo, $searchData);
foreach ($result['items'] as $id => $resultItem) {
$expectedItem = $expectedRenderInfo[$id];
$this->assertEquals($expectedItem['name'], $resultItem['name']);
$this->assertEquals($expectedItem['type'], $resultItem['type']);
$this->assertEquals($expectedItem['is_salable'], $resultItem['is_salable']);
$this->assertEquals($expectedItem['store_id'], $resultItem['store_id']);
$this->assertEquals($expectedItem['currency_code'], $resultItem['currency_code']);
$this->assertEquals(
$expectedItem['final_price'],
$resultItem['price_info']['formatted_prices']['final_price']
);
}
}
/**
* Provider for parts of product information
* @return array
*/
public function productRenderInfoProvider()
{
return [
'simple_products_variation' => [
[
[
'id' => 21,
'name' => 'Virtual Product',
'type' => 'virtual',
'is_salable' => true,
'store_id' => 1,
'currency_code' => 'USD',
'final_price' => '<span class="price">$10.00</span>'
],
[
'id' => 31,
'name' => 'Simple Product',
'type' => 'simple',
'is_salable' => true,
'store_id' => 1,
'currency_code' => 'USD',
'final_price' => '<span class="price">$5.99</span>'
]
]
]
];
}
}
@@ -0,0 +1,284 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\Website\Link;
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\Eav\Model\Config;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Tests for products creation for all store views.
*
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProductRepositoryAllStoreViewsTest extends WebapiAbstract
{
const PRODUCT_SERVICE_NAME = 'catalogProductRepositoryV1';
const SERVICE_VERSION = 'V1';
const PRODUCTS_RESOURCE_PATH = '/V1/products';
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var Registry
*/
private $registry;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var Link
*/
private $productWebsiteLink;
/**
* @var Config
*/
private $eavConfig;
/**
* @var string
*/
private $productSku = 'simple';
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->eavConfig = $this->objectManager->get(Config::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->productWebsiteLink = $this->objectManager->get(Link::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
try {
$this->productRepository->deleteById($this->productSku);
} catch (NoSuchEntityException $e) {
//already deleted
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
parent::tearDown();
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category.php
* @return void
*/
public function testCreateProduct(): void
{
$productData = $this->getProductData();
$resultData = $this->saveProduct($productData);
$this->assertProductWebsites($this->productSku, $this->getAllWebsiteIds());
$this->assertProductData($productData, $resultData, $this->getAllWebsiteIds());
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/category.php
* @magentoApiDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
* @return void
*/
public function testCreateProductOnMultipleWebsites(): void
{
$productData = $this->getProductData();
$resultData = $this->saveProduct($productData);
$this->assertProductWebsites($this->productSku, $this->getAllWebsiteIds());
$this->assertProductData($productData, $resultData, $this->getAllWebsiteIds());
}
/**
* Saves product via API.
*
* @param array $product
* @return array
*/
private function saveProduct(array $product): array
{
$serviceInfo = [
'rest' => ['resourcePath' =>self::PRODUCTS_RESOURCE_PATH, 'httpMethod' => Request::HTTP_METHOD_POST],
'soap' => [
'service' => self::PRODUCT_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::PRODUCT_SERVICE_NAME . 'Save'
]
];
$requestData = ['product' => $product];
return $this->_webApiCall($serviceInfo, $requestData, null, 'all');
}
/**
* Returns product data.
*
* @return array
*/
private function getProductData(): array
{
$setId = (int)$this->eavConfig->getEntityType(ProductAttributeInterface::ENTITY_TYPE_CODE)
->getDefaultAttributeSetId();
return [
ProductInterface::SKU => $this->productSku,
ProductInterface::NAME => 'simple',
ProductInterface::TYPE_ID => Type::TYPE_SIMPLE,
ProductInterface::WEIGHT => 1,
ProductInterface::ATTRIBUTE_SET_ID => $setId,
ProductInterface::PRICE => 10,
ProductInterface::STATUS => Status::STATUS_ENABLED,
ProductInterface::VISIBILITY => Visibility::VISIBILITY_BOTH,
ProductInterface::EXTENSION_ATTRIBUTES_KEY => [
'stock_item' => [
StockItemInterface::IS_IN_STOCK => 1,
StockItemInterface::QTY => 1000,
StockItemInterface::IS_QTY_DECIMAL => 0,
StockItemInterface::SHOW_DEFAULT_NOTIFICATION_MESSAGE => 0,
StockItemInterface::USE_CONFIG_MIN_QTY => 0,
StockItemInterface::USE_CONFIG_MIN_SALE_QTY => 0,
StockItemInterface::MIN_QTY => 1,
StockItemInterface::MIN_SALE_QTY => 1,
StockItemInterface::MAX_SALE_QTY => 100,
StockItemInterface::USE_CONFIG_MAX_SALE_QTY => 0,
StockItemInterface::USE_CONFIG_BACKORDERS => 0,
StockItemInterface::BACKORDERS => 0,
StockItemInterface::USE_CONFIG_NOTIFY_STOCK_QTY => 0,
StockItemInterface::NOTIFY_STOCK_QTY => 0,
StockItemInterface::USE_CONFIG_QTY_INCREMENTS => 0,
StockItemInterface::QTY_INCREMENTS => 0,
StockItemInterface::USE_CONFIG_ENABLE_QTY_INC => 0,
StockItemInterface::ENABLE_QTY_INCREMENTS => 0,
StockItemInterface::USE_CONFIG_MANAGE_STOCK => 1,
StockItemInterface::MANAGE_STOCK => 1,
StockItemInterface::LOW_STOCK_DATE => null,
StockItemInterface::IS_DECIMAL_DIVIDED => 0,
StockItemInterface::STOCK_STATUS_CHANGED_AUTO => 0,
],
],
ProductInterface::CUSTOM_ATTRIBUTES => [
['attribute_code' => 'url_key', 'value' => 'simple'],
['attribute_code' => 'tax_class_id', 'value' => 2],
['attribute_code' => 'category_ids', 'value' => [333]]
]
];
}
/**
* Asserts that product is linked to websites in 'catalog_product_website' table.
*
* @param string $sku
* @param array $websiteIds
* @return void
*/
private function assertProductWebsites(string $sku, array $websiteIds): void
{
$productId = $this->productRepository->get($sku)->getId();
$this->assertEquals($websiteIds, $this->productWebsiteLink->getWebsiteIdsByProductId($productId));
}
/**
* Asserts result after product creation.
*
* @param array $productData
* @param array $resultData
* @param array $websiteIds
* @return void
*/
private function assertProductData(array $productData, array $resultData, array $websiteIds): void
{
foreach ($productData as $key => $value) {
if ($key == 'extension_attributes' || $key == 'custom_attributes') {
continue;
}
$this->assertEquals($value, $resultData[$key]);
}
foreach ($productData['custom_attributes'] as $attribute) {
$resultAttribute = $this->getCustomAttributeByCode(
$resultData['custom_attributes'],
$attribute['attribute_code']
);
if ($attribute['attribute_code'] == 'category_ids') {
$this->assertEquals(array_values($attribute['value']), array_values($resultAttribute['value']));
continue;
}
$this->assertEquals($attribute['value'], $resultAttribute['value']);
}
foreach ($productData['extension_attributes']['stock_item'] as $key => $value) {
$this->assertEquals($value, $resultData['extension_attributes']['stock_item'][$key]);
}
$this->assertEquals($websiteIds, $resultData['extension_attributes']['website_ids']);
}
/**
* Get list of all websites IDs.
*
* @return array
*/
private function getAllWebsiteIds(): array
{
$websiteIds = [];
foreach ($this->storeManager->getWebsites() as $website) {
$websiteIds[] = $website->getId();
}
return $websiteIds;
}
/**
* Returns custom attribute data by given code.
*
* @param array $attributes
* @param string $attributeCode
* @return array
*/
private function getCustomAttributeByCode(array $attributes, string $attributeCode): array
{
$items = array_filter(
$attributes,
function ($attribute) use ($attributeCode) {
return $attribute['attribute_code'] == $attributeCode;
}
);
return reset($items);
}
}
@@ -0,0 +1,121 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductRepositoryMultiCurrencyTest extends WebapiAbstract
{
const PRODUCT_SERVICE_NAME = 'catalogProductRepositoryV1';
const WEBSITES_SERVICE_NAME = 'storeWebsiteRepositoryV1';
const WEBSITE_LINK_SERVICE_NAME = 'catalogProductWebsiteLinkRepositoryV1';
const SERVICE_VERSION = 'V1';
const PRODUCTS_RESOURCE_PATH = '/V1/products';
const WEBSITES_RESOURCE_PATH = '/V1/store/websites';
/**
* @magentoApiDataFixture Magento/Catalog/_files/category.php
* @magentoApiDataFixture Magento/Store/_files/second_website_with_second_currency.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGet()
{
$sku = 'simple';
$this->assignProductToWebsite($sku, $this->getWebsiteId('test'));
$product = $this->getProduct($sku);
$this->assertEquals(10, $product['price']);
$product['price'] = 20;
$this->saveProduct($product, 'fixture_second_store');
$product = $this->getProduct($sku, 'fixture_third_store');
$this->assertEquals(20, $product['price']);
}
private function saveProduct($product, $storeCode = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $product['sku'],
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::PRODUCT_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::PRODUCT_SERVICE_NAME . 'Save'
]
];
$requestData = ['product' => $product];
return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
}
private function getProduct($sku, $storeCode = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::PRODUCTS_RESOURCE_PATH . '/' . $sku,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::PRODUCT_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::PRODUCT_SERVICE_NAME . 'get'
]
];
$requestData = ['sku' => $sku];
return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
}
private function getWebsiteId($websiteCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::WEBSITES_RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::WEBSITES_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::WEBSITES_SERVICE_NAME . 'GetList'
]
];
$response = $this->_webApiCall($serviceInfo);
$websiteId = null;
foreach ($response as $website) {
if ($website['code'] == $websiteCode) {
$websiteId = $website['id'];
}
}
$this->assertNotNull($websiteId);
return $websiteId;
}
private function assignProductToWebsite($sku, $websiteId)
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $sku . '/websites',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::WEBSITE_LINK_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::WEBSITE_LINK_SERVICE_NAME . 'save'
]
];
$requestData = [
"productWebsiteLink" => [
"websiteId" => $websiteId,
"sku" => $sku
]
];
$this->assertTrue($this->_webApiCall($serviceInfo, $requestData));
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Catalog\Api\Data\ProductInterface as Product;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductRepositoryMultiStoreTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products';
const STORE_CODE_FROM_FIXTURE = 'fixturestore';
const STORE_NAME_FROM_FIXTURE = 'Fixture Store';
private $productData = [
[
Product::SKU => 'simple',
Product::NAME => 'Simple Related Product',
Product::TYPE_ID => 'simple',
Product::PRICE => 10
],
[
Product::SKU => 'simple_with_cross',
Product::NAME => 'Simple Product With Related Product',
Product::TYPE_ID => 'simple',
Product::PRICE => 10
],
];
/**
* @magentoApiDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoApiDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGetMultiStore()
{
$productData = $this->productData[0];
$nameInFixtureStore = 'Name in fixture store';
/** @var $store \Magento\Store\Model\Group */
$store = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Store\Model\Store::class);
$store->load(self::STORE_CODE_FROM_FIXTURE);
$this->assertEquals(
self::STORE_NAME_FROM_FIXTURE,
$store->getName(),
'Precondition failed: fixture store was not created.'
);
$sku = $productData[Product::SKU];
/** @var \Magento\Catalog\Model\Product $product */
$product = Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->load($product->getIdBySku($sku));
$product->setName($nameInFixtureStore)->setStoreId($store->getId())->save();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $sku,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'get'
]
];
$requestData = ['id' => $sku, 'sku' => $sku];
$defaultStoreResponse = $this->_webApiCall($serviceInfo, $requestData);
$nameInDefaultStore = 'Simple Product';
$this->assertEquals(
$nameInDefaultStore,
$defaultStoreResponse[Product::NAME],
'Product name in default store is invalid.'
);
$fixtureStoreResponse = $this->_webApiCall($serviceInfo, $requestData, null, self::STORE_CODE_FROM_FIXTURE);
$this->assertEquals(
$nameInFixtureStore,
$fixtureStoreResponse[Product::NAME],
'Product name in fixture store is invalid.'
);
}
/**
* Remove test store
*/
public static function tearDownAfterClass(): void
{
parent::tearDownAfterClass();
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $store \Magento\Store\Model\Store */
$store = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Store\Model\Store::class);
$store->load('fixturestore');
if ($store->getId()) {
$store->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,563 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Helper\Data;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
use Magento\Store\Test\Fixture\Group as StoreGroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
use Magento\Catalog\Model\Product;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Framework\ObjectManagerInterface;
/**
* Test for \Magento\Catalog\Api\ProductRepositoryInterface
*
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class ProductRepositoryMultiWebsiteTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogProductRepositoryV1';
private const SERVICE_VERSION = 'V1';
private const RESOURCE_PATH = '/V1/products';
/**
* @var array
*/
private $fixtureProducts = [];
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->fixtures = $this->objectManager->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$this->deleteFixtureProducts();
}
/**
* Save Product
*
* @param array $product
* @param string|null $storeCode
* @param string|null $token
* @return mixed
*/
private function saveProduct(array $product, ?string $storeCode = null, ?string $token = null)
{
if (isset($product['custom_attributes'])) {
foreach ($product['custom_attributes'] as &$attribute) {
if ($attribute['attribute_code'] == 'category_ids'
&& !is_array($attribute['value'])
) {
$attribute['value'] = [""];
}
}
}
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
if ($token) {
$serviceInfo['rest']['token'] = $serviceInfo['soap']['token'] = $token;
}
$requestData = ['product' => $product];
return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
}
/**
* Delete Product
*
* @param string $sku
* @return boolean
*/
private function deleteProduct(string $sku) : bool
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $sku,
'httpMethod' => Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'DeleteById',
],
];
return (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) ?
$this->_webApiCall($serviceInfo, ['sku' => $sku]) : $this->_webApiCall($serviceInfo);
}
/**
* @return void
*/
private function deleteFixtureProducts(): void
{
foreach ($this->fixtureProducts as $sku) {
$this->deleteProduct($sku);
}
$this->fixtureProducts = [];
}
/**
* Test that updating some values for product for specified store won't uncheck 'use default values'
* for attributes which weren't changed
*
* @magentoApiDataFixture Magento/Store/_files/second_website_with_two_stores.php
*/
public function testProductDefaultValuesWithTwoWebsites(): void
{
$productData = [
ProductInterface::SKU => 'test-1',
ProductInterface::NAME => 'Test 1',
ProductInterface::ATTRIBUTE_SET_ID => 4,
ProductInterface::PRICE => 10,
ProductInterface::STATUS => 1,
ProductInterface::VISIBILITY => 4,
ProductInterface::TYPE_ID => 'simple',
ProductInterface::WEIGHT => 100,
];
$response = $this->saveProduct($productData, 'all');
$this->assertEquals($response[ProductInterface::SKU], $productData[ProductInterface::SKU]);
$this->fixtureProducts[] = $productData[ProductInterface::SKU];
$productEditData = [
ProductInterface::SKU => 'test-1',
ProductInterface::NAME => 'Test 1 changed',
];
$responseAfterEdit = $this->saveProduct($productEditData, 'fixture_third_store');
$this->assertEquals($productEditData[ProductInterface::NAME], $responseAfterEdit[ProductInterface::NAME]);
$store = $this->objectManager->get(Store::class);
/** @var Product $model */
$model = $this->objectManager->get(Product::class);
$product = $model->load($model->getIdBySku($responseAfterEdit[ProductInterface::SKU]));
/** @var ScopeOverriddenValue $scopeOverriddenValue */
$scopeOverriddenValue = $this->objectManager->get(ScopeOverriddenValue::class);
$storeId = $store->load('fixture_third_store', 'code')->getId();
$attributeCodeList = ['visibility', 'tax_class_id', 'status', 'short_description', 'description',
'url_key', 'meta_title', 'meta_keywords', 'meta_description'];
foreach ($attributeCodeList as $attributeCode) {
$this->assertFalse($scopeOverriddenValue->containsValue(
ProductInterface::class,
$product,
$attributeCode,
$storeId
));
}
}
/**
* @magentoApiDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoApiDataFixture Magento/Catalog/_files/product_text_attribute.php
* @magentoApiDataFixture Magento/Catalog/_files/product_varchar_attribute.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testPartialUpdate(): void
{
$this->_markTestAsRestOnly(
'Test skipped due to known issue with SOAP. NULL value is cast to corresponding attribute type.'
);
$sku = 'api_test_update_product';
$store = $this->objectManager->get(Store::class);
$storeId = (int) $store->load('fixture_third_store', 'code')->getId();
$this->updateAttribute('varchar_attribute', ['is_global' => ScopedAttributeInterface::SCOPE_STORE]);
$this->updateAttribute('text_attribute', ['is_global' => ScopedAttributeInterface::SCOPE_STORE]);
$request1 = [
ProductInterface::SKU => $sku,
ProductInterface::NAME => 'Test 1',
ProductInterface::ATTRIBUTE_SET_ID => 4,
ProductInterface::PRICE => 10,
ProductInterface::STATUS => 1,
ProductInterface::VISIBILITY => 4,
ProductInterface::TYPE_ID => 'simple',
ProductInterface::WEIGHT => 100,
ProductInterface::CUSTOM_ATTRIBUTES => [
[
'attribute_code' => 'varchar_attribute',
'value' => 'api_test_value_varchar',
],
[
'attribute_code' => 'text_attribute',
'value' => 'api_test_value_text',
]
],
];
$response = $this->saveProduct($request1, 'all');
$this->assertResponse($request1, $response);
$this->fixtureProducts[] = $sku;
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get($sku);
$request2 = [
ProductInterface::SKU => $sku,
ProductInterface::CUSTOM_ATTRIBUTES => [
[
'attribute_code' => 'varchar_attribute',
'value' => 'api_test_value_varchar_changed',
]
],
];
$response2 = $this->saveProduct($request2, 'fixture_third_store');
$expected = [
'varchar_attribute' => 'api_test_value_varchar_changed',
'text_attribute' => 'api_test_value_text'
];
$this->assertResponse(
array_merge($request1, $expected),
$response2
);
$this->assertOverriddenValues(
[
'visibility' => false,
'tax_class_id' => false,
'status' => false,
'name' => false,
'varchar_attribute' => true,
'text_attribute' => false,
],
$product,
$storeId
);
$request3 = [
ProductInterface::SKU => $sku,
ProductInterface::CUSTOM_ATTRIBUTES => [
[
'attribute_code' => 'text_attribute',
'value' => 'api_test_value_text_changed',
]
],
];
$response3 = $this->saveProduct($request3, 'fixture_third_store');
$expected = [
'varchar_attribute' => 'api_test_value_varchar_changed',
'text_attribute' => 'api_test_value_text_changed'
];
$this->assertResponse(
array_merge($request1, $expected),
$response3
);
$this->assertOverriddenValues(
[
'visibility' => false,
'tax_class_id' => false,
'status' => false,
'name' => false,
'varchar_attribute' => true,
'text_attribute' => true,
],
$product,
$storeId
);
$request4 = [
ProductInterface::SKU => $sku,
ProductInterface::CUSTOM_ATTRIBUTES => [
[
'attribute_code' => 'text_attribute',
'value' => null,
]
],
];
$response4 = $this->saveProduct($request4, 'fixture_third_store');
$expected = [
'varchar_attribute' => 'api_test_value_varchar_changed',
'text_attribute' => 'api_test_value_text'
];
$this->assertResponse(
array_merge($request1, $expected),
$response4
);
$this->assertOverriddenValues(
[
'visibility' => false,
'tax_class_id' => false,
'status' => false,
'name' => false,
'varchar_attribute' => true,
'text_attribute' => false,
],
$product,
$storeId
);
}
#[
Config(Data::XML_PATH_PRICE_SCOPE, Data::PRICE_SCOPE_WEBSITE),
DataFixture(WebsiteFixture::class, as: 'website2'),
DataFixture(StoreGroupFixture::class, ['website_id' => '$website2.id$'], 'store_group2'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group2.id$'], 'store2'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group2.id$'], 'store3'),
DataFixture(ProductFixture::class, ['website_ids' => [1, '$website2.id$' ]], as: 'product'),
]
public function testUpdatePrice(): void
{
$store = $this->objectManager->get(Store::class);
$defaultWebsiteStore1 = $store->load('default', 'code')->getCode();
$secondWebsiteStore1 = $this->fixtures->get('store2')->getCode();
$secondWebsiteStore2 = $this->fixtures->get('store3')->getCode();
$sku = $this->fixtures->get('product')->getSku();
// change any attribute value in second store
$request = [
ProductInterface::SKU => $sku,
'name' => 'updated product name for storeview'
];
$this->saveProduct($request, $secondWebsiteStore1);
// now update prices in second website
$request = [
ProductInterface::SKU => $sku,
'price' => 9,
ProductInterface::CUSTOM_ATTRIBUTES => [
[
'attribute_code' => 'special_price',
'value' => 8,
]
],
];
$this->saveProduct($request, $secondWebsiteStore1);
$defaultWebsiteStore1Response = $this->flattenCustomAttributes($this->getProduct($sku, $defaultWebsiteStore1));
$this->assertEquals(10, $defaultWebsiteStore1Response['price']);
$this->assertArrayNotHasKey('special_price', $defaultWebsiteStore1Response);
$secondWebsiteStore1Response = $this->flattenCustomAttributes($this->getProduct($sku, $secondWebsiteStore1));
$this->assertEquals(9, $secondWebsiteStore1Response['price']);
$this->assertEquals(8, $secondWebsiteStore1Response['special_price']);
$secondWebsiteStore2Response = $this->flattenCustomAttributes($this->getProduct($sku, $secondWebsiteStore2));
$this->assertEquals(9, $secondWebsiteStore2Response['price']);
$this->assertEquals(8, $secondWebsiteStore2Response['special_price']);
}
/**
* @magentoApiDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testPartialUpdateShouldNotOverrideImagesRolesInheritance(): void
{
$sku = 'simple';
$name = 'Product Simple edited';
$store = $this->objectManager->get(Store::class);
$storeId = (int) $store->load('fixture_third_store', 'code')->getId();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get($sku);
$request = [
ProductInterface::SKU => $sku,
ProductInterface::NAME => $name,
];
$response = $this->saveProduct($request, 'fixture_third_store');
$this->assertEquals($name, $response['name']);
$this->assertOverriddenValues(
[
'name' => true,
'image' => false,
'small_image' => false,
'thumbnail' => false,
],
$product,
$storeId
);
}
#[
DataFixture(ProductFixture::class, as: 'product1'),
DataFixture(ProductFixture::class, as: 'product2'),
]
public function testPartialUpdateShouldNotOverrideUrlKeyInheritance(): void
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$store = $this->objectManager->get(Store::class);
$defaultStore = $store->load('default', 'code');
$sku2 = $this->fixtures->get('product2')->getSku();
$sku1Name = $this->fixtures->get('product1')->getName();
$sku2NewName = $this->fixtures->get('product2')->getName() . ' storeview';
$sku2UrlKey = $this->fixtures->get('product2')->getUrlKey();
// Change the second product name with the first product name in default store view
$this->saveProduct(
[
ProductInterface::SKU => $sku2,
'name' => $sku1Name
],
$defaultStore->getCode()
);
$response = $this->flattenCustomAttributes($this->getProduct($sku2, $defaultStore->getCode()));
$this->assertEquals($sku1Name, $response['name']);
// Assert that Url Key has not changed
$this->assertEquals($sku2UrlKey, $response['url_key']);
$product = $productRepository->get($sku2, false, $defaultStore->getId(), true);
$this->assertOverriddenValues(
[
'name' => true,
'url_key' => false,
],
$product,
(int) $defaultStore->getId()
);
// Change the second product name with a new name in default store view
$this->saveProduct(
[
ProductInterface::SKU => $sku2,
'name' => $sku2NewName
],
$defaultStore->getCode()
);
$response = $this->flattenCustomAttributes($this->getProduct($sku2, $defaultStore->getCode()));
$this->assertEquals($sku2NewName, $response['name']);
// Assert that Url Key has not changed
$this->assertEquals($sku2UrlKey, $response['url_key']);
$product = $productRepository->get($sku2, false, $defaultStore->getId(), true);
$this->assertOverriddenValues(
[
'name' => true,
'url_key' => false,
],
$product,
(int) $defaultStore->getId()
);
}
/**
* @param array $expected
* @param array $actual
*/
private function assertResponse(array $expected, array $actual): void
{
$customAttributes = $expected[ProductInterface::CUSTOM_ATTRIBUTES] ?? [];
unset($expected[ProductInterface::CUSTOM_ATTRIBUTES]);
$expected = array_merge(array_column($customAttributes, 'value', 'attribute_code'), $expected);
$customAttributes = $actual[ProductInterface::CUSTOM_ATTRIBUTES] ?? [];
unset($actual[ProductInterface::CUSTOM_ATTRIBUTES]);
$actual = array_merge(array_column($customAttributes, 'value', 'attribute_code'), $actual);
$this->assertEquals($expected, array_intersect_key($actual, $expected));
}
/**
* @param Product $product
* @param array $expected
* @param int $storeId
*/
private function assertOverriddenValues(array $expected, Product $product, int $storeId): void
{
/** @var ScopeOverriddenValue $scopeOverriddenValue */
$scopeOverriddenValue = $this->objectManager->create(ScopeOverriddenValue::class);
$actual = [];
foreach (array_keys($expected) as $attribute) {
$actual[$attribute] = $scopeOverriddenValue->containsValue(
ProductInterface::class,
$product,
$attribute,
$storeId
);
}
$this->assertEquals($expected, $actual);
}
/**
* Update attribute
*
* @param string $code
* @param array $data
* @return void
*/
private function updateAttribute(string $code, array $data): void
{
$attributeRepository = $this->objectManager->create(ProductAttributeRepositoryInterface::class);
$attribute = $attributeRepository->get($code);
$attribute->addData($data);
$attributeRepository->save($attribute);
}
/**
* @param array $data
* @return array
*/
private function flattenCustomAttributes(array $data): array
{
$customAttributes = $data[ProductInterface::CUSTOM_ATTRIBUTES] ?? [];
unset($data[ProductInterface::CUSTOM_ATTRIBUTES]);
return array_merge(array_column($customAttributes, 'value', 'attribute_code'), $data);
}
/**
* Get product
*
* @param string $sku
* @param string|null $storeCode
* @return array|bool|float|int|string
*/
private function getProduct($sku, $storeCode = null)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $sku,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
return $this->_webApiCall($serviceInfo, ['sku' => $sku], null, $storeCode);
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Store\Model\Store;
class ProductRepositoryPriceModeWebsiteChangePriceTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogProductRepositoryV1';
private const PRICE_SERVICE_NAME = 'catalogBasePriceStorageV1';
private const SERVICE_VERSION = 'V1';
private const PRODUCTS_RESOURCE_PATH = '/V1/products';
private const PRICES_RESOURCE_PATH = '/V1/products/base-prices';
private const STORE1_CODE_FROM_FIXTURE = 'fixturestore';
private const STORE2_CODE_FROM_FIXTURE = 'fixture_second_store';
/**
* @magentoApiDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoApiDataFixture Magento/Store/_files/second_store.php
* @magentoApiDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoConfigFixture admin_store catalog/price/scope 1
*/
public function testChangePriceForStore()
{
/** @var $store1 \Magento\Store\Model\Group */
$store1 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(Store::class);
$store1->load(self::STORE1_CODE_FROM_FIXTURE);
/** @var $store2 \Magento\Store\Model\Group */
$store2 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(Store::class);
$store2->load(self::STORE2_CODE_FROM_FIXTURE);
$sku = 'simple';
$requestData1 = [
'prices' => [
[
'price' => 20,
'store_id' => $store1->getId(),
'sku' => $sku
]
]
];
$requestData2 = [
'prices' => [
[
'price' => 30,
'store_id' => $store2->getId(),
'sku' => $sku
]
]
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::PRICES_RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::PRICE_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::PRICE_SERVICE_NAME . 'Update',
]
];
$this->_webApiCall($serviceInfo, $requestData1);
$this->_webApiCall($serviceInfo, $requestData2);
/** @var \Magento\Catalog\Model\ProductRepository $productRepository */
$productRepository = Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\ProductRepository::class);
$product = $productRepository->get($sku, false, $store1->getId());
$this->assertEquals(
$product->getPrice(),
30,
'Product prices for Website Price mode is invalid.'
);
}
}
@@ -0,0 +1,108 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Api\Data\AttributeOptionLabelInterface;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductSwatchAttributeOptionManagementInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeOptionManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attributes';
/**
* @magentoApiDataFixture Magento/Swatches/_files/swatch_attribute.php
* @dataProvider addDataProvider
*/
public function testAdd($optionData)
{
$testAttributeCode = 'color_swatch';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $testAttributeCode . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'add',
],
];
$response = $this->_webApiCall(
$serviceInfo,
[
'attributeCode' => $testAttributeCode,
'option' => $optionData,
]
);
$this->assertNotNull($response);
$updatedData = $this->getAttributeOptions($testAttributeCode);
$lastOption = array_pop($updatedData);
foreach ($updatedData as $option) {
$this->assertStringNotContainsString('id', $option['value']);
}
$this->assertEquals(
$optionData[AttributeOptionInterface::STORE_LABELS][0][AttributeOptionLabelInterface::LABEL],
$lastOption['label']
);
}
/**
* @return array
*/
public function addDataProvider()
{
$optionPayload = [
AttributeOptionInterface::LABEL => 'new color',
AttributeOptionInterface::SORT_ORDER => 100,
AttributeOptionInterface::IS_DEFAULT => true,
AttributeOptionInterface::STORE_LABELS => [
[
AttributeOptionLabelInterface::LABEL => 'DE label',
AttributeOptionLabelInterface::STORE_ID => 1,
],
],
AttributeOptionInterface::VALUE => ''
];
return [
'option_without_value_node' => [
$optionPayload
],
'option_with_value_node_that_starts_with_text' => [
array_merge($optionPayload, [AttributeOptionInterface::VALUE => 'some_text'])
],
'option_with_value_node_that_starts_with_a_number' => [
array_merge($optionPayload, [AttributeOptionInterface::VALUE => '123_some_text'])
],
];
}
/**
* @param $testAttributeCode
* @return array|bool|float|int|string
*/
private function getAttributeOptions($testAttributeCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $testAttributeCode . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'getItems',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $testAttributeCode]);
}
}
@@ -0,0 +1,208 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* ProductTierPriceManagementTest API operations test
*/
class ProductTierPriceManagementTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogProductTierPriceManagementV1';
private const SERVICE_VERSION = 'V1';
private const RESOURCE_PATH = '/V1/products/';
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @dataProvider getListDataProvider
*/
public function testGetList($customerGroupId, $count, $value, $qty)
{
$productSku = 'simple';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . $productSku . '/group-prices/' . $customerGroupId . '/tiers',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$tierPriceList = $this->_webApiCall(
$serviceInfo,
['sku' => $productSku, 'customerGroupId' => $customerGroupId]
);
$this->assertCount($count, $tierPriceList);
if ($count) {
$this->assertEquals($value, $tierPriceList[0]['value']);
$this->assertEquals($qty, $tierPriceList[0]['qty']);
}
}
public function getListDataProvider()
{
return [
[0, 3, 5, 3],
[1, 0, null, null],
['all', 2, 8, 2],
];
}
/**
* @param string|int $customerGroupId
* @param int $qty
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @dataProvider deleteDataProvider
*/
public function testDelete($customerGroupId, $qty)
{
$productSku = 'simple';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH
. $productSku . "/group-prices/" . $customerGroupId . "/tiers/" . $qty,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Remove',
],
];
$requestData = ['sku' => $productSku, 'customerGroupId' => $customerGroupId, 'qty' => $qty];
$this->assertTrue($this->_webApiCall($serviceInfo, $requestData, null, "all"));
}
public function deleteDataProvider()
{
return [
'delete_tier_price_for_specific_customer_group' => [0, 3],
'delete_tier_price_for_all_customer_group' => ['all', 5]
];
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoAppIsolation enabled
*/
public function testAdd()
{
$productSku = 'simple';
$customerGroupId = 1;
$qty = 50;
$price = 10;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $productSku
. '/group-prices/' . $customerGroupId . '/tiers/' . $qty . '/price/' . $price,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Add',
],
];
$requestData = [
'sku' => $productSku,
'customerGroupId' => $customerGroupId,
'qty' => $qty,
'price' => $price,
];
$this->_webApiCall($serviceInfo, $requestData);
$objectManager = \Magento\TestFramework\ObjectManager::getInstance();
/** @var \Magento\Catalog\Api\ProductTierPriceManagementInterface $service */
$service = $objectManager->get(\Magento\Catalog\Api\ProductTierPriceManagementInterface::class);
$prices = $service->getList($productSku, 1);
$this->assertCount(1, $prices);
$this->assertEquals(10, $prices[0]->getValue());
$this->assertEquals(50, $prices[0]->getQty());
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoAppIsolation enabled
*/
public function testAddWithAllCustomerGrouped()
{
$productSku = 'simple';
$customerGroupId = 'all';
$qty = 50;
$price = 20;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $productSku
. '/group-prices/' . $customerGroupId . '/tiers/' . $qty . '/price/' . $price,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Add',
],
];
$requestData = [
'sku' => $productSku,
'customerGroupId' => $customerGroupId,
'qty' => $qty,
'price' => $price,
];
$this->_webApiCall($serviceInfo, $requestData);
$objectManager = \Magento\TestFramework\ObjectManager::getInstance();
/** @var \Magento\Catalog\Api\ProductTierPriceManagementInterface $service */
$service = $objectManager->get(\Magento\Catalog\Api\ProductTierPriceManagementInterface::class);
$prices = $service->getList($productSku, 'all');
$this->assertCount(3, $prices);
$this->assertEquals(20, (int)$prices[2]->getValue());
$this->assertEquals(50, (int)$prices[2]->getQty());
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoAppIsolation enabled
*/
public function testUpdateWithAllGroups()
{
$productSku = 'simple';
$customerGroupId = 'all';
$qty = 2;
$price = 20;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $productSku
. '/group-prices/' . $customerGroupId . '/tiers/' . $qty . '/price/' . $price,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Add',
],
];
$requestData = [
'sku' => $productSku,
'customerGroupId' => $customerGroupId,
'qty' => $qty,
'price' => $price,
];
$this->_webApiCall($serviceInfo, $requestData, null, "all");
$objectManager = \Magento\TestFramework\ObjectManager::getInstance();
/** @var \Magento\Catalog\Api\ProductTierPriceManagementInterface $service */
$service = $objectManager->get(\Magento\Catalog\Api\ProductTierPriceManagementInterface::class);
$prices = $service->getList($productSku, 'all');
$this->assertCount(2, $prices);
$this->assertEquals(20, (int)$prices[0]->getValue());
$this->assertEquals(2, (int)$prices[0]->getQty());
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
class ProductTypeListTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductTypeListV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/';
public function testGetProductTypes()
{
$expectedProductTypes = [
[
'name' => 'simple',
'label' => 'Simple Product',
],
[
'name' => 'virtual',
'label' => 'Virtual Product',
],
[
'name' => 'downloadable',
'label' => 'Downloadable Product',
],
[
'name' => 'bundle',
'label' => 'Bundle Product',
],
[
'name' => 'configurable',
'label' => 'Configurable Product',
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/types',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetProductTypes',
],
];
$productTypes = $this->_webApiCall($serviceInfo);
foreach ($expectedProductTypes as $expectedProductType) {
$this->assertContains($expectedProductType, $productTypes);
}
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Api;
use Magento\Catalog\Model\ProductWebsiteLink;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Tests to check products to websites assigning.
*
* @see \Magento\Catalog\Model\ProductWebsiteLinkRepository
*
* @magentoAppIsolation enabled
*/
class ProductWebsiteLinkRepositoryTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductWebsiteLinkRepositoryV1';
const SERVICE_VERSION = 'V1';
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var WebsiteRepositoryInterface */
private $websiteRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->websiteRepository = $this->objectManager->get(WebsiteRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @return void
*/
public function testSaveWebsiteLinkWithUnexistingWebsiteId(): void
{
$pattern = '/(Could\\snot\\sassign\\sproduct)+([\\s\\S]*)(to\\swebsites)+([\\s\\S]*)/';
$unexistingWebsiteId = 8932568989;
$serviceInfo = $this->fillServiceInfo('/V1/products/:sku/websites', Request::HTTP_METHOD_POST, 'Save');
$requestData = [
'productWebsiteLink' => [
ProductWebsiteLink::KEY_SKU => 'simple2',
ProductWebsiteLink::WEBSITE_ID => $unexistingWebsiteId,
],
];
$this->expectException(\Exception::class);
$this->expectExceptionMessageMatches($pattern);
$this->_webApiCall($serviceInfo, $requestData);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_with_two_websites.php
*
* @return void
*/
public function testDeleteWebsiteLink(): void
{
$productSku = 'unique-simple-azaza';
$websiteId = (int)$this->websiteRepository->get('second_website')->getId();
$resourcePath = sprintf('/V1/products/%s/websites/%u', $productSku, $websiteId);
$serviceInfo = $this->fillServiceInfo($resourcePath, Request::HTTP_METHOD_DELETE, 'DeleteById');
$this->_webApiCall(
$serviceInfo,
[ProductWebsiteLink::KEY_SKU => $productSku, ProductWebsiteLink::WEBSITE_ID => $websiteId]
);
$product = $this->productRepository->get($productSku, false, null, true);
$this->assertNotContains($websiteId, $product->getWebsiteIds());
}
/**
* Fill service information
*
* @param string $resourcePath
* @param string $httpMethod
* @param string $operation
* @return array
*/
private function fillServiceInfo(string $resourcePath, string $httpMethod, string $operation): array
{
return [
'rest' => ['resourcePath' => $resourcePath, 'httpMethod' => $httpMethod],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . $operation,
],
];
}
}
@@ -0,0 +1,359 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* SpecialPriceStorage API operations test
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SpecialPriceStorageTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogSpecialPriceStorageV1';
private const SERVICE_VERSION = 'V1';
private const SIMPLE_PRODUCT_SKU = 'simple';
private const VIRTUAL_PRODUCT_SKU = 'virtual-product';
private const PRODUCT_SKU_TWO_WEBSITES = 'simple-on-two-websites';
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @ingeritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* Test get method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGet()
{
$specialPrice = 3057;
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU, true);
$product->setData('special_price', $specialPrice);
$productRepository->save($product);
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price-information',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
/** @var ProductInterface $product */
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU);
$this->assertNotEmpty($response);
$this->assertEquals($product->getSpecialPrice(), $response[0]['price']);
}
/**
* Test get method when special price is 0.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGetZeroValue()
{
$specialPrice = 0;
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get(self::SIMPLE_PRODUCT_SKU, true);
$product->setData('special_price', $specialPrice);
$productRepository->save($product);
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price-information',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
$this->assertNotEmpty($response);
$this->assertEquals($specialPrice, $response[0]['price']);
}
/**
* Test update method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_virtual.php
* @dataProvider updateData
* @param array $data
*/
public function testUpdate(array $data)
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
$data
]
]
);
$this->assertEmpty($response);
}
/**
* Delete special price for specified store when price scope is global
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoConfigFixture default_store catalog/price/scope 0
* @return void
*/
public function testDeleteWhenPriceIsGlobal(): void
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price-delete',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Delete',
],
];
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
[
'price' => 777,
'store_id' => 1,
'sku' => self::SIMPLE_PRODUCT_SKU,
'price_from' => '2037-01-19 03:14:07',
'price_to' => '2038-01-19 03:14:07'
]
]
]
);
$errorMessage = current(array_column($response, 'message'));
$this->assertStringContainsString(
'Could not change non global Price when price scope is global.',
$errorMessage
);
}
/**
* Test delete method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @dataProvider deleteData
* @param array $data
* @throws CouldNotSaveException
* @throws InputException
* @throws NoSuchEntityException
* @throws StateException
*/
public function testDelete(array $data)
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get($data['sku'], true);
$product->setData('special_price', $data['price']);
$product->setData('special_from_date', $data['price_from']);
if ($data['price_to']) {
$product->setData('special_to_date', $data['price_to']);
}
$productRepository->save($product);
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price-delete',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Delete',
],
];
$response = $this->_webApiCall(
$serviceInfo,
[
'prices' => [
$data
]
]
);
$product = $productRepository->get($data['sku'], false, null, true);
$this->assertEmpty($response);
$this->assertNull($product->getSpecialPrice());
}
/**
* Data provider for testUpdate
*
* @return array
*/
public function updateData(): array
{
$fromDate = '2037-01-19 03:14:07';
$toDate = '2038-01-19 03:14:07';
return [
[
// data set with 'price_to' specified
[
'price' => 31337,
'store_id' => 0,
'sku' => self::VIRTUAL_PRODUCT_SKU,
'price_from' => $fromDate,
'price_to' => $toDate
]
],
[
// data set without 'price_to' specified
[
'price' => 31337,
'store_id' => 0,
'sku' => self::VIRTUAL_PRODUCT_SKU,
'price_from' => $fromDate,
'price_to' => false
]
],
];
}
/**
* Data provider for testDelete
*
* @return array
*/
public function deleteData(): array
{
$fromDate = '1970-01-01 00:00:01';
$toDate = '2038-01-19 03:14:07';
return [
[
// data set with 'price_to' specified
[
'price' => 3057,
'store_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'price_from' => $fromDate,
'price_to' => $toDate
]
],
[
// data set without 'price_to' specified
[
'price' => 3057,
'store_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'price_from' => $fromDate,
'price_to' => false
]
],
];
}
/**
* Test delete method for specific store.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_two_websites.php
* @magentoConfigFixture default_store catalog/price/scope 1
* @return void
*/
public function testDeleteDataForSpecificStore(): void
{
$secondStoreViewId = $this->storeManager->getStore('fixture_second_store')
->getId();
$data = [
'price' => 777,
'store_id' => $secondStoreViewId,
'sku' => self::PRODUCT_SKU_TWO_WEBSITES,
'price_from' => '1970-01-01 00:00:01',
'price_to' => false
];
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get($data['sku'], true, 1, true);
$product->setData('special_price', $data['price']);
$product->setData('special_from_date', $data['price_from']);
$this->productResource->saveAttribute($product, 'special_price');
$this->productResource->saveAttribute($product, 'special_from_date');
$this->productResource->saveAttribute($product, 'special_to_date');
$product->setData('store_id', $secondStoreViewId);
$this->productResource->saveAttribute($product, 'special_price');
$this->productResource->saveAttribute($product, 'special_from_date');
$this->productResource->saveAttribute($product, 'special_to_date');
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/special-price-delete',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Delete',
],
];
$this->_webApiCall($serviceInfo, ['prices' => [$data]]);
$product = $productRepository->get($data['sku'], false, 1, true);
$this->assertNotNull($product->getSpecialPrice());
$product = $productRepository->get($data['sku'], false, $secondStoreViewId, true);
$this->assertNull($product->getSpecialPrice());
}
}
@@ -0,0 +1,327 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Api;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\Data\TierPriceInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Test all API calls for tier price storage.
*/
class TierPriceStorageTest extends WebapiAbstract
{
private const SERVICE_NAME = 'catalogTierPriceStorageV1';
private const SERVICE_VERSION = 'V1';
private const SIMPLE_PRODUCT_SKU = 'simple';
private const CUSTOMER_ALL_GROUPS_NAME ='ALL GROUPS';
private const CUSTOMER_GENERAL_GROUP_NAME ='General';
private const CUSTOMER_NOT_LOGGED_IN_GROUP_NAME ='NOT LOGGED IN';
private const WRONG_CUSTOMER_GROUP_NAME ='general';
/**
* @var \Magento\TestFramework\ObjectManager
*/
private $objectManager;
/**
* Set up.
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* Test get method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoConfigFixture default_store catalog/price/scope 0
*/
public function testGet()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices-information',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var ProductInterface $product */
$tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$this->assertNotEmpty($response);
$this->assertEquals(count($response), count($tierPrices));
foreach ($response as $item) {
$this->assertTrue($this->isPriceCorrect($item, $tierPrices));
}
}
/**
* Test update method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoConfigFixture default_store catalog/price/scope 0
*/
public function testUpdate()
{
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$prices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$tierPrice = array_shift($prices);
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$newPrice = [
'price' => 40,
'price_type' => TierPriceInterface::PRICE_TYPE_DISCOUNT,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::CUSTOMER_ALL_GROUPS_NAME,
'quantity' => 7778
];
$updatedPrice = [
'price' => 778,
'price_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::CUSTOMER_NOT_LOGGED_IN_GROUP_NAME,
'quantity' => $tierPrice->getQty()
];
$response = $this->_webApiCall($serviceInfo, ['prices' => [$updatedPrice, $newPrice]]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$this->assertEmpty($response);
$this->assertTrue($this->isPriceCorrect($newPrice, $tierPrices));
$this->assertTrue($this->isPriceCorrect($updatedPrice, $tierPrices));
}
/**
* Call update method with specifying new website value for tier price with all websites value.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testUpdateWebsiteForAllWebsites()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Update',
],
];
$invalidPrice = [
'price' => 40,
'price_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'website_id' => 2,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => 'not logged in',
'quantity' => 3
];
$response = $this->_webApiCall($serviceInfo, ['prices' => [$invalidPrice]]);
$this->assertNotEmpty($response);
$message = 'Invalid attribute Website ID = %websiteId. '
. 'Row ID: SKU = %SKU, Website ID: %websiteId, '
. 'Customer Group: %customerGroup, Quantity: %qty.';
$this->assertEquals($message, $response[0]['message']);
$this->assertEquals('simple', $response[0]['parameters'][0]);
$this->assertEquals('2', $response[0]['parameters'][1]);
if (array_key_exists(1, $response)) {
$message = 'We found a duplicate website, tier price, customer group and quantity: '
. 'Customer Group = %customerGroup, Website ID = %websiteId, Quantity = %qty. '
. 'Row ID: SKU = %SKU, Website ID: %websiteId, Customer Group: %customerGroup, Quantity: %qty.';
$this->assertEquals($message, $response[1]['message']);
$this->assertEquals('simple', $response[1]['parameters'][0]);
$this->assertEquals('0', $response[1]['parameters'][1]);
$this->assertEquals('NOT LOGGED IN', $response[1]['parameters'][2]);
$this->assertEquals('3.0000', $response[1]['parameters'][3]);
}
}
/**
* Test replace method without error message.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testReplaceWithoutErrorMessage()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices',
'httpMethod' => Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Replace',
],
];
$newPrices = [
[
'price' => 50,
'price_type' => TierPriceInterface::PRICE_TYPE_DISCOUNT,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::CUSTOMER_GENERAL_GROUP_NAME,
'quantity' => 7778
],
[
'price' => 70,
'price_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::CUSTOMER_NOT_LOGGED_IN_GROUP_NAME,
'quantity' => 33
]
];
$response = $this->_webApiCall($serviceInfo, ['prices' => $newPrices]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var ProductInterface $product */
$tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$this->assertEmpty($response);
$this->assertEquals(count($newPrices), count($tierPrices));
}
/**
* Test replace method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testReplaceWithErrorMessage()
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices',
'httpMethod' => Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Replace',
],
];
$newPrices = [
[
'price' => 10.31,
'price_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::WRONG_CUSTOMER_GROUP_NAME,
'quantity' => 2
],
[
'price' => 20.62,
'price_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'website_id' => 0,
'sku' => self::SIMPLE_PRODUCT_SKU,
'customer_group' => self::WRONG_CUSTOMER_GROUP_NAME,
'quantity' => 2
]
];
$response = $this->_webApiCall($serviceInfo, ['prices' => $newPrices]);
$this->assertNotEmpty($response);
$message = 'We found a duplicate website, tier price, customer group and quantity: '
. 'Customer Group = %customerGroup, Website ID = %websiteId, Quantity = %qty. '
. 'Row ID: SKU = %SKU, Website ID: %websiteId, Customer Group: %customerGroup, Quantity: %qty.';
$this->assertEquals($message, $response[0]['message']);
$this->assertEquals('simple', $response[0]['parameters'][0]);
$this->assertEquals('0', $response[0]['parameters'][1]);
$this->assertEquals('general', $response[0]['parameters'][2]);
$this->assertEquals('2', $response[0]['parameters'][3]);
}
/**
* Test delete method.
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testDelete()
{
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$pricesToStore = array_pop($tierPrices);
$pricesToDelete = [];
foreach ($tierPrices as $tierPrice) {
$tierPriceValue = $tierPrice->getExtensionAttributes()->getPercentageValue()
?: $tierPrice->getValue();
$priceType = $tierPrice->getExtensionAttributes()->getPercentageValue()
? TierPriceInterface::PRICE_TYPE_DISCOUNT
: TierPriceInterface::PRICE_TYPE_FIXED;
$customerGroup = $tierPrice->getCustomerGroupId() == \Magento\Customer\Model\Group::NOT_LOGGED_IN_ID
? self::CUSTOMER_NOT_LOGGED_IN_GROUP_NAME
: self::CUSTOMER_ALL_GROUPS_NAME;
$pricesToDelete[] = [
'price' => $tierPriceValue,
'price_type' => $priceType,
'website_id' => 0,
'customer_group' => $customerGroup,
'sku' => self::SIMPLE_PRODUCT_SKU,
'quantity' => $tierPrice->getQty()
];
}
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/tier-prices-delete',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Delete',
],
];
$response = $this->_webApiCall($serviceInfo, ['prices' => $pricesToDelete]);
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices();
$tierPrice = $tierPrices[0];
$this->assertEmpty($response);
$this->assertCount(1, $tierPrices);
$this->assertEquals($pricesToStore, $tierPrice);
}
/**
* Check prise exists and is correct.
*
* @param array $price
* @param array $tierPrices
* @return bool
*/
private function isPriceCorrect(array $price, array $tierPrices)
{
$isCorrect = false;
foreach ($tierPrices as $tierPrice) {
$priceIsCorrect = $price['price_type'] === TierPriceInterface::PRICE_TYPE_DISCOUNT
? (float)$tierPrice->getExtensionAttributes()->getPercentageValue() === (float)$price['price']
: (float)$tierPrice->getValue() === (float)$price['price'];
if ($priceIsCorrect
&& (int)$tierPrice->getQty() === (int)$price['quantity']
&& $tierPrice->getExtensionAttributes()->getWebsiteId() == $price['website_id']
) {
$isCorrect = true;
break;
}
}
return $isCorrect;
}
}
@@ -0,0 +1,156 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
[
'title' => 'test_option_code_1',
'type' => 'field',
'sort_order' => 1,
'is_require' => 1,
'price' => -10,
'price_type' => 'fixed',
'sku' => 'sku1',
'max_characters' => 10,
],
[
'title' => 'area option',
'type' => 'area',
'sort_order' => 2,
'is_require' => 0,
'price' => 20,
'price_type' => 'percent',
'sku' => 'sku2',
'max_characters' => 20,
],
[
'title' => 'file option',
'type' => 'file',
'sort_order' => 3,
'is_require' => 1,
'price' => 30,
'price_type' => 'percent',
'sku' => 'sku3',
'file_extension' => 'jpg, png, gif',
'image_size_x' => 10,
'image_size_y' => 20,
],
[
'title' => 'drop_down option',
'type' => 'drop_down',
'sort_order' => 4,
'is_require' => 1,
'values' => [
[
'title' => 'drop_down option 1',
'sort_order' => 1,
'price' => 10,
'price_type' => 'fixed',
'sku' => 'drop_down option 1 sku',
],
[
'title' => 'drop_down option 2',
'sort_order' => 2,
'price' => 20,
'price_type' => 'fixed',
'sku' => 'drop_down option 2 sku'
],
],
],
[
'title' => 'radio option',
'type' => 'radio',
'sort_order' => 5,
'is_require' => 1,
'values' => [
[
'title' => 'radio option 1',
'sort_order' => 1,
'price' => 10,
'price_type' => 'fixed',
'sku' => 'radio option 1 sku',
],
[
'title' => 'radio option 2',
'sort_order' => 2,
'price' => 20,
'price_type' => 'fixed',
'sku' => 'radio option 2 sku',
],
],
],
[
'title' => 'checkbox option',
'type' => 'checkbox',
'sort_order' => 6,
'is_require' => 1,
'values' => [
[
'title' => 'checkbox option 1',
'sort_order' => 1,
'price' => 10,
'price_type' => 'fixed',
'sku' => 'checkbox option 1 sku',
],
[
'title' => 'checkbox option 2',
'sort_order' => 2,
'price' => 20,
'price_type' => 'fixed',
'sku' => 'checkbox option 2 sku'
],
],
],
[
'title' => 'multiple option',
'type' => 'multiple',
'sort_order' => 7,
'is_require' => 1,
'values' => [
[
'title' => 'multiple option 1',
'sort_order' => 1,
'price' => 10,
'price_type' => 'fixed',
'sku' => 'multiple option 1 sku',
],
[
'title' => 'multiple option 2',
'sort_order' => 2,
'price' => 20,
'price_type' => 'fixed',
'sku' => 'multiple option 2 sku'
],
],
],
[
'title' => 'date option',
'type' => 'date',
'is_require' => 1,
'sort_order' => 8,
'price' => 80.0,
'price_type' => 'fixed',
'sku' => 'date option sku',
],
[
'title' => 'date_time option',
'type' => 'date_time',
'is_require' => 1,
'sort_order' => 9,
'price' => 90.0,
'price_type' => 'fixed',
'sku' => 'date_time option sku',
],
[
'title' => 'time option',
'type' => 'time',
'is_require' => 1,
'sort_order' => 10,
'price' => 100.0,
'price_type' => 'fixed',
'sku' => 'time option sku',
],
];
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
'empty_required_field' => [
'title' => null,
'type' => 'field',
'sort_order' => 1,
'is_require' => 1,
'price' => 10.0,
'price_type' => 'fixed',
'sku' => 'sku1',
'max_characters' => 10,
],
'negative_value_of_image_size' => [
'title' => 'file option',
'type' => 'file',
'sort_order' => 3,
'is_require' => 1,
'price' => 30,
'price_type' => 'percent',
'sku' => 'sku3',
'file_extension' => 'jpg',
'image_size_x' => -10,
'image_size_y' => -20,
],
'option_with_type_select_without_options' => [
'title' => 'drop_down option',
'type' => 'drop_down',
'sort_order' => 4,
'is_require' => 1,
],
'title_is_empty' => [
'title' => 'radio option',
'type' => 'radio',
'sort_order' => 5,
'is_require' => 1,
'values' => [
[
'price' => 10.0,
'price_type' => 'fixed',
'sku' => 'radio option 1 sku',
'title' => null,
'sort_order' => 1,
],
],
],
'option_with_non_existing_price_type' => [
'title' => 'checkbox option',
'type' => 'checkbox',
'sort_order' => 6,
'is_require' => 1,
'values' => [
[
'price' => 10.0,
'price_type' => 'fixed_one',
'sku' => 'checkbox option 1 sku',
'title' => 'checkbox option 1',
'sort_order' => 1,
],
],
],
'option_with_non_existing_option_type' => [
'title' => 'multiple option',
'type' => 'multiple_some_value',
'sort_order' => 7,
'is_require' => 1,
'values' => [
[
'price' => 10.0,
'price_type' => 'fixed',
'sku' => 'multiple option 1 sku',
'title' => 'multiple option 1',
'sort_order' => 1,
],
],
],
];
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
'missing_product_sku' => [
[
'title' => 'title',
'type' => 'field',
'sort_order' => 1,
'is_require' => 1,
'price' => 10.0,
'price_type' => 'fixed',
'max_characters' => 10,
],
'The ProductSku is empty. Set the ProductSku and try again.',
400,
],
'invalid_product_sku' => [
[
'title' => 'title',
'type' => 'field',
'sort_order' => 1,
'is_require' => 1,
'price' => 10.0,
'price_type' => 'fixed',
'product_sku' => 'sku1',
'max_characters' => 10,
],
'The product that was requested doesn\'t exist. Verify the product and try again.',
404,
],
];
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB