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,108 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Adminhtml\Product\Composite\Fieldset;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test Configurable block in composite product configuration layout
*
* @see \Magento\ConfigurableProduct\Block\Adminhtml\Product\Composite\Fieldset\Configurable
* @magentoAppArea adminhtml
*/
class ConfigurableTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var SerializerInterface */
private $serializer;
/** @var Configurable */
private $block;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Registry */
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->serializer = $this->objectManager->get(SerializerInterface::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Configurable::class);
$this->registry = $this->objectManager->get(Registry::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('product');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @return void
*/
public function testGetProduct(): void
{
$product = $this->productRepository->get('simple-1');
$this->registerProduct($product);
$blockProduct = $this->block->getProduct();
$this->assertSame($product, $blockProduct);
$this->assertEquals(
$product->getId(),
$blockProduct->getId(),
'The expected product is missing in the Configurable block!'
);
$this->assertNotNull($blockProduct->getTypeInstance()->getStoreFilter($blockProduct));
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php
* @return void
*/
public function testGetJsonConfig(): void
{
$product = $this->productRepository->get('configurable');
$this->registerProduct($product);
$config = $this->serializer->unserialize($this->block->getJsonConfig());
$this->assertTrue($config['disablePriceReload']);
$this->assertTrue($config['stablePrices']);
}
/**
* Register the product
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('product');
$this->registry->register('product', $product);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Variations\Config;
/**
* @magentoAppArea adminhtml
*/
class MatrixTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
const ATTRIBUTE_LABEL = 'New Attribute Label';
const ATTRIBUTE_POSITION = 42;
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetVariations()
{
$this->_objectManager->get(
\Magento\Framework\Registry::class
)->register(
'current_product',
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
)->load(1)
);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Framework\View\Element\Text::class,
'head'
);
/** @var $usedAttribute \Magento\Catalog\Model\Entity\Attribute */
$usedAttribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\Entity\Attribute::class
)->loadByCode(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Eav\Model\Config::class
)->getEntityType(
'catalog_product'
)->getId(),
'test_configurable'
);
$attributeOptions = $usedAttribute->getSource()->getAllOptions(false);
/** @var $block \Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Variations\Config\Matrix */
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
preg_replace('/Test$/', '', __CLASS__)
);
$variations = $block->getVariations();
foreach ($variations as &$variation) {
foreach ($variation as &$row) {
unset($row['price']);
}
}
$this->assertEquals(
[
[$usedAttribute->getId() => $attributeOptions[0]],
[$usedAttribute->getId() => $attributeOptions[1]],
],
$variations
);
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps;
use Magento\Backend\Model\Auth\Session;
use Magento\ConfigurableProduct\Block\DataProviders\PermissionsData;
use Magento\Framework\View\Layout;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\User;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
class AttributeValuesTest extends TestCase
{
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/restricted_admin_with_catalog_permissions.php
*/
public function testRestrictedUserNotAllowedToManageAttributes()
{
$user = Bootstrap::getObjectManager()->create(
User::class
)->loadByUsername(
'admincatalog_user'
);
/** @var $session Session */
$session = Bootstrap::getObjectManager()->get(
Session::class
);
$session->setUser($user);
/** @var $layout Layout */
$layout = Bootstrap::getObjectManager()->get(
LayoutInterface::class
);
/** @var \Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps\AttributeValues */
$block = $layout->createBlock(
AttributeValues::class,
'step2',
[
'data' => [
'config' => [
'form' => 'product_form.product_form',
'modal' => 'configurableModal',
'dataScope' => 'productFormConfigurable',
],
'permissions' => Bootstrap::getObjectManager()->get(PermissionsData::class)
]
]
);
$isAllowedToManageAttributes = $block->getPermissions()->isAllowedToManageAttributes();
$html = $block->toHtml();
$this->assertFalse($isAllowedToManageAttributes);
$this->assertStringNotContainsString('<button class="action-create-new action-tertiary"', $html);
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Block\Cart\Item\Renderer;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Block\Cart\Item\Renderer\Configurable as ConfigurableRenderer;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
/**
* Test \Magento\ConfigurableProduct\Block\Cart\Item\Renderer\Configurable block
*
* @magentoAppArea frontend
*/
class ConfigurableTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ConfigurableRenderer
*/
private $block;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)
->createBlock(ConfigurableRenderer::class);
}
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testGetProductPriceHtml()
{
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$configurableProduct = $productRepository->getById(1);
$layout = $this->objectManager->get(LayoutInterface::class);
$layout->createBlock(
\Magento\Framework\Pricing\Render::class,
'product.price.render.default',
[
'data' => [
'price_render_handle' => 'catalog_product_prices',
'use_link_for_as_low_as' => true
]
]
);
$this->block->setItem(
$this->block->getCheckoutSession()->getQuote()->getAllVisibleItems()[0]
);
$html = $this->block->getProductPriceHtml($configurableProduct);
$this->assertStringContainsString('<span class="price">$10.00</span>', $html);
}
}
@@ -0,0 +1,114 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\ProductList;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Block\Product\ProductList\AbstractLinksTest;
use Magento\Catalog\Block\Product\ProductList\Related;
/**
* Check the correct behavior of related products on the configurable product view page
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*/
class RelatedTest extends AbstractLinksTest
{
/**
* @var Related
*/
protected $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->layout->createBlock(Related::class);
$this->linkType = 'related';
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testRenderConfigurableWithLinkedProduct(): void
{
$this->linkProducts('configurable', ['simple2' => ['position' => 1]]);
$relatedProduct = $this->productRepository->get('simple2');
$this->block->setProduct($this->productRepository->get('configurable'));
$this->prepareBlock();
$html = $this->block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringContainsString($relatedProduct->getName(), $html);
$this->assertCount(1, $this->block->getItems());
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testRenderConfigurableWithLinkedProductOnChild(): void
{
$this->linkProducts('simple_10', ['simple2' => ['position' => 1]]);
$relatedProduct = $this->productRepository->get('simple2');
$this->block->setProduct($this->productRepository->get('configurable'));
$this->prepareBlock();
$html = $this->block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringNotContainsString($relatedProduct->getName(), $html);
$this->assertEmpty($this->block->getItems());
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testLinkedProductsPosition(): void
{
$this->linkProducts(
'configurable',
['wrong-simple' => ['position' => 3], 'simple-249' => ['position' => 2], 'simple-156' => ['position' => 1]]
);
$this->block->setProduct($this->productRepository->get('configurable'));
$this->assertEquals(
['simple-156', 'simple-249','wrong-simple'],
$this->getActualLinks($this->getLinkedItems()),
'Expected linked products do not match actual linked products!'
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetIdentities(): void
{
$this->linkProducts('configurable', ['simple2' => ['position = 1']]);
$relatedProduct = $this->productRepository->get('simple2');
$this->block->setProduct($this->productRepository->get('configurable'));
$this->prepareBlock();
$this->assertEquals(['cat_p_' . $relatedProduct->getId(), 'cat_p'], $this->block->getIdentities());
}
/**
* Returns linked products from block.
*
* @return ProductInterface[]
*/
protected function getLinkedItems(): array
{
return $this->block->getItems()->getItems();
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\ProductList;
use Magento\Catalog\Block\Product\ProductList\Upsell;
/**
* Check the correct behavior of up-sell products on the configurable product view page
*
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*/
class UpsellTest extends RelatedTest
{
/**
* @var Upsell
*/
protected $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->layout->createBlock(Upsell::class);
$this->linkType = 'upsell';
}
/**
* @inheritdoc
*/
protected function getLinkedItems(): array
{
return $this->block->getItems();
}
}
@@ -0,0 +1,111 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\CustomOptions;
use Magento\Catalog\Block\Product\View\Options\AbstractRenderCustomOptionsTest;
/**
* Test cases related to check that configurable product custom option renders as expected.
*
* @magentoAppArea frontend
*/
class RenderOptionsTest extends AbstractRenderCustomOptionsTest
{
/**
* Check that options from text group(field, area) render on configurable product as expected.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @dataProvider \Magento\TestFramework\ConfigurableProduct\Block\CustomOptions\TextGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromTextGroup(array $optionData, array $checkArray): void
{
$this->assertTextOptionRenderingOnProduct('Configurable product', $optionData, $checkArray);
}
/**
* Check that options from file group(file) render on configurable product as expected.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @dataProvider \Magento\TestFramework\ConfigurableProduct\Block\CustomOptions\FileGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromFileGroup(array $optionData, array $checkArray): void
{
$this->assertFileOptionRenderingOnProduct('Configurable product', $optionData, $checkArray);
}
/**
* Check that options from select group(drop-down, radio buttons, checkbox, multiple select) render
* on configurable product as expected.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @dataProvider \Magento\TestFramework\ConfigurableProduct\Block\CustomOptions\SelectGroupDataProvider::getData
*
* @param array $optionData
* @param array $optionValueData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromSelectGroup(
array $optionData,
array $optionValueData,
array $checkArray
): void {
$this->assertSelectOptionRenderingOnProduct('Configurable product', $optionData, $optionValueData, $checkArray);
}
/**
* Check that options from date group(date, date & time, time) render on configurable product as expected.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @dataProvider \Magento\TestFramework\ConfigurableProduct\Block\CustomOptions\DateGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromDateGroup(array $optionData, array $checkArray): void
{
$this->assertDateOptionRenderingOnProduct('Configurable product', $optionData, $checkArray);
}
/**
* @inheritdoc
*/
protected function getHandlesList(): array
{
return [
'default',
'catalog_product_view',
'catalog_product_view_type_configurable',
];
}
/**
* @inheritdoc
*/
protected function getMaxCharactersCssClass(): string
{
return 'class="character-counter';
}
/**
* @inheritdoc
*/
protected function getOptionsBlockName(): string
{
return 'product.info.options';
}
}
@@ -0,0 +1,274 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use PHPUnit\Framework\TestCase;
/**
* Check configurable product price displaying
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @magentoAppArea frontend
*/
class ConfigurableProductPriceTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Page */
private $page;
/** @var ProductCustomOptionInterface */
private $productCustomOption;
/** @var SerializerInterface */
private $json;
/** @var StoreManagerInterface */
private $storeManager;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->page = $this->objectManager->get(PageFactory::class)->create();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->productCustomOption = $this->objectManager->get(ProductCustomOptionInterface::class);
$this->json = $this->objectManager->get(SerializerInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('product');
$this->registry->unregister('current_product');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @return void
*/
public function testConfigurablePrice(): void
{
$this->assertPrice('configurable', 10.00);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_price_on_second_website.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testConfigurablePriceOnSecondWebsite(): void
{
$this->executeInStoreContext->execute('fixture_second_store', [$this, 'assertPrice'], 'configurable', 10.00);
$this->resetPageLayout();
$this->assertAmount('configurable', 150.00);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_disable_first_child.php
*
* @return void
*/
public function testConfigurablePriceWithDisabledFirstChild(): void
{
$this->assertAmount('configurable', 20.00);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_zero_qty_first_child.php
*
* @return void
*/
public function testConfigurablePriceWithOutOfStockFirstChild(): void
{
$this->assertAmount('configurable', 20.00);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDataFixture Magento/CatalogRule/_files/rule_apply_as_percentage_of_original_not_logged_user.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testConfigurablePriceWithCatalogRule(): void
{
$this->assertPrice('configurable', 9.00);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_custom_option_type_text.php
*
* @return void
*/
public function testConfigurablePriceWithCustomOption(): void
{
$product = $this->getProduct('configurable');
$this->registerProduct($product);
$this->preparePageLayout();
$customOptionsBlock = $this->page->getLayout()
->getChildBlock('product.info.options.wrapper', 'product_options');
$option = $product->getOptions()[0] ?? null;
$this->assertNotNull($option);
$this->assertJsonConfig($customOptionsBlock->getJsonConfig(), '15', (int)$option->getId());
$optionBlock = $customOptionsBlock->getChildBlock($this->productCustomOption->getGroupByType('area'));
$optionPrice = $optionBlock->setProduct($product)->setOption($option)->getFormattedPrice();
$this->assertEquals('+$15.00', preg_replace('/[\n\s]/', '', strip_tags($optionPrice)));
}
/**
* Register the product.
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('product');
$this->registry->register('product', $product);
$this->registry->unregister('current_product');
$this->registry->register('current_product', $product);
}
/**
* Prepare configurable product page.
*
* @return void
*/
private function preparePageLayout(): void
{
$this->page->addHandle([
'default',
'catalog_product_view',
'catalog_product_view_type_configurable',
]);
$this->page->getLayout()->generateXml();
}
/**
* Reset layout page to get new block html.
*
* @return void
*/
private function resetPageLayout(): void
{
$this->page = $this->objectManager->get(PageFactory::class)->create();
}
/**
* Process view product final price block html.
*
* @param string $sku
* @return string
*/
private function processPriceView(string $sku): string
{
$product = $this->getProduct($sku);
$this->registerProduct($product);
$this->preparePageLayout();
return $this->page->getLayout()->getBlock('product.price.final')->toHtml();
}
/**
* Assert that html contain price label and expected final price amount.
*
* @param string $sku
* @param float $expectedPrice
* @return void
*/
public function assertPrice(string $sku, float $expectedPrice): void
{
$priceBlockHtml = $this->processPriceView($sku);
$regexp = '/<span class="price-label">As low as<\/span>.*';
$regexp .= '<span.*data-price-amount="%s".*<span class="price">\$%.2f<\/span><\/span>/';
$this->assertMatchesRegularExpression(
sprintf($regexp, round($expectedPrice, 2), $expectedPrice),
preg_replace('/[\n\r]/', '', $priceBlockHtml)
);
}
/**
* Assert custom option price json config.
*
* @param string $config
* @param string $expectedPrice
* @param int $optionId
* @return void
*/
private function assertJsonConfig(string $config, string $expectedPrice, int $optionId): void
{
$price = $this->json->unserialize($config)[$optionId]['prices']['finalPrice']['amount'] ?? null;
$this->assertNotNull($price);
$this->assertEquals($expectedPrice, $price);
}
/**
* Loads product by sku.s
*
* @param string $sku
* @return ProductInterface
*/
private function getProduct(string $sku): ProductInterface
{
return $this->productRepository->get($sku, false, $this->storeManager->getStore()->getId(), true);
}
/**
* Assert that html contain expected final price amount.
*
* @param string $sku
* @param float $expectedPrice
* @return void
*/
public function assertAmount(string $sku, float $expectedPrice): void
{
$priceBlockHtml = $this->processPriceView($sku);
$regexp = '/<span\s+class="price">\$%.2f<\/span>/';
$this->assertMatchesRegularExpression(
sprintf($regexp, $expectedPrice),
$priceBlockHtml
);
}
}
@@ -0,0 +1,301 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\Product as HelperProduct;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute as ConfigurableAttribute;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test class to check configurable product view behaviour.
*
* @see \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigurableTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var SearchCriteriaBuilder
*/
private $searchBuilder;
/**
* @var Configurable
*/
private $block;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var ProductInterface
*/
private $product;
/**
* @var HelperProduct
*/
private $helperProduct;
/** @var DataObjectFactory */
private $dataObjectFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->serializer = $this->objectManager->get(SerializerInterface::class);
$this->searchBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->productResource = $this->objectManager->create(ProductResource::class);
$this->product = $this->productRepository->get('configurable');
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Configurable::class);
$this->block->setProduct($this->product);
$this->helperProduct = $this->objectManager->get(HelperProduct::class);
$this->dataObjectFactory = $this->objectManager->get(DataObjectFactory::class);
}
/**
* @return void
*/
public function testGetAllowAttributes(): void
{
$attributes = $this->block->getAllowAttributes();
$this->assertInstanceOf(Collection::class, $attributes);
$this->assertGreaterThanOrEqual(1, $attributes->getSize());
}
/**
* @return void
*/
public function testHasOptions(): void
{
$this->assertTrue($this->block->hasOptions());
}
/**
* @return void
*/
public function testGetAllowProducts(): void
{
$products = $this->block->getAllowProducts();
$this->assertGreaterThanOrEqual(2, count($products));
foreach ($products as $product) {
$this->assertInstanceOf(ProductInterface::class, $product);
}
}
/**
* Verify configurable option not assigned to current website won't be visible.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_two_websites.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*
* @return void
*/
public function testGetAllowProductsNonDefaultWebsite(): void
{
// Set current website to non-default.
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$storeManager->setCurrentStore('fixture_second_store');
// Un-assign simple product from non-default website.
$simple = $this->productRepository->get('simple_Option_1');
$simple->setWebsiteIds([1]);
$this->productRepository->save($simple);
// Verify only one configurable option will be visible.
$products = $this->block->getAllowProducts();
$this->assertEquals(1, count($products));
}
/**
* @return void
*/
public function testGetJsonConfig(): void
{
$config = $this->serializer->unserialize($this->block->getJsonConfig());
$this->assertNotEmpty($config);
$this->assertArrayHasKey('productId', $config);
$this->assertEquals(1, $config['productId']);
$this->assertArrayHasKey('attributes', $config);
$this->assertArrayHasKey('template', $config);
$this->assertArrayHasKey('prices', $config);
$this->assertArrayHasKey('basePrice', $config['prices']);
$this->assertArrayHasKey('images', $config);
$this->assertCount(0, $config['images']);
}
/**
* @return void
*/
public function testGetJsonConfigWithPreconfiguredValues(): void
{
/** @var ConfigurableAttribute $attribute */
$attribute = $this->product->getExtensionAttributes()->getConfigurableProductOptions()[0];
$expectedAttributeValue = [
$attribute->getAttributeId() => $attribute->getOptions()[0]['value_index'],
];
/** @var DataObject $request */
$buyRequest = $this->dataObjectFactory->create();
$buyRequest->setData([
'qty' => 1,
'super_attribute' => $expectedAttributeValue,
]);
$this->helperProduct->prepareProductOptions($this->product, $buyRequest);
$config = $this->serializer->unserialize($this->block->getJsonConfig());
$this->assertArrayHasKey('defaultValues', $config);
$this->assertEquals($expectedAttributeValue, $config['defaultValues']);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_child_products_with_images.php
* @return void
*/
public function testGetJsonConfigWithChildProductsImages(): void
{
$config = $this->serializer->unserialize($this->block->getJsonConfig());
$this->assertNotEmpty($config);
$this->assertArrayHasKey('images', $config);
$this->assertCount(2, $config['images']);
$products = $this->getProducts(
$this->product->getExtensionAttributes()->getConfigurableProductLinks()
);
$i = 0;
foreach ($products as $simpleProduct) {
$i++;
$resultImage = reset($config['images'][$simpleProduct->getId()]);
$this->assertStringContainsString($simpleProduct->getImage(), $resultImage['thumb']);
$this->assertStringContainsString($simpleProduct->getImage(), $resultImage['img']);
$this->assertStringContainsString($simpleProduct->getImage(), $resultImage['full']);
$this->assertTrue($resultImage['isMain']);
$this->assertEquals('image', $resultImage['type']);
$this->assertEquals($i, $resultImage['position']);
$this->assertNull($resultImage['videoUrl']);
}
}
/**
* @dataProvider expectedDataProvider
*
* @param string $label
* @param array $expectedConfig
* @return void
*/
public function testConfigurableProductView(string $label, array $expectedConfig): void
{
$attributes = $this->block->decorateArray($this->block->getAllowAttributes());
$this->assertCount(1, $attributes);
$attribute = $attributes->getFirstItem();
$this->assertEquals($label, $attribute->getLabel());
$config = $this->serializer->unserialize($this->block->getJsonConfig())['attributes'] ?? null;
$this->assertNotNull($config);
$this->assertConfig(reset($config), $expectedConfig);
}
/**
* @return array
*/
public function expectedDataProvider(): array
{
return [
[
'label' => 'Test Configurable',
'config_data' => [
'label' => 'Test Configurable',
'options' => [
[
'label' => 'Option 1',
'sku' => 'simple_10',
],
[
'label' => 'Option 2',
'sku' => 'simple_20',
],
],
],
],
];
}
/**
* Assert that data was generated
*
* @param array $data
* @param array $expectedData
* @return void
*/
private function assertConfig(array $data, array $expectedData): void
{
$this->assertEquals($expectedData['label'], $data['label']);
$skus = array_column($expectedData['options'], 'sku');
$idBySkuMap = $this->productResource->getProductsIdsBySkus($skus);
foreach ($expectedData['options'] as &$option) {
$sku = $option['sku'];
unset($option['sku']);
$option['products'] = [$idBySkuMap[$sku]];
foreach ($data['options'] as $actualOption) {
if ($option['label'] === $actualOption['label']) {
unset($actualOption['id']);
$this->assertEquals($option, $actualOption);
}
}
}
}
/**
* Returns products by ids list.
*
* @param array $productIds
* @return ProductInterface[]
*/
private function getProducts(array $productIds): array
{
$criteria = $this->searchBuilder->addFilter('entity_id', $productIds, 'in')
->create();
return $this->productRepository->getList($criteria)->getItems();
}
}
@@ -0,0 +1,219 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use PHPUnit\Framework\TestCase;
/**
* Class checks configurable product displaying on category view page
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @magentoAppArea frontend
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_out_of_stock_children.php
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigurableViewOnCategoryPageTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var Page */
private $page;
/** @var Registry */
private $registry;
/** @var StoreManagerInterface */
private $storeManager;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->page = $this->objectManager->get(PageFactory::class)->create();
$this->registry = $this->objectManager->get(Registry::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_category');
parent::tearDown();
}
/**
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
*
* @return void
*/
public function testOutOfStockProductWithEnabledConfigView(): void
{
$this->preparePageLayout();
$this->assertCollectionSize(1, $this->getListingBlock()->getLoadedProductCollection());
}
/**
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 0
*
* @return void
*/
public function testOutOfStockProductWithDisabledConfigView(): void
{
$this->preparePageLayout();
$this->assertCollectionSize(0, $this->getListingBlock()->getLoadedProductCollection());
}
/**
* @magentoDataFixture Magento/Catalog/_files/reindex_catalog_inventory_stock.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_category.php
*
* @return void
*/
public function testCheckConfigurablePrice(): void
{
$this->assertProductPrice('configurable', 'As low as $10.00');
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_price_on_second_website.php
*
* @return void
*/
public function testCheckConfigurablePriceOnSecondWebsite(): void
{
$this->executeInStoreContext->execute(
'fixture_second_store',
[$this, 'assertProductPrice'],
'configurable',
__('As low as') . ' $10.00'
);
$this->resetPageLayout();
$this->assertProductPrice('configurable', '$150.00');
}
/**
* Checks product price.
*
* @param string $sku
* @param string $priceString
* @return void
*/
public function assertProductPrice(string $sku, string $priceString): void
{
$this->preparePageLayout();
$this->assertCollectionSize(1, $this->getListingBlock()->getLoadedProductCollection());
$priceHtml = $this->getListingBlock()->getProductPrice($this->getProduct($sku));
$this->assertEquals($priceString, $this->clearPriceHtml($priceHtml));
}
/**
* Check collection size
*
* @param int $expectedSize
* @param AbstractCollection $collection
* @return void
*/
private function assertCollectionSize(int $expectedSize, AbstractCollection $collection): void
{
$this->assertEquals($expectedSize, $collection->getSize());
$this->assertCount($expectedSize, $collection->getItems());
}
/**
* Prepare category page.
*
* @return void
*/
private function preparePageLayout(): void
{
$this->registry->unregister('current_category');
$this->registry->register(
'current_category',
$this->categoryRepository->get(333, $this->storeManager->getStore()->getId())
);
$this->page->addHandle(['default', 'catalog_category_view']);
$this->page->getLayout()->generateXml();
}
/**
* Reset layout page to get new block html.
*
* @return void
*/
private function resetPageLayout(): void
{
$this->page = $this->objectManager->get(PageFactory::class)->create();
}
/**
* Removes html tags and spaces from price html string.
*
* @param string $priceHtml
* @return string
*/
private function clearPriceHtml(string $priceHtml): string
{
return trim(preg_replace('/\s+/', ' ', strip_tags($priceHtml)));
}
/**
* Returns product list block.
*
* @return null|ListProduct
*/
private function getListingBlock(): ?ListProduct
{
$block = $this->page->getLayout()->getBlock('category.products.list');
return $block ? $block : null;
}
/**
* Loads product by sku.
*
* @param string $sku
* @return ProductInterface
*/
private function getProduct(string $sku): ProductInterface
{
return $this->productRepository->get($sku, false, $this->storeManager->getStore()->getId(), true);
}
}
@@ -0,0 +1,290 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\CatalogInventory\Api\Data\StockStatusInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class checks configurable product view with out of stock children
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigurableViewOnProductPageTest extends TestCase
{
private const STOCK_DISPLAY_TEMPLATE = 'Magento_Catalog::product/view/type/default.phtml';
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var LayoutInterface */
private $layout;
/** @var Configurable */
private $block;
/** @var SerializerInterface */
private $json;
/** @var ProductResource */
private $productResource;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Configurable::class);
$this->json = $this->objectManager->get(SerializerInterface::class);
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* @dataProvider oneChildNotVisibleDataProvider
* @magentoDbIsolation disabled
*
* @param string $sku
* @param array $data
* @param array $expectedData
* @return void
*/
public function testOneChildNotVisible(string $sku, array $data, array $expectedData): void
{
$configurableProduct = $this->prepareConfigurableProduct($sku, $data);
$result = $this->renderStockBlock($configurableProduct);
$this->performAsserts($result, $expectedData);
}
/**
* @return array
*/
public function oneChildNotVisibleDataProvider(): array
{
return [
'one_child_out_of_stock' => [
'sku' => 'simple_10',
'data' => [
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_OUT_OF_STOCK,
],
],
'expected_data' => [
'stock_status' => 'In stock',
'options' => [
[
'label' => 'Option 2',
'product' => 'simple_20',
],
],
],
],
'one_child_disabled' => [
'sku' => 'simple_10',
'data' => [
'status' => Status::STATUS_DISABLED,
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_IN_STOCK,
],
],
'expected_data' => [
'stock_status' => 'In stock',
'options' => [
[
'label' => 'Option 2',
'product' => 'simple_20',
],
],
],
],
];
}
/**
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
*
* @dataProvider oneChildNotVisibleDataProviderWithEnabledConfig
*
* @param string $sku
* @param array $data
* @param array $expectedData
* @return void
*/
public function testOneChildNotVisibleWithEnabledShowOutOfStockProducts(
string $sku,
array $data,
array $expectedData
): void {
$configurableProduct = $this->prepareConfigurableProduct($sku, $data);
$result = $this->renderStockBlock($configurableProduct);
$this->performAsserts($result, $expectedData);
}
/**
* @return array
*/
public function oneChildNotVisibleDataProviderWithEnabledConfig(): array
{
return [
'one_child_out_of_stock' => [
'sku' => 'simple_10',
'data' => [
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_OUT_OF_STOCK,
],
],
'expected_data' => [
'stock_status' => 'In stock',
'options' => [
[
'label' => 'Option 2',
'product' => 'simple_20'
],
[
'label' => 'Option 1',
'product' => 'simple_10',
],
],
],
],
'one_child_disabled' => [
'sku' => 'simple_10',
'data' => [
'status' => Status::STATUS_DISABLED,
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_IN_STOCK,
],
],
'expected_data' => [
'stock_status' => 'In stock',
'options' => [
[
'label' => 'Option 2',
'product' => 'simple_20',
],
],
],
],
];
}
/**
* Update product with data
*
* @param array $sku
* @param array $data
* @return void
*/
private function updateProduct(string $sku, array $data): void
{
$currentStore = $this->storeManager->getStore();
try {
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
$product = $this->productRepository->get($sku);
$product->addData($data);
$this->productRepository->save($product);
} finally {
$this->storeManager->setCurrentStore($currentStore);
}
}
/**
* Check attribute options
*
* @param array $actualData
* @param array $expectedData
* @return void
*/
private function assertConfig(array $actualData, array $expectedData): void
{
$this->assertCount(count($expectedData), $actualData['options_data'], 'Redundant options were loaded');
$sku = array_column($expectedData, 'product');
$idBySkuMapping = $this->productResource->getProductsIdsBySkus($sku);
foreach ($expectedData as $expectedOption) {
$expectedId = $idBySkuMapping[$expectedOption['product']];
$itemToCheck = $actualData['options_data'][$expectedId] ?? null;
$this->assertNotNull($itemToCheck);
foreach ($actualData['attributes']['options'] as $actualAttributeDataItem) {
if ($actualAttributeDataItem['id'] === reset($itemToCheck)) {
$this->assertEquals($expectedOption['label'], $actualAttributeDataItem['label']);
}
}
}
}
/**
* Render stock block
*
* @param ProductInterface $configurableProduct
* @return string
*/
private function renderStockBlock(ProductInterface $configurableProduct): string
{
$this->block->setProduct($configurableProduct);
$this->block->setTemplate(self::STOCK_DISPLAY_TEMPLATE);
return $this->block->toHtml();
}
/**
* Perform test asserts
*
* @param string $result
* @param array $expectedData
* @return void
*/
private function performAsserts(string $result, array $expectedData): void
{
$this->assertEquals((string)__($expectedData['stock_status']), trim(strip_tags($result)));
$config = $this->json->unserialize($this->block->getJsonConfig());
$dataToCheck = ['attributes' => reset($config['attributes']), 'options_data' => $config['index']];
$this->assertConfig($dataToCheck, $expectedData['options']);
}
/**
* Prepare configurable product with children to test
*
* @param string $sku
* @param array $data
* @return ProductInterface
*/
private function prepareConfigurableProduct(string $sku, array $data): ProductInterface
{
$this->updateProduct($sku, $data);
return $this->productRepository->get('configurable', false, null, true);
}
}
@@ -0,0 +1,258 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use PHPUnit\Framework\TestCase;
/**
* Class check configurable product options displaying per stores
*
* @magentoDbIsolation disabled
*/
class MultiStoreConfigurableViewOnProductPageTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var StoreManagerInterface */
private $storeManager;
/** @var LayoutInterface */
private $layout;
/** @var SerializerInterface */
private $serializer;
/** @var ProductResource */
private $productResource;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->serializer = $this->objectManager->get(SerializerInterface::class);
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_different_option_labeles_per_stores.php
*
* @dataProvider expectedLabelsDataProvider
*
* @param array $expectedStoreData
* @param array $expectedSecondStoreData
* @return void
*/
public function testMultiStoreLabelView(array $expectedStoreData, array $expectedSecondStoreData): void
{
$this->executeInStoreContext->execute('default', [$this, 'assertProductLabel'], $expectedStoreData);
$this->executeInStoreContext->execute('fixturestore', [$this, 'assertProductLabel'], $expectedSecondStoreData);
}
/**
* @return array
*/
public function expectedLabelsDataProvider(): array
{
return [
[
'options_first_store' => [
'simple_option_1_default_store' => [
'label' => 'Option 1 Default Store',
],
'simple_option_2_default_store' => [
'label' => 'Option 2 Default Store',
],
'simple_option_3_default_store' => [
'label' => 'Option 3 Default Store',
],
],
'options_second_store' => [
'simple_option_1_default_store' => [
'label' => 'Option 1 Second Store',
],
'simple_option_2_default_store' => [
'label' => 'Option 2 Second Store',
],
'simple_option_3_default_store' => [
'label' => 'Option 3 Second Store',
],
],
],
];
}
/**
* Assert configurable product labels config
*
* @param $expectedStoreData
* @return void
*/
public function assertProductLabel($expectedStoreData): void
{
$product = $this->productRepository->get('configurable', false, null, true);
$config = $this->getBlockConfig($product)['attributes'] ?? null;
$this->assertNotNull($config);
$this->assertAttributeConfig($expectedStoreData, reset($config));
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_two_websites.php
*
* @dataProvider expectedProductDataProvider
*
* @param array $expectedProducts
* @param array $expectedSecondStoreProducts
* @return void
*/
public function testMultiStoreOptionsView(array $expectedProducts, array $expectedSecondStoreProducts): void
{
$this->prepareConfigurableProduct('configurable', 'fixture_second_store');
$this->executeInStoreContext->execute('default', [$this, 'assertProductConfig'], $expectedProducts);
$this->executeInStoreContext->execute(
'fixture_second_store',
[$this, 'assertProductConfig'],
$expectedSecondStoreProducts
);
}
/**
* @return array
*/
public function expectedProductDataProvider(): array
{
return [
[
'expected_store_products' => ['simple_option_1', 'simple_option_2'],
'expected_second_store_products' => ['simple_option_2'],
],
];
}
/**
* Assert configurable product config
*
* @param $expectedProducts
* @return void
*/
public function assertProductConfig($expectedProducts): void
{
$product = $this->productRepository->get('configurable', false, null, true);
$config = $this->getBlockConfig($product)['index'] ?? null;
$this->assertNotNull($config);
$this->assertProducts($expectedProducts, $config);
}
/**
* Prepare configurable product to test
*
* @param string $sku
* @param string $storeCode
* @return void
*/
private function prepareConfigurableProduct(string $sku, string $storeCode): void
{
$product = $this->productRepository->get($sku, false, null, true);
$productToUpdate = $product->getTypeInstance()->getUsedProductCollection($product)
->addStoreFilter($storeCode)
->setPageSize(1)
->getFirstItem();
$this->assertNotEmpty($productToUpdate->getData(), 'Configurable product does not have a child');
$this->executeInStoreContext->execute($storeCode, [$this, 'setProductDisabled'], $productToUpdate);
}
/**
* Assert product options display per stores
*
* @param array $expectedProducts
* @param array $config
* @return void
*/
private function assertProducts(array $expectedProducts, array $config): void
{
$this->assertCount(count($expectedProducts), $config);
$idsBySkus = $this->productResource->getProductsIdsBySkus($expectedProducts);
foreach ($idsBySkus as $productId) {
$this->assertArrayHasKey($productId, $config);
}
}
/**
* Set product status attribute to disabled
*
* @param ProductInterface $product
* @param string $storeCode
* @return void
*/
public function setProductDisabled(ProductInterface $product): void
{
$product->setStatus(Status::STATUS_DISABLED);
$this->productRepository->save($product);
}
/**
* Get block config
*
* @param ProductInterface $product
* @return array
*/
private function getBlockConfig(ProductInterface $product): array
{
$block = $this->layout->createBlock(Configurable::class);
$block->setProduct($product);
return $this->serializer->unserialize($block->getJsonConfig());
}
/**
* Assert configurable product config
*
* @param array $expectedData
* @param array $actualOptions
* @return void
*/
private function assertAttributeConfig(array $expectedData, array $actualOptions): void
{
$skus = array_keys($expectedData);
$idBySkuMap = $this->productResource->getProductsIdsBySkus($skus);
array_walk($actualOptions['options'], function (&$option) {
unset($option['id']);
});
foreach ($expectedData as $sku => &$option) {
$option['products'] = [$idBySkuMap[$sku]];
}
$this->assertEquals(array_values($expectedData), $actualOptions['options']);
}
}
@@ -0,0 +1,145 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Block\Product\View\Type;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\View;
use Magento\Catalog\Model\Product\Visibility;
use Magento\ConfigurableProduct\Helper\Data;
use Magento\ConfigurableProduct\Model\ConfigurableAttributeData;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\Result\Page;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Test cases related to render configurable options.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class RenderConfigurableOptionsTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var Data
*/
private $configurableHelper;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ConfigurableAttributeData
*/
private $configurableAttributeData;
/**
* @var Registry
*/
private $registry;
/**
* @var Page
*/
private $page;
/**
* @var Json
*/
private $json;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->configurableHelper = $this->objectManager->get(Data::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->configurableAttributeData = $this->objectManager->get(ConfigurableAttributeData::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->page = $this->objectManager->create(Page::class);
$this->json = $this->objectManager->get(Json::class);
parent::setUp();
}
/**
* Assert that all configurable options was rendered correctly if one of
* child product is visible on catalog\search.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
*
* @return void
*/
public function testRenderConfigurableOptionsBlockWithOneVisibleOption(): void
{
$configurableProduct = $this->productRepository->get('Configurable product');
$childProduct = $this->productRepository->get('Simple option 1');
$childProduct->setVisibility(Visibility::VISIBILITY_BOTH);
$this->productRepository->save($childProduct);
$allProducts = $configurableProduct->getTypeInstance()->getUsedProducts($configurableProduct, null);
$options = $this->configurableHelper->getOptions($configurableProduct, $allProducts);
$confAttrData = $this->configurableAttributeData->getAttributesData($configurableProduct, $options);
$attributesJson = str_replace(
['[', ']'],
['\[', '\]'],
$this->json->serialize($confAttrData['attributes'])
);
$optionsHtml = $this->getConfigurableOptionsHtml('Configurable product');
$this->assertMatchesRegularExpression("/\"spConfig\": {\"attributes\":{$attributesJson}/", $optionsHtml);
}
/**
* Render configurable options block.
*
* @param string $configurableSku
* @return string
*/
private function getConfigurableOptionsHtml(string $configurableSku): string
{
$product = $this->productRepository->get($configurableSku);
$this->registry->unregister('product');
$this->registry->register('product', $product);
$optionsBlock = $this->getOptionsWrapperBlockWithOnlyConfigurableBlock();
$optionHtml = $optionsBlock->toHtml();
$this->registry->unregister('product');
return $optionHtml;
}
/**
* Get options wrapper without extra blocks(only configurable child block).
*
* @return View
*/
private function getOptionsWrapperBlockWithOnlyConfigurableBlock(): View
{
$this->page->addHandle([
'default',
'catalog_product_view',
'catalog_product_view_type_configurable',
]);
$this->page->getLayout()->generateXml();
/** @var View $productInfoOptionsWrapper */
$productInfoOptionsWrapper = $this->page->getLayout()->getBlock('product.info.options.wrapper');
$productInfoOptionsWrapper->unsetChild('product_options');
$productInfoOptionsWrapper->unsetChild('html_calendar');
return $productInfoOptionsWrapper;
}
}