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,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Checks creating attribute options process.
*
* @see \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute\CreateOptions
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class CreateOptionsTest extends AbstractBackendController
{
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$productRepository->cleanCache();
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testAddAlreadyAddedOption(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$attribute = $this->_objectManager->get(ProductAttributeRepositoryInterface::class)
->get('test_configurable');
$this->getRequest()->setParams([
'options' => [
[
'label' => 'Option 1',
'is_new' => true,
'attribute_id' => (int)$attribute->getAttributeId(),
],
],
]);
$this->dispatch('backend/catalog/product_attribute/createOptions');
$responseBody = $this->_objectManager->get(SerializerInterface::class)
->unserialize($this->getResponse()->getBody());
$this->assertNotEmpty($responseBody);
$this->assertStringContainsString(
(string)__('The value of attribute ""%1"" must be unique', $attribute->getAttributeCode()),
$responseBody['message']
);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Test\Fixture\Attribute as AttributeFixture;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\Eav\Model\Config;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
/**
* Checks creating attribute options process.
*
* @see \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute\UpdateProductAttributeTest
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class UpdateProductAttributeTest extends AbstractBackendController
{
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var Config
*/
private $eavConfig;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$productRepository->cleanCache();
$this->productAttributeRepository = $this->_objectManager->create(ProductAttributeRepositoryInterface::class);
$this->eavConfig = $this->_objectManager->create(Config::class);
}
/**
* Test updating a product attribute and checking the frontend_class for the sku attribute.
*
* @return void
* @throws LocalizedException
*/
#[
DataFixture(AttributeFixture::class, as: 'attr'),
]
public function testAttributeWithBackendTypeHasSameValueInFrontendClass()
{
// Load the 'sku' attribute.
/** @var ProductAttributeInterface $attribute */
$attribute = $this->productAttributeRepository->get('sku');
$expectedFrontEndClass = $attribute->getFrontendClass();
// Save the attribute.
$this->productAttributeRepository->save($attribute);
// Check that the value of the frontend_class changed or not.
try {
$skuAttribute = $this->eavConfig->getAttribute('catalog_product', 'sku');
$this->assertEquals($expectedFrontEndClass, $skuAttribute->getFrontendClass());
} catch (LocalizedException $e) {
$this->fail($e->getMessage());
}
}
}
@@ -0,0 +1,384 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Initialization;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper;
use Magento\Catalog\Model\Product\Media\Config;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for image processing plugins for child products by saving a configurable product.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class HelperTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Helper
*/
private $helper;
/**
* @var RequestInterface
*/
private $request;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var SerializerInterface
*/
private $jsonSerializer;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var Config
*/
private $config;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ProductInterface
*/
private $configurableProduct;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->request = $this->objectManager->get(RequestInterface::class);
$this->helper = $this->objectManager->get(Helper::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->productResource =$this->objectManager->get(ProductResource::class);
$this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->jsonSerializer = $this->objectManager->get(SerializerInterface::class);
$this->searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$this->config = $this->objectManager->get(Config::class);
$this->mediaDirectory = $this->objectManager->get(Filesystem::class)->getDirectoryWrite(DirectoryList::MEDIA);
$this->configurableProduct = $this->productRepository->get('configurable');
}
/**
* Tests adding images with various roles to child products by saving a configurable product.
*
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @dataProvider initializeDataProvider
* @param array $childProducts
* @param array $expectedImages
* @return void
*/
public function testInitialize(array $childProducts, array $expectedImages): void
{
$this->setRequestParams($childProducts);
$this->helper->initialize($this->configurableProduct);
$this->assertChildProductImages($expectedImages);
}
/**
* Tests replacing images with various roles to child products by saving a configurable product.
*
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @dataProvider initializeWithExistingChildImagesDataProvider
* @param array $childProducts
* @param array $expectedImages
* @return void
*/
public function testInitializeWithExistingChildImages(array $childProducts, array $expectedImages): void
{
$this->updateChildProductsImages(
[
'simple_10' => '/m/a/magento_thumbnail.jpg.tmp',
'simple_20' => '/m/a/magento_small_image.jpg.tmp',
]
);
$this->setRequestParams($childProducts);
$this->helper->initialize($this->configurableProduct);
$this->assertChildProductImages($expectedImages);
}
/**
* @return array
*/
public function initializeDataProvider(): array
{
return [
'children_with_same_image_and_roles' => [
'child_products' => [
'simple_10' => [
'media_gallery' => $this->getMediaGallery(['ben062bdw2v' => '/m/a/magento_image.jpg.tmp']),
'images' => [
'/m/a/magento_image.jpg.tmp' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
'simple_20' => [
'media_gallery' => $this->getMediaGallery(['ben062bdw2v' => '/m/a/magento_image.jpg.tmp']),
'images' => [
'/m/a/magento_image.jpg.tmp' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
],
'expected_images' => [
'simple_10' => [
'/m/a/magento_image_1.jpg' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
'simple_20' => [
'/m/a/magento_image_2.jpg' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
],
'children_with_different_images' => [
'child_products' => [
'simple_10' => [
'media_gallery' => $this->getMediaGallery(['ben062bdw2v' => '/m/a/magento_image.jpg.tmp']),
'images' => [
'/m/a/magento_image.jpg.tmp' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
'simple_20' => [
'media_gallery' => $this->getMediaGallery(
['lrwuv5ukisn' => '/m/a/magento_small_image.jpg.tmp']
),
'images' => [
'/m/a/magento_small_image.jpg.tmp' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
],
'expected_images' => [
'simple_10' => [
'/m/a/magento_image_1.jpg' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
'simple_20' => [
'/m/a/magento_small_image_1.jpg' => ['swatch_image', 'small_image', 'image', 'thumbnail'],
],
],
],
'children_with_different_image_roles' => [
'child_products' => [
'simple_10' => [
'media_gallery' => $this->getMediaGallery(
[
'ben062bdw2v' => '/m/a/magento_image.jpg.tmp',
'lrwuv5ukisn' => '/m/a/magento_small_image.jpg.tmp',
]
),
'images' => [
'/m/a/magento_image.jpg.tmp' => ['swatch_image', 'small_image'],
'/m/a/magento_small_image.jpg.tmp' => ['image', 'thumbnail'],
],
],
'simple_20' => [
'media_gallery' => $this->getMediaGallery(
[
'ben062bdw2v' => '/m/a/magento_image.jpg.tmp',
'lrwuv5ukisn' => '/m/a/magento_small_image.jpg.tmp',
]
),
'images' => [
'/m/a/magento_small_image.jpg.tmp' => ['swatch_image', 'small_image'],
'/m/a/magento_image.jpg.tmp' => ['image', 'thumbnail'],
],
],
],
'expected_images' => [
'simple_10' => [
'/m/a/magento_image_1.jpg' => ['swatch_image', 'small_image'],
'/m/a/magento_small_image_1.jpg' => ['image', 'thumbnail'],
],
'simple_20' => [
'/m/a/magento_small_image_2.jpg' => ['swatch_image', 'small_image'],
'/m/a/magento_image_2.jpg' => ['image', 'thumbnail'],
],
],
],
];
}
/**
* @return array
*/
public function initializeWithExistingChildImagesDataProvider(): array
{
$dataProvider = $this->initializeDataProvider();
unset($dataProvider['children_with_different_images'], $dataProvider['children_with_different_image_roles']);
return array_values($dataProvider);
}
/**
* Sets configurable product params to request.
*
* @param array $childProducts
* @return void
*/
private function setRequestParams(array $childProducts): void
{
$matrix = $associatedProductIds = [];
$attribute = $this->productAttributeRepository->get('test_configurable');
foreach ($childProducts as $sku => $product) {
$simpleProduct = $this->productRepository->get($sku);
$attributeValue = $simpleProduct->getData('test_configurable');
foreach ($product['images'] as $image => $roles) {
foreach ($roles as $role) {
$product[$role] = $image;
}
}
unset($product['images']);
$product['configurable_attribute'] = $this->jsonSerializer->serialize(
['test_configurable' => $attributeValue]
);
$product['variationKey'] = $attributeValue;
$product['id'] = $simpleProduct->getId();
$product['sku'] = $sku;
$product['was_changed'] = true;
$product['newProduct'] = 0;
$matrix[] = $product;
$associatedProductIds[] = $simpleProduct->getId();
}
$this->request->setParams(
[
'attributes' => [$attribute->getAttributeId()],
'configurable-matrix-serialized' => $this->jsonSerializer->serialize($matrix),
]
);
$this->request->setPostValue(
'associated_product_ids_serialized',
$this->jsonSerializer->serialize($associatedProductIds)
);
}
/**
* Asserts child products images.
*
* @param array $expectedImages
* @return void
*/
private function assertChildProductImages(array $expectedImages): void
{
$simpleIds = $this->configurableProduct->getExtensionAttributes()->getConfigurableProductLinks();
$criteria = $this->searchCriteriaBuilder->addFilter('entity_id', $simpleIds, 'in')->create();
foreach ($this->productRepository->getList($criteria)->getItems() as $simpleProduct) {
$images = $expectedImages[$simpleProduct->getSku()];
foreach ($images as $image => $roles) {
foreach ($roles as $role) {
$this->assertEquals($image, $simpleProduct->getData($role));
}
$this->assertTrue(
$this->mediaDirectory->isExist($this->config->getBaseMediaPath() . $image)
);
}
}
}
/**
* Returns media gallery product param.
*
* @param array $imageNames
* @return array
*/
private function getMediaGallery(array $imageNames): array
{
$images = [];
foreach ($imageNames as $key => $item) {
$images[$key] = ['file' => $item, 'label' => '', 'media_type' => 'image'];
}
return ['images' => $images];
}
/**
* Sets image to child products.
*
* @param array $imageNames
* @return void
*/
private function updateChildProductsImages(array $imageNames): void
{
$simpleIds = $this->configurableProduct->getExtensionAttributes()->getConfigurableProductLinks();
$criteria = $this->searchCriteriaBuilder->addFilter('entity_id', $simpleIds, 'in')->create();
$products = $this->productRepository->getList($criteria)->getItems();
foreach ($products as $simpleProduct) {
$simpleProduct->setStoreId(Store::DEFAULT_STORE_ID)
->setImage($imageNames[$simpleProduct->getSku()])
->setSmallImage($imageNames[$simpleProduct->getSku()])
->setThumbnail($imageNames[$simpleProduct->getSku()])
->setSwatchImage($imageNames[$simpleProduct->getSku()])
->setData(
'media_gallery',
[
'images' => [
['file' => $imageNames[$simpleProduct->getSku()], 'label' => '', 'media_type' => 'image']
]
]
);
$this->productResource->save($simpleProduct);
}
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product;
use Magento\Catalog\Controller\Adminhtml\Product\MassDeleteTest as CatalogMassDeleteTest;
/**
* Test for mass configurable product deleting.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class MassDeleteTest extends CatalogMassDeleteTest
{
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_one_simple.php
*
* @return void
*/
public function testDeleteConfigurableProductViaMassAction(): void
{
$product = $this->productRepository->get('configurable');
$this->dispatchMassDeleteAction([$product->getId()]);
$this->assertSuccessfulDeleteProducts(1);
}
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Controller\Adminhtml\Product\Save\CreateCustomOptionsTest as SimpleProductOptionsTest;
/**
* Base test cases for configurable product custom options with type "field".
* Option add via dispatch product controller action save with options data in POST data.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
class CreateCustomOptionsTest extends SimpleProductOptionsTest
{
/**
* @var string
*/
protected $productSku = 'configurable';
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Controller\Adminhtml\Product\Save\DeleteCustomOptionsTest as SimpleProductOptionsTest;
/**
* Base test cases for delete configurable product custom option with type "field".
* Option deleting via product controller action save.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
class DeleteCustomOptionsTest extends SimpleProductOptionsTest
{
/**
* @var string
*/
protected $productSku = 'configurable';
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Controller\Adminhtml\Product\Save\UpdateCustomOptionsTest as SimpleProductOptionsTest;
/**
* Base test cases for update configurable product custom options with type "field".
* Option updating via dispatch product controller action save with updated options data in POST data.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
class UpdateCustomOptionsTest extends SimpleProductOptionsTest
{
/**
* @var string
*/
protected $productSku = 'configurable';
}
@@ -0,0 +1,537 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Controller\Adminhtml;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type\Simple;
use Magento\Catalog\Model\Product\Type\Virtual;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Model\Config;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for configurable product admin save.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class ProductTest extends AbstractBackendController
{
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var Registry
*/
private $registry;
/**
* @var SerializerInterface
*/
private $jsonSerializer;
/**
* @var Config
*/
private $eavConfig;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->productAttributeRepository = $this->_objectManager->get(ProductAttributeRepositoryInterface::class);
$this->registry = $this->_objectManager->get(Registry::class);
$this->jsonSerializer = $this->_objectManager->get(SerializerInterface::class);
$this->eavConfig = $this->_objectManager->get(Config::class);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/associated_products.php
* @return void
*/
public function testSaveActionAssociatedProductIds(): void
{
$associatedProductIds = ['3', '14', '15', '92'];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'id' => 1,
'attributes' => [$this->getAttribute('test_configurable')->getId()],
'associated_product_ids_serialized' => $this->jsonSerializer->serialize($associatedProductIds),
]
);
$this->dispatch('backend/catalog/product/save');
$this->assertSessionMessages($this->equalTo([__('You saved the product.')]), MessageInterface::TYPE_SUCCESS);
$this->assertRegistryConfigurableLinks($associatedProductIds);
$this->assertConfigurableLinks('configurable', $associatedProductIds);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_attribute.php
* @dataProvider saveNewProductDataProvider
* @param array $childProducts
* @return void
*/
public function testSaveNewProduct(array $childProducts): void
{
$this->serRequestParams($childProducts);
$this->dispatch('backend/catalog/product/save');
$this->assertSessionMessages($this->equalTo([__('You saved the product.')]), MessageInterface::TYPE_SUCCESS);
$this->assertChildProducts($childProducts);
$this->assertConfigurableOptions('configurable', $childProducts);
$this->assertConfigurableLinks('configurable', $this->getProductIds(array_keys($childProducts)));
}
/**
* @return array
*/
public function saveNewProductDataProvider(): array
{
return [
'with_different_prices_and_qty' => [
'child_products' => [
'simple_1' => [
'name' => 'simple_1',
'sku' => 'simple_1',
'price' => 200,
'weight' => '1',
'qty' => '100',
'attributes' => ['test_configurable' => 'Option 1'],
],
'simple_2' => [
'name' => 'simple_2',
'sku' => 'simple_2',
'price' => 100,
'weight' => '1',
'qty' => '200',
'attributes' => ['test_configurable' => 'Option 2'],
],
],
],
'without_weight' => [
'child_products' => [
'simple_1' => [
'name' => 'simple_1',
'sku' => 'simple_1',
'price' => 100,
'qty' => '100',
'attributes' => ['test_configurable' => 'Option 1'],
],
'simple_2' => [
'name' => 'simple_2',
'sku' => 'simple_2',
'price' => 100,
'qty' => '100',
'attributes' => ['test_configurable' => 'Option 2'],
],
],
],
];
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_one_simple.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_attribute_2.php
* @dataProvider saveExistProductDataProvider
* @param array $childProducts
* @param array $associatedProducts
* @return void
*/
public function testSaveExistProduct(array $childProducts, array $associatedProducts): void
{
$configurableProduct = $this->productRepository->get('configurable');
$this->serRequestParams($childProducts, $associatedProducts, (int)$configurableProduct->getId());
$this->dispatch('backend/catalog/product/save');
$this->assertSessionMessages($this->equalTo([__('You saved the product.')]), MessageInterface::TYPE_SUCCESS);
$this->assertChildProducts($childProducts);
$this->assertConfigurableOptions('configurable', $childProducts);
$this->assertConfigurableLinks(
'configurable',
$this->getProductIds(array_merge($associatedProducts, array_keys($childProducts)))
);
}
/**
* @return array
*/
public function saveExistProductDataProvider(): array
{
return [
'added_new_option' => [
'child_products' => [
'simple_2' => [
'name' => 'simple_2',
'sku' => 'simple_2',
'price' => 100,
'weight' => '1',
'qty' => '200',
'attributes' => ['test_configurable' => 'Option 2'],
],
],
'associated_products' => ['simple_1'],
],
'added_new_option_and_delete_old' => [
'child_products' => [
'simple_2' => [
'name' => 'simple_2',
'sku' => 'simple_2',
'price' => 100,
'qty' => '100',
'attributes' => ['test_configurable' => 'Option 2'],
],
],
'associated_products' => [],
],
'delete_all_options' => [
'child_products' => [],
'associated_products' => [],
],
'added_new_attribute' => [
'child_products' => [
'simple_1_1' => [
'name' => 'simple_1_1',
'sku' => 'simple_1_1',
'price' => 100,
'weight' => '1',
'qty' => '200',
'attributes' => [
'test_configurable' => 'Option 1',
'test_configurable_2' => 'Option 1',
],
],
'simple_1_2' => [
'name' => 'simple_1_2',
'sku' => 'simple_1_2',
'price' => 100,
'weight' => '1',
'qty' => '200',
'attributes' => [
'test_configurable' => 'Option 1',
'test_configurable_2' => 'Option 2',
],
],
],
'associated_products' => [],
],
'added_new_attribute_and_delete_old' => [
'child_products' => [
'simple_2_1' => [
'name' => 'simple_2_1',
'sku' => 'simple_2_1',
'price' => 100,
'qty' => '100',
'attributes' => ['test_configurable_2' => 'Option 1'],
],
'simple_2_2' => [
'name' => 'simple_2_2',
'sku' => 'simple_2_2',
'price' => 100,
'qty' => '100',
'attributes' => ['test_configurable_2' => 'Option 2'],
],
],
'associated_products' => [],
],
];
}
/**
* Sets products data into request.
*
* @param array $childProducts
* @param array|null $associatedProducts
* @param int|null $mainProductId
* @return void
*/
private function serRequestParams(
array $childProducts,
?array $associatedProducts = [],
?int $mainProductId = null
): void {
$this->setVariationMatrix($childProducts);
$this->setAssociatedProducts($associatedProducts);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams(
[
'type' => Configurable::TYPE_CODE,
'set' => $this->getDefaultAttributeSetId(),
'id' => $mainProductId,
]
);
$this->getRequest()->setPostValue(
'product',
[
'attribute_set_id' => $this->getDefaultAttributeSetId(),
'name' => 'configurable',
'sku' => 'configurable',
'configurable_attributes_data' => $this->getConfigurableAttributesData($childProducts) ?: null,
]
);
}
/**
* Asserts product configurable links.
*
* @param string $sku
* @param array $associatedProductIds
* @return void
*/
private function assertConfigurableLinks(string $sku, array $associatedProductIds): void
{
$product = $this->productRepository->get($sku, false, null, true);
$this->assertEquals(
$associatedProductIds,
array_values($product->getExtensionAttributes()->getConfigurableProductLinks() ?: []),
'Product links are not available in the database'
);
}
/**
* Asserts product from registry configurable links.
*
* @param array $associatedProductIds
* @return void
*/
private function assertRegistryConfigurableLinks(array $associatedProductIds): void
{
$product = $this->registry->registry('current_product');
$this->assertNotNull($product);
$this->assertEquals(
$associatedProductIds,
array_values($product->getExtensionAttributes()->getConfigurableProductLinks() ?: []),
'Product links are not available in the registry'
);
}
/**
* Asserts child products data.
*
* @param array $childProducts
* @return void
*/
private function assertChildProducts(array $childProducts): void
{
foreach ($this->getProducts(array_column($childProducts, 'sku')) as $product) {
$expectedProduct = $childProducts[$product->getSku()];
$this->assertEquals($expectedProduct['price'], $product->getPrice());
if (!empty($expectedProduct['weight'])) {
$this->assertEquals($expectedProduct['weight'], (double)$product->getWeight());
$this->assertInstanceOf(Simple::class, $product->getTypeInstance());
} else {
$this->assertInstanceOf(Virtual::class, $product->getTypeInstance());
}
$this->assertEquals($expectedProduct['qty'], $product->getExtensionAttributes()->getStockItem()->getQty());
}
}
/**
* Asserts that configurable attributes present in product configurable option list.
*
* @param string $sku
* @param array $childProducts
* @return void
*/
private function assertConfigurableOptions(string $sku, array $childProducts): void
{
$configurableProduct = $this->productRepository->get($sku, false, null, true);
$options = $configurableProduct->getExtensionAttributes()->getConfigurableProductOptions();
if (empty($childProducts)) {
$this->assertNull($options);
} else {
foreach ($options as $option) {
$attribute = $this->getAttribute($option->getAttributeId());
foreach ($childProducts as $childProduct) {
$this->assertContains($attribute->getAttributeCode(), array_keys($childProduct['attributes']));
}
}
}
}
/**
* Sets configurable product params to request.
*
* @param array $childProducts
* @return void
*/
private function setVariationMatrix(array $childProducts): void
{
$matrix = $attributeIds = $configurableAttributes = [];
foreach ($childProducts as $product) {
foreach ($product['attributes'] as $attributeCode => $optionLabel) {
$attribute = $this->getAttribute($attributeCode);
$configurableAttributes[$attributeCode] = $attribute->getSource()->getOptionId($optionLabel);
$attributeIds[] = $attribute->getAttributeId();
}
$product['status'] = Status::STATUS_ENABLED;
$product['configurable_attribute'] = $this->jsonSerializer->serialize($configurableAttributes);
$product['newProduct'] = 1;
$product['variationKey'] = implode('-', array_values($configurableAttributes));
$matrix[] = $product;
}
$this->getRequest()->setPostValue(
[
'affect_configurable_product_attributes' => 1,
'attributes' => $attributeIds,
'new-variations-attribute-set-id' => $this->getDefaultAttributeSetId(),
'configurable-matrix-serialized' => $this->jsonSerializer->serialize($matrix),
]
);
}
/**
* Sets associated product ids param to request.
*
* @param array|null $associatedProducts
*/
private function setAssociatedProducts(?array $associatedProducts): void
{
if (!empty($associatedProducts)) {
$associatedProductIds = array_map(
function (ProductInterface $product) {
return $product->getId();
},
$this->getProducts($associatedProducts)
);
$this->getRequest()->setPostValue(
'associated_product_ids_serialized',
$this->jsonSerializer->serialize($associatedProductIds)
);
}
}
/**
* Returns product configurable attributes data.
*
* @param array $childProducts
* @return array
*/
private function getConfigurableAttributesData(array $childProducts): array
{
$result = [];
foreach ($childProducts as $product) {
foreach ($product['attributes'] as $attributeCode => $optionLabel) {
$attribute = $this->getAttribute($attributeCode);
$optionId = $attribute->getSource()->getOptionId($optionLabel);
if (empty($result[$attribute->getAttributeId()])) {
$result[$attribute->getAttributeId()] = [
'attribute_id' =>$attribute->getAttributeId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getAttributeCode(),
'position' => '0',
'values' => [
$optionId => [
'include' => '1',
'value_index' => $optionId,
],
],
];
} else {
$result[$attribute->getAttributeId()]['values'][$optionId] = [
'include' => '1',
'value_index' => $optionId,
];
}
}
}
return $result;
}
/**
* Retrieve default product attribute set id.
*
* @return int
*/
private function getDefaultAttributeSetId(): int
{
return (int)$this->eavConfig
->getEntityType(ProductAttributeInterface::ENTITY_TYPE_CODE)
->getDefaultAttributeSetId();
}
/**
* Retrieve configurable attribute instance.
*
* @param string $attributeCode
* @return ProductAttributeInterface
*/
private function getAttribute(string $attributeCode): ProductAttributeInterface
{
return $this->productAttributeRepository->get($attributeCode);
}
/**
* Returns products by sku list.
*
* @param array $skuList
* @return ProductInterface[]
*/
private function getProducts(array $skuList): array
{
$result = [];
foreach ($skuList as $sku) {
$result[] = $this->productRepository->get($sku);
}
return $result;
}
/**
* Returns product ids by sku list.
*
* @param array $skuList
* @return array
*/
private function getProductIds(array $skuList): array
{
$associatedProductIds = [];
foreach ($this->getProducts($skuList) as $product) {
$associatedProductIds[] = $product->getId();
}
return $associatedProductIds;
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test class for \Magento\Checkout\Controller\Cart
*/
namespace Magento\ConfigurableProduct\Controller;
use Magento\Framework\App\Request\Http as HttpRequest;
class CartTest extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* Test for \Magento\Checkout\Controller\Cart::configureAction() with configurable product
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testConfigureActionWithConfigurableProduct()
{
/** @var $session \Magento\Checkout\Model\Session */
$session = $this->_objectManager->create(\Magento\Checkout\Model\Session::class);
$quoteItem = $this->_getQuoteItemIdByProductId($session->getQuote(), 1);
$this->assertNotNull($quoteItem, 'Cannot get quote item for configurable product');
$this->dispatch(
'checkout/cart/configure/id/' . $quoteItem->getId() . '/product_id/' . $quoteItem->getProduct()->getId()
);
$response = $this->getResponse();
$this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//button[@type="submit" and @title="Update Cart"]',
$response->getBody()
),
'Response for configurable product doesn\'t contain "Update Cart" button'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//select[contains(@class,"super-attribute-select")]',
$response->getBody()
),
'Response for configurable product doesn\'t contain select for super attribute'
);
}
/**
* Gets \Magento\Quote\Model\Quote\Item from \Magento\Quote\Model\Quote by product id
*
* @param \Magento\Quote\Model\Quote $quote
* @param mixed $productId
* @return \Magento\Quote\Model\Quote\Item|null
*/
private function _getQuoteItemIdByProductId(\Magento\Quote\Model\Quote $quote, $productId)
{
/** @var $quoteItems \Magento\Quote\Model\Quote\Item[] */
$quoteItems = $quote->getAllItems();
foreach ($quoteItems as $quoteItem) {
if ($productId == $quoteItem->getProductId()) {
return $quoteItem;
}
}
return null;
}
/**
* Test for \Magento\Checkout\Controller\Cart\CouponPost::execute() with configurable product with last option
* Covers MAGETWO-60352
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product_last_variation.php
*/
public function testExecuteForConfigurableLastOption()
{
/** @var $session \Magento\Checkout\Model\Session */
$session = $this->_objectManager->create(\Magento\Checkout\Model\Session::class);
$quote = $session->getQuote();
$quote->setData('trigger_recollect', 1)->setTotalsCollectedFlag(true);
$inputData = [
'remove' => 0,
'coupon_code' => 'test'
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($inputData);
$this->dispatch(
'checkout/cart/couponPost/'
);
$this->assertSessionMessages(
$this->equalTo(['The coupon code &quot;test&quot; is not valid.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}