ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,363 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Api;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
class CartItemRepositoryTest extends WebapiAbstract
{
const SERVICE_NAME = 'quoteCartItemRepositoryV1';
const SERVICE_VERSION = 'V1';
const CONFIGURABLE_PRODUCT_SKU = 'configurable';
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
*/
public function testAddProduct()
{
/** @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->assertNotNull($response['item_id']);
$this->assertEquals(Configurable::TYPE_CODE, $response['product_type']);
$quote->load('test_order_1', 'reserved_order_id');
$items = $quote->getAllItems();
$this->assertGreaterThan(0, count($items));
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item|null $item */
$item = null;
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item $quoteItem */
foreach ($items as $quoteItem) {
if ($quoteItem->getProductType() == Configurable::TYPE_CODE && !$quoteItem->getParentItemId()) {
$item = $quoteItem;
break;
}
}
$this->assertNotNull($item);
}
/**
* @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
*/
public function testAddProductWithIncorrectOptions()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('You need to choose options for your item.');
/** @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',
],
];
$requestData = $this->getRequestData($cartId);
$requestData['cartItem']['product_option']['extension_attributes']
['configurable_item_options'][0]['option_id'] = 1000;
$requestData['cartItem']['product_option']['extension_attributes']
['configurable_item_options'][0]['option_value'] = 2000;
$this->_webApiCall($serviceInfo, $requestData);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testUpdateIncorrectItem()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The %1 Cart doesn\'t contain the %2 item.');
$qty = 1;
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_cart_with_configurable', 'reserved_order_id');
$cartId = $quote->getId();
$requestData = $this->getRequestData($cartId, 1);
$requestData['cartItem']['qty'] = $qty;
$requestData['cartItem']['item_id'] = 1000;
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/carts/' . $cartId . '/items/1000',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$this->_webApiCall($serviceInfo, $requestData);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testUpdate()
{
$qty = 4;
$this->updateStockForItem(10, 100);
$this->updateStockForItem(20, 100);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_cart_with_configurable', 'reserved_order_id');
$cartId = $quote->getId();
$items = $quote->getAllItems();
$this->assertGreaterThan(0, count($items));
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item|null $item */
$item = null;
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item $quoteItem */
foreach ($items as $quoteItem) {
if ($quoteItem->getProductType() == Configurable::TYPE_CODE) {
$item = $quoteItem;
break;
}
}
$this->assertNotNull($item);
$this->assertNotNull($item->getId());
$this->assertEquals(Configurable::TYPE_CODE, $item->getProductType());
$requestData = $this->getRequestData($cartId, 1);
$requestData['cartItem']['qty'] = $qty;
$requestData['cartItem']['item_id'] = $item->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/carts/' . $cartId . '/items/' . $item->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$response = $this->_webApiCall($serviceInfo, $requestData);
$this->assertNotNull($response['item_id']);
$this->assertEquals(Configurable::TYPE_CODE, $response['product_type']);
$this->assertEquals($cartId, $response['quote_id']);
$this->assertEquals($qty, $response['qty']);
$this->assertEquals(
$response['product_option']['extension_attributes']['configurable_item_options'][0],
$requestData['cartItem']['product_option']['extension_attributes']['configurable_item_options'][0]
);
}
/**
* @param int $itemId
* @param int $qty
*/
protected function updateStockForItem($itemId, $qty)
{
/** @var \Magento\CatalogInventory\Model\Stock\Status $stockStatus */
$stockStatus = $this->objectManager->create(\Magento\CatalogInventory\Model\Stock\Status::class);
$stockStatus->load($itemId, 'product_id');
if (!$stockStatus->getProductId()) {
$stockStatus->setProductId($itemId);
}
$stockStatus->setQty($qty);
$stockStatus->setStockStatus(1);
$stockStatus->save();
/** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
$stockItem = $this->objectManager->create(\Magento\CatalogInventory\Model\Stock\Item::class);
$stockItem->load($itemId, 'product_id');
if (!$stockItem->getProductId()) {
$stockItem->setProductId($itemId);
}
$stockItem->setUseConfigManageStock(1);
$stockItem->setQty($qty);
$stockItem->setIsQtyDecimal(0);
$stockItem->setIsInStock(1);
$stockItem->save();
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testUpdateQty()
{
$qty = 1;
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_cart_with_configurable', 'reserved_order_id');
$cartId = $quote->getId();
$items = $quote->getAllItems();
$this->assertGreaterThan(0, count($items));
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item|null $item */
$item = null;
/** @var \Magento\Quote\Model\ResourceModel\Quote\Item $quoteItem */
foreach ($items as $quoteItem) {
if ($quoteItem->getProductType() == Configurable::TYPE_CODE) {
$item = $quoteItem;
break;
}
}
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/carts/' . $cartId . '/items/' . $item->getId(),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$this->assertNotNull($item);
$this->assertNotNull($item->getId());
$this->assertEquals(Configurable::TYPE_CODE, $item->getProductType());
$requestData = $this->getRequestData($cartId);
$requestData['cartItem']['qty'] = $qty;
$requestData['cartItem']['item_id'] = $item->getId();
$requestData['cartItem']['product_option'] = null;
$response = $this->_webApiCall($serviceInfo, $requestData);
$this->assertNotNull($response['item_id']);
$this->assertEquals($item->getId(), $response['item_id']);
$this->assertEquals(Configurable::TYPE_CODE, $response['product_type']);
$this->assertEquals($cartId, $response['quote_id']);
$this->assertEquals($qty, $response['qty']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testGetList()
{
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('test_cart_with_configurable', '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->assertEquals(Configurable::TYPE_CODE, $item['product_type']);
$this->assertArrayHasKey('product_option', $item);
$this->assertArrayHasKey('extension_attributes', $item['product_option']);
$this->assertArrayHasKey('configurable_item_options', $item['product_option']['extension_attributes']);
$options = $item['product_option']['extension_attributes']['configurable_item_options'];
$this->assertGreaterThan(0, count($options));
$this->assertArrayHasKey('option_id', $options[0]);
$this->assertArrayHasKey('option_value', $options[0]);
$this->assertNotNull($options[0]['option_id']);
$this->assertNotNull($options[0]['option_value']);
}
/**
* @param $cartId
* @param null $selectedOption
* @return array
*/
protected function getRequestData($cartId, $selectedOption = null)
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get(self::CONFIGURABLE_PRODUCT_SKU);
$configurableProductOptions = $product->getExtensionAttributes()->getConfigurableProductOptions();
$optionKey = 0;
if ($selectedOption && isset($options[$selectedOption])) {
$optionKey = $selectedOption;
}
$attributeId = $configurableProductOptions[0]->getAttributeId();
$options = $configurableProductOptions[0]->getOptions();
$optionId = $options[$optionKey]['value_index'];
return [
'cartItem' => [
'sku' => self::CONFIGURABLE_PRODUCT_SKU,
'qty' => 1,
'quote_id' => $cartId,
'product_option' => [
'extension_attributes' => [
'configurable_item_options' => [
[
'option_id' => $attributeId,
'option_value' => $optionId
]
]
]
]
]
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Api;
use Magento\TestFramework\Helper\Bootstrap;
class ConfigurableProductManagementTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
const SERVICE_NAME = 'configurableProductConfigurableProductManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/configurable-products/variation';
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attribute.php
*/
public function testGetVariation()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GenerateVariation'
]
];
/** @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->get(
\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class
);
$attribute = $attributeRepository->get('test_configurable');
$attributeOptionValue = $attribute->getOptions()[1]->getValue();
$data = [
'product' => [
'sku' => 'test',
'price' => 10
],
'options' => [
[
'attribute_id' => 'test_configurable',
'values' => [
[
'value_index' => $attributeOptionValue,
]
]
]
]
];
$actual = $this->_webApiCall($serviceInfo, $data);
$expectedItems = [
[
'sku' => 'test-' . $attributeOptionValue,
'price' => 10,
'name' => '-' . $attributeOptionValue,
'status' => 1,
'visibility' => \Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE,
'product_links' => [],
'custom_attributes' => [
[
'attribute_code' => 'test_configurable',
'value' => $attributeOptionValue
]
],
'tier_prices' => []
]
];
ksort($expectedItems);
ksort($actual);
$this->assertEquals($expectedItems, $actual);
}
}
@@ -0,0 +1,519 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Api;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Eav\Model\AttributeRepository;
use Magento\Eav\Model\Entity\Attribute\Option;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Class LinkManagementTest for testing ConfigurableProduct to SimpleProduct link functionality
*/
class LinkManagementTest extends WebapiAbstract
{
const SERVICE_NAME = 'configurableProductLinkManagementV1';
const OPTION_SERVICE_NAME = 'configurableProductOptionRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/configurable-products';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var AttributeRepository
*/
protected $attributeRepository;
/**
* Execute per test initialization
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->attributeRepository = $this->objectManager->get(\Magento\Eav\Model\AttributeRepository::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testGetChildren(): void
{
$productSku = 'configurable';
/** @var array $result */
$result = $this->getChildren($productSku);
$this->assertCount(2, $result);
foreach ($result as $product) {
$this->assertArrayHasKey('custom_attributes', $product);
$this->assertArrayHasKey('price', $product);
$this->assertArrayHasKey('updated_at', $product);
$this->assertArrayHasKey('name', $product);
$this->assertStringContainsString('Configurable Option', $product['name']);
$this->assertArrayHasKey('sku', $product);
$this->assertStringContainsString('simple_', $product['sku']);
$this->assertArrayHasKey('status', $product);
$this->assertEquals('1', $product['status']);
}
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_simple_77.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/delete_association.php
*
* @return void
*/
public function testAddChild(): void
{
$productSku = 'configurable';
$childSku = 'simple_77';
$res = $this->addChild($productSku, $childSku);
$this->assertTrue($res);
}
/**
* Test the full flow of creating a configurable product and adding a child via REST
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attribute.php
*
* @return void
*/
public function testAddChildFullRestCreation(): void
{
$productSku = 'configurable-product-sku';
$childSku = 'simple-product-sku';
$this->createConfigurableProduct($productSku);
$attribute = $this->attributeRepository->get('catalog_product', 'test_configurable');
$this->addOptionToConfigurableProduct(
$productSku,
(int)$attribute->getAttributeId(),
[
[
'value_index' => $attribute->getOptions()[1]->getValue()
]
]
);
$this->createSimpleProduct(
$childSku,
[
[
'attribute_code' => 'test_configurable',
'value' => $attribute->getOptions()[1]->getValue()
]
]
);
$res = $this->addChild($productSku, $childSku);
$this->assertTrue($res);
// confirm that the simple product was added
$children = $this->getChildren($productSku);
$added = false;
foreach ($children as $child) {
if ($child['sku'] == $childSku) {
$added = true;
break;
}
}
$this->assertTrue($added);
// clean up products
$this->deleteProduct($productSku);
$this->deleteProduct($childSku);
}
/**
* Test if configurable option attribute positions are being preserved after simple products were assigned to a
* configurable product.
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php
*
* @return void
*/
public function testConfigurableOptionPositionPreservation(): void
{
$productSku = 'configurable-product-sku';
$childProductSkus = [
'simple-product-sku-1',
'simple-product-sku-2'
];
$attributesToAdd = [
'custom_attr_1',
'custom_attr_2',
];
$this->createConfigurableProduct($productSku);
$position = 0;
$attributeOptions = [];
foreach ($attributesToAdd as $attributeToAdd) {
/** @var Attribute $attribute */
$attribute = $this->attributeRepository->get('catalog_product', $attributeToAdd);
/** @var Option $options [] */
$options = $attribute->getOptions();
array_shift($options);
$attributeOptions[$attributeToAdd] = $options;
$valueIndexesData = [];
foreach ($options as $option) {
$valueIndexesData[]['value_index'] = $option->getValue();
}
$this->addOptionToConfigurableProduct(
$productSku,
(int)$attribute->getAttributeId(),
$valueIndexesData,
$position
);
$position++;
}
$this->assertArrayHasKey($attributesToAdd[0], $attributeOptions);
$this->assertArrayHasKey($attributesToAdd[1], $attributeOptions);
$this->assertCount(4, $attributeOptions[$attributesToAdd[0]]);
$this->assertCount(4, $attributeOptions[$attributesToAdd[1]]);
$attributesBeforeAssign = $this->getConfigurableAttribute($productSku);
$simpleProdsAttributeData = [];
foreach ($attributeOptions as $attributeCode => $options) {
$simpleProdsAttributeData [0][] = [
'attribute_code' => $attributeCode,
'value' => $options[0]->getValue(),
];
$simpleProdsAttributeData [0][] = [
'attribute_code' => $attributeCode,
'value' => $options[1]->getValue(),
];
$simpleProdsAttributeData [1][] = [
'attribute_code' => $attributeCode,
'value' => $options[2]->getValue(),
];
$simpleProdsAttributeData [1][] = [
'attribute_code' => $attributeCode,
'value' => $options[3]->getValue(),
];
}
foreach ($childProductSkus as $childNum => $childSku) {
$this->createSimpleProduct($childSku, $simpleProdsAttributeData[$childNum]);
$res = $this->addChild($productSku, $childSku);
$this->assertTrue($res);
}
$childProductsDiff = array_diff(
$childProductSkus,
array_column(
$this->getChildren($productSku),
'sku'
)
);
$this->assertCount(0, $childProductsDiff, 'Added child product count mismatch expected result');
$attributesAfterAssign = $this->getConfigurableAttribute($productSku);
$this->assertEquals(
$attributesBeforeAssign[0]['position'],
$attributesAfterAssign[0]['position'],
'Product 1 attribute option position mismatch'
);
$this->assertEquals(
$attributesBeforeAssign[1]['position'],
$attributesAfterAssign[1]['position'],
'Product 2 attribute option position mismatch'
);
foreach ($childProductSkus as $childSku) {
$this->deleteProduct($childSku);
}
$this->deleteProduct($productSku);
}
/**
* Delete product by SKU
*
* @param string $sku
* @return bool
*/
private function deleteProduct(string $sku): bool
{
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products/' . $sku,
'httpMethod' => Request::HTTP_METHOD_DELETE
],
'soap' => [
'service' => 'catalogProductRepositoryV1',
'serviceVersion' => self::SERVICE_VERSION,
'operation' => 'catalogProductRepositoryV1DeleteById',
],
];
return $this->_webApiCall($serviceInfo, ['sku' => $sku]);
}
/**
* Get configurable product attributes
*
* @param string $productSku
* @return array
*/
protected function getConfigurableAttribute(string $productSku): array
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/all',
'httpMethod' => Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::OPTION_SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::OPTION_SERVICE_NAME . 'GetList'
]
];
return $this->_webApiCall($serviceInfo, ['sku' => $productSku]);
}
/**
* Perform add child product Api call
*
* @param string $productSku
* @param string $childSku
* @return array|int|string|float|bool
*/
private function addChild(string $productSku, string $childSku)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/child',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'AddChild'
]
];
return $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'childSku' => $childSku]);
}
/**
* Perform create configurable product api call
*
* @param string $productSku
* @return array|bool|float|int|string
*/
protected function createConfigurableProduct(string $productSku)
{
$requestData = [
'product' => [
'sku' => $productSku,
'name' => 'configurable-product-' . $productSku,
'type_id' => 'configurable',
'price' => 50,
'attribute_set_id' => 4
]
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products',
'httpMethod' => Request::HTTP_METHOD_POST
],
'soap' => [
'service' => 'catalogProductRepositoryV1',
'serviceVersion' => self::SERVICE_VERSION,
'operation' => 'catalogProductRepositoryV1Save',
],
];
return $this->_webApiCall($serviceInfo, $requestData);
}
/**
* Add option to configurable product
*
* @param string $productSku
* @param int $attributeId
* @param array $attributeValues
* @param int $position
* @return array|bool|float|int|string
*/
protected function addOptionToConfigurableProduct(
string $productSku,
int $attributeId,
array $attributeValues,
int $position = 0
) {
$requestData = [
'sku' => $productSku,
'option' => [
'attribute_id' => $attributeId,
'label' => 'test_configurable',
'position' => $position,
'is_use_default' => true,
'values' => $attributeValues
]
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/configurable-products/' . $productSku . '/options',
'httpMethod' => Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => 'configurableProductOptionRepositoryV1',
'serviceVersion' => self::SERVICE_VERSION,
'operation' => 'configurableProductOptionRepositoryV1Save',
],
];
return $this->_webApiCall($serviceInfo, $requestData);
}
protected function createSimpleProduct($sku, $customAttributes)
{
$requestData = [
'product' => [
'sku' => $sku,
'name' => 'simple-product-' . $sku,
'type_id' => 'simple',
'attribute_set_id' => 4,
'price' => 3.62,
'status' => 1,
'visibility' => 4,
'custom_attributes' => $customAttributes
]
];
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/products',
'httpMethod' => Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => 'catalogProductRepositoryV1',
'serviceVersion' => self::SERVICE_VERSION,
'operation' => 'catalogProductRepositoryV1Save',
],
];
return $this->_webApiCall($serviceInfo, $requestData);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testRemoveChild(): void
{
$productSku = 'configurable';
$childSku = 'simple_10';
$this->assertTrue($this->removeChild($productSku, $childSku));
}
/**
* @dataProvider errorsDataProvider
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @param string $parentSku
* @param string $childSku
* @param string $errorMessage
* @return void
*/
public function testAddChildWithError(string $parentSku, string $childSku, string $errorMessage): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage($errorMessage);
$this->addChild($parentSku, $childSku);
}
/**
* @return array
*/
public function errorsDataProvider(): array
{
return [
'simple_instead_of_configurable' => [
'parent_sku' => 'simple2',
'child_sku' => 'configurable',
'error_message' => (string)__("The parent product doesn't have configurable product options."),
],
'simple_with_empty_configurable_attribute_value' => [
'parent_sku' => 'configurable',
'child_sku' => 'simple2',
'error_message' => TESTS_WEB_API_ADAPTER === self::ADAPTER_SOAP
? (string)__(
'The child product doesn\'t have the "%1" attribute value. Verify the value and try again.'
)
: (string)__(
'The child product doesn\'t have the \\"%1\\" attribute value. Verify the value and try again.'
),
],
];
}
/**
* Remove child product
*
* @param string $productSku
* @param string $childSku
* @return array|bool|float|int|string
*/
protected function removeChild(string $productSku, string $childSku)
{
$resourcePath = self::RESOURCE_PATH . '/%s/children/%s';
$serviceInfo = [
'rest' => [
'resourcePath' => sprintf($resourcePath, $productSku, $childSku),
'httpMethod' => Request::HTTP_METHOD_DELETE
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'RemoveChild'
]
];
$requestData = ['sku' => $productSku, 'childSku' => $childSku];
return $this->_webApiCall($serviceInfo, $requestData);
}
/**
* Get child products
*
* @param string $productSku
* @return string[]
*/
protected function getChildren(string $productSku)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/children',
'httpMethod' => Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetChildren'
]
];
return $this->_webApiCall($serviceInfo, ['sku' => $productSku]);
}
}
@@ -0,0 +1,377 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Api;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Model\ProductRepository;
use Magento\Eav\Api\AttributeRepositoryInterface;
/**
* Class OptionRepositoryTest for testing ConfigurableProductoption integration
*/
class OptionRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
public const SERVICE_NAME = 'configurableProductOptionRepositoryV1';
public const SERVICE_VERSION = 'V1';
public const RESOURCE_PATH = '/V1/configurable-products';
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testGet(): void
{
$productSku = 'configurable';
$options = $this->getList($productSku);
$this->assertIsArray($options);
$this->assertNotEmpty($options);
foreach ($options as $option) {
/** @var array $result */
$result = $this->get($productSku, $option['id']);
$this->assertIsArray($result);
$this->assertNotEmpty($result);
$this->assertArrayHasKey('id', $result);
$this->assertEquals($option['id'], $result['id']);
$this->assertArrayHasKey('attribute_id', $result);
$this->assertEquals($option['attribute_id'], $result['attribute_id']);
$this->assertArrayHasKey('label', $result);
$this->assertEquals($option['label'], $result['label']);
$this->assertArrayHasKey('values', $result);
$this->assertIsArray($result['values']);
$this->assertEquals($option['values'], $result['values']);
}
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testGetList(): void
{
$productSku = 'configurable';
/** @var array $result */
$result = $this->getList($productSku);
$this->assertNotEmpty($result);
$this->assertIsArray($result);
$this->assertArrayHasKey(0, $result);
$option = $result[0];
$this->assertNotEmpty($option);
$this->assertIsArray($option);
$this->assertArrayHasKey('id', $option);
$this->assertArrayHasKey('label', $option);
$this->assertEquals($option['label'], 'Test Configurable');
$this->assertArrayHasKey('values', $option);
$this->assertIsArray($option);
$this->assertNotEmpty($option);
$this->assertCount(2, $option['values']);
foreach ($option['values'] as $value) {
$this->assertIsArray($value);
$this->assertNotEmpty($value);
$this->assertArrayHasKey('value_index', $value);
}
}
/**
* @return void
*/
public function testGetUndefinedProduct(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'The product that was requested doesn\'t exist. Verify the product and try again.'
);
$productSku = 'product_not_exist';
$this->getList($productSku);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testGetUndefinedOption(): void
{
$expectedMessage = 'The "%1" entity that was requested doesn\'t exist. Verify the entity and try again.';
$productSku = 'configurable';
$attributeId = -42;
try {
$this->get($productSku, $attributeId);
} 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([$attributeId], $errorObj['parameters']);
}
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testDelete(): void
{
$productSku = 'configurable';
$optionList = $this->getList($productSku);
$optionId = $optionList[0]['id'];
$resultRemove = $this->delete($productSku, $optionId);
$optionListRemoved = $this->getList($productSku);
$this->assertTrue($resultRemove);
$this->assertEquals(count($optionList) - 1, count($optionListRemoved));
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attribute.php
*
* @return void
*/
public function testAdd(): void
{
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class);
/** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */
$attribute = $attributeRepository->get('catalog_product', 'test_configurable');
$productSku = 'simple';
$productRepository = Bootstrap::getObjectManager()->create(ProductRepository::class);
$product = $productRepository->get($productSku);
$this->assertEquals('simple', $product->getTypeId());
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save'
]
];
$option = [
'attribute_id' => $attribute->getAttributeId(),
'label' => 'Test',
'values' => [
[
'value_index' => 1,
]
],
];
/** @var int $result */
$result = $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'option' => $option]);
$this->assertGreaterThan(0, $result);
$updatedproductRepo = Bootstrap::getObjectManager()->create(ProductRepository::class);
$updatedproduct = $updatedproductRepo->get($productSku);
$this->assertEquals('configurable', $updatedproduct->getTypeId());
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testUpdate(): void
{
$productSku = 'configurable';
$configurableAttribute = $this->getConfigurableAttribute($productSku);
$optionId = $configurableAttribute[0]['id'];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options' . '/' . $optionId,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save'
]
];
$requestBody = [
'option' => [
'label' => 'Update Test Configurable',
]
];
if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
$requestBody['sku'] = $productSku;
$requestBody['option']['id'] = $optionId;
}
$result = $this->_webApiCall($serviceInfo, $requestBody);
$this->assertGreaterThan(0, $result);
$configurableAttribute = $this->getConfigurableAttribute($productSku);
$this->assertEquals($requestBody['option']['label'], $configurableAttribute[0]['label']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testUpdateWithoutOptionId(): void
{
$productSku = 'configurable';
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class);
/** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */
$attribute = $attributeRepository->get('catalog_product', 'test_configurable');
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save'
]
];
$option = [
'attribute_id' => $attribute->getAttributeId(),
'label' => 'Update Test Configurable with sku and attribute_id',
'values' => [
[
'value_index' => 1,
]
],
];
$result = $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'option' => $option]);
$this->assertGreaterThan(0, $result);
$configurableAttribute = $this->getConfigurableAttribute($productSku);
$this->assertEquals($option['label'], $configurableAttribute[0]['label']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testDeleteNotExistsOption(): void
{
$message = (string)__('The option that was requested doesn\'t exist. Verify the entity and try again.');
$this->expectExceptionMessage($message);
$this->expectException(\Exception::class);
$this->delete('configurable', 555);
}
/**
* @param string $productSku
* @return array
*/
protected function getConfigurableAttribute($productSku)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/all',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList'
]
];
return $this->_webApiCall($serviceInfo, ['sku' => $productSku]);
}
/**
* @param string $productSku
* @param int $optionId
* @return bool
*/
private function delete($productSku, $optionId)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/' . $optionId,
'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, ['sku' => $productSku, 'id' => $optionId]);
}
/**
* @param $productSku
* @param $optionId
* @return array
*/
protected function get($productSku, $optionId)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/' . $optionId,
'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, ['sku' => $productSku, 'id' => $optionId]);
}
/**
* @param $productSku
* @return array
*/
protected function getList($productSku)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/all',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList'
]
];
return $this->_webApiCall($serviceInfo, ['sku' => $productSku]);
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\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/ConfigurableProduct/_files/order_item_with_configurable_and_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/ConfigurableProduct/_files/order_item_with_configurable_and_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()->getSuperAttribute();
$this->assertArrayHasKey('product_option', $response);
$this->assertArrayHasKey('extension_attributes', $response['product_option']);
$this->assertArrayHasKey('configurable_item_options', $response['product_option']['extension_attributes']);
$actualOptions = $response['product_option']['extension_attributes']['configurable_item_options'];
$this->assertIsArray($actualOptions);
$this->assertIsArray($actualOptions[0]);
$this->assertArrayHasKey('option_id', $actualOptions[0]);
$this->assertArrayHasKey('option_value', $actualOptions[0]);
$this->assertEquals(key($expected), $actualOptions[0]['option_id']);
$this->assertEquals(current($expected), $actualOptions[0]['option_value']);
}
}
@@ -0,0 +1,628 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Api;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Entity\Attribute;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection;
use Magento\Framework\Api\ExtensibleDataInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
/**
* Class ProductRepositoryTest for testing ConfigurableProduct integration
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProductRepositoryTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductRepositoryV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products';
const CONFIGURABLE_PRODUCT_SKU = 'configurable-product-sku';
/**
* @var Config
*/
private $eavConfig;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Attribute
*/
private $configurableAttribute;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->eavConfig = $this->objectManager->get(Config::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->deleteProductBySku(self::CONFIGURABLE_PRODUCT_SKU);
parent::tearDown();
}
/**
* Retrieve configurable attribute options
*
* @return array
*/
protected function getConfigurableAttributeOptions()
{
/** @var Collection $optionCollection */
$optionCollection = $this->objectManager->create(
Collection::class
);
$options = $optionCollection->setAttributeFilter($this->configurableAttribute->getId())->getData();
return $options;
}
/**
* Create configurable product by web api
*
* @return array
*/
protected function createConfigurableProduct()
{
$productId1 = 10;
$productId2 = 20;
$label = "color";
$this->configurableAttribute = $this->eavConfig->getAttribute('catalog_product', 'test_configurable');
$this->assertNotNull($this->configurableAttribute);
$options = $this->getConfigurableAttributeOptions();
$this->assertCount(2, $options);
$configurableProductOptions = [
[
"attribute_id" => $this->configurableAttribute->getId(),
"label" => $label,
"position" => 0,
"values" => [
[
"value_index" => $options[0]['option_id'],
],
[
"value_index" => $options[1]['option_id'],
],
],
],
];
$product = [
"sku" => self::CONFIGURABLE_PRODUCT_SKU,
"name" => self::CONFIGURABLE_PRODUCT_SKU,
"type_id" => "configurable",
"price" => 50,
'attribute_set_id' => 4,
"custom_attributes" => [
[
"attribute_code" => $this->configurableAttribute->getAttributeCode(),
"value" => $options[0]['option_id'],
],
],
"extension_attributes" => [
"configurable_product_options" => $configurableProductOptions,
"configurable_product_links" => [$productId1, $productId2],
],
];
$response = $this->createProduct($product);
return $response;
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testCreateConfigurableProduct()
{
$productId1 = 10;
$productId2 = 20;
$label = "color";
$response = $this->createConfigurableProduct();
$this->assertEquals(self::CONFIGURABLE_PRODUCT_SKU, $response[ProductInterface::SKU]);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"])
);
$resultConfigurableProductOptions
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"];
$this->assertCount(1, $resultConfigurableProductOptions);
$this->assertTrue(isset($resultConfigurableProductOptions[0]['label']));
$this->assertTrue(isset($resultConfigurableProductOptions[0]['id']));
$this->assertEquals($label, $resultConfigurableProductOptions[0]['label']);
$this->assertTrue(
isset($resultConfigurableProductOptions[0]['values'])
);
$this->assertCount(2, $resultConfigurableProductOptions[0]['values']);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"])
);
$resultConfigurableProductLinks
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"];
$this->assertCount(2, $resultConfigurableProductLinks);
$this->assertEquals([$productId1, $productId2], $resultConfigurableProductLinks);
}
/**
* Verify configurable product creation passes validation with required attribute not specified in product itself.
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testCreateConfigurableProductWithRequiredAttribute(): void
{
$configurableAttribute = $this->eavConfig->getAttribute('catalog_product', 'test_configurable');
$configurableAttribute->setIsRequired(true);
$configurableAttribute->save();
$response = $this->createConfigurableProductWithRequiredAttribute();
$this->assertEquals(self::CONFIGURABLE_PRODUCT_SKU, $response[ProductInterface::SKU]);
}
/**
* Create configurable with simple which has zero attribute value
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attribute_with_source_model.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @return void
*/
public function testCreateConfigurableProductWithZeroOptionValue(): void
{
$attributeCode = 'test_configurable_with_sm';
$attributeValue = 0;
$product = $this->productRepository->get('simple');
$product->setCustomAttribute($attributeCode, $attributeValue);
$this->productRepository->save($product);
$configurableAttribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
$productData = [
'sku' => self::CONFIGURABLE_PRODUCT_SKU,
'name' => self::CONFIGURABLE_PRODUCT_SKU,
'type_id' => Configurable::TYPE_CODE,
'attribute_set_id' => 4,
'extension_attributes' => [
'configurable_product_options' => [
[
'attribute_id' => $configurableAttribute->getId(),
'label' => 'Test configurable with source model',
'values' => [
['value_index' => '0'],
],
],
],
'configurable_product_links' => [$product->getId()],
],
];
$response = $this->createProduct($productData);
$this->assertArrayHasKey(ProductInterface::SKU, $response);
$this->assertEquals(self::CONFIGURABLE_PRODUCT_SKU, $response[ProductInterface::SKU]);
$this->assertArrayHasKey(ProductInterface::TYPE_ID, $response);
$this->assertEquals('configurable', $response[ProductInterface::TYPE_ID]);
$this->assertArrayHasKey(ProductInterface::EXTENSION_ATTRIBUTES_KEY, $response);
$this->assertArrayHasKey(
'configurable_product_options',
$response[ProductInterface::EXTENSION_ATTRIBUTES_KEY]
);
$configurableProductOption =
current($response[ProductInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options']);
$this->assertArrayHasKey('attribute_id', $configurableProductOption);
$this->assertEquals($configurableAttribute->getId(), $configurableProductOption['attribute_id']);
$this->assertArrayHasKey('values', $configurableProductOption);
$this->assertEquals($attributeValue, $configurableProductOption['values'][0]['value_index']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testDeleteConfigurableProductOption()
{
$response = $this->createConfigurableProduct();
//delete existing option
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'] = [];
//leave the product links unchanged
unset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links']);
$response = $this->saveProduct($response);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"])
);
$resultConfigurableProductOptions
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"];
$this->assertCount(0, $resultConfigurableProductOptions);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"])
);
$resultConfigurableProductLinks
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"];
$this->assertCount(0, $resultConfigurableProductLinks);
$this->assertEquals([], $resultConfigurableProductLinks);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testUpdateConfigurableProductOption()
{
$productId1 = 10;
$newLabel = 'size';
$response = $this->createConfigurableProduct();
$option = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"][0];
$optionId = $option['id'];
$productId = $option['product_id'];
$updatedOption = [
'id' => $optionId,
'attribute_id' => $option['attribute_id'],
'label' => $newLabel,
'position' => 1,
'values' => [
[
'value_index' => $option['values'][0]['value_index'],
],
],
'product_id' => $productId,
];
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'][0] =
$updatedOption;
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [$productId1];
$response = $this->saveProduct($response);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"])
);
$resultConfigurableProductOptions
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"];
$this->assertCount(1, $resultConfigurableProductOptions);
unset($updatedOption['id']);
unset($resultConfigurableProductOptions[0]['id']);
$this->assertEquals($updatedOption, $resultConfigurableProductOptions[0]);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testUpdateConfigurableProductLinks()
{
$productId1 = 10;
$productId2 = 20;
$response = $this->createConfigurableProduct();
$options = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'];
//leave existing option untouched
unset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options']);
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [$productId1];
$response = $this->saveProduct($response);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"])
);
$resultConfigurableProductOptions
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"];
$this->assertCount(1, $resultConfigurableProductOptions);
//Since one product is removed, the available values for the option is reduced
$this->assertCount(1, $resultConfigurableProductOptions[0]['values']);
$this->assertTrue(
isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"])
);
$resultConfigurableProductLinks
= $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"];
$this->assertCount(1, $resultConfigurableProductLinks);
$this->assertEquals([$productId1], $resultConfigurableProductLinks);
//adding back the product links, the option value should be restored
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links']
= [$productId1, $productId2];
//set the value for required attribute
$response["custom_attributes"][] =
[
"attribute_code" => $this->configurableAttribute->getAttributeCode(),
"value" => $resultConfigurableProductOptions[0]['values'][0]['value_index'],
];
$response = $this->saveProduct($response);
$currentOptions = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'];
$this->assertEquals($options, $currentOptions);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testUpdateConfigurableProductLinksWithNonExistingProduct()
{
$productId1 = 10;
$nonExistingId = 999;
$response = $this->createConfigurableProduct();
//leave existing option untouched
unset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options']);
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [
$productId1,
$nonExistingId,
];
$expectedMessage = 'The product that was requested doesn\'t exist. Verify the product and try again.';
try {
$this->saveProduct($response);
$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']);
}
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testUpdateConfigurableProductLinksWithDuplicateAttributes()
{
$productId1 = 10;
$productId2 = 20;
$response = $this->createConfigurableProduct();
$options = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'];
//make product2 and product1 have the same value for the configurable attribute
$optionValue1 = $options[0]['values'][0]['value_index'];
$product2 = $this->getProduct('simple_' . $productId2);
$product2['custom_attributes'] = [
[
'attribute_code' => 'test_configurable',
'value' => $optionValue1,
],
];
$this->saveProduct($product2);
//leave existing option untouched
unset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options']);
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [
$productId1,
$productId2,
];
$expectedMessage = 'Products "%1" and "%2" have the same set of attribute values.';
try {
$this->saveProduct($response);
$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(['0' => 20, '1' => 10], $errorObj['parameters']);
}
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testUpdateConfigurableProductLinksWithWithoutVariationAttributes()
{
$productId1 = 99;
$productId2 = 88;
$response = $this->createConfigurableProduct();
/** delete all variation attribute */
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options'] = [];
$response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [
$productId1,
$productId2,
];
$expectedMessage = 'The product that was requested doesn\'t exist. Verify the product and try again.';
try {
$this->saveProduct($response);
$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']);
}
}
/**
* Get product
*
* @param string $productSku
* @return array the product data
*/
protected function getProduct($productSku)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $productSku,
'httpMethod' => Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$response = (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) ?
$this->_webApiCall($serviceInfo, ['sku' => $productSku]) : $this->_webApiCall($serviceInfo);
return $response;
}
/**
* Create product
*
* @param array $product
* @return array the created product data
*/
protected function createProduct($product)
{
$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',
],
];
$requestData = ['product' => $product];
$response = $this->_webApiCall($serviceInfo, $requestData);
return $response;
}
/**
* Delete a product by sku
*
* @param $productSku
* @return bool
*/
protected function deleteProductBySku($productSku)
{
$resourcePath = self::RESOURCE_PATH . '/' . $productSku;
$serviceInfo = [
'rest' => [
'resourcePath' => $resourcePath,
'httpMethod' => 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;
}
/**
* Save product
*
* @param array $product
* @return array the created product data
*/
protected function saveProduct($product)
{
if (isset($product['custom_attributes'])) {
$count = count($product['custom_attributes']);
for ($i = 0; $i < $count; $i++) {
if ($product['custom_attributes'][$i]['attribute_code'] == 'category_ids'
&& !is_array($product['custom_attributes'][$i]['value'])
) {
$product['custom_attributes'][$i]['value'] = [""];
}
}
}
$resourcePath = self::RESOURCE_PATH . '/' . $product['sku'];
$serviceInfo = [
'rest' => [
'resourcePath' => $resourcePath,
'httpMethod' => Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$requestData = ['product' => $product];
$response = $this->_webApiCall($serviceInfo, $requestData);
return $response;
}
/**
* Create configurable product with required attribute by web api.
*
* @return array
*/
private function createConfigurableProductWithRequiredAttribute(): array
{
$this->configurableAttribute = $this->eavConfig->getAttribute('catalog_product', 'test_configurable');
$options = $this->getConfigurableAttributeOptions();
$configurableProductOptions = [
[
"attribute_id" => $this->configurableAttribute->getId(),
"label" => 'color',
"position" => 0,
"values" => [
[
"value_index" => $options[0]['option_id'],
],
[
"value_index" => $options[1]['option_id'],
],
],
],
];
$product = [
"sku" => self::CONFIGURABLE_PRODUCT_SKU,
"name" => self::CONFIGURABLE_PRODUCT_SKU,
"type_id" => "configurable",
"price" => 50,
'attribute_set_id' => 4,
"extension_attributes" => [
"configurable_product_options" => $configurableProductOptions,
"configurable_product_links" => [10, 20],
],
];
return $this->createProduct($product);
}
}