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,236 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model\Category;
use Magento\Catalog\Model\Category;
/**
* @magentoDataFixture Magento/Catalog/_files/indexer_catalog_category.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
* @magentoDbIsolation disabled
*/
class ProductIndexerTest extends \PHPUnit\Framework\TestCase
{
const DEFAULT_ROOT_CATEGORY = 2;
/**
* @var \Magento\Framework\Indexer\IndexerInterface
*/
private $indexer;
/**
* @var \Magento\Catalog\Model\ResourceModel\Product
*/
private $productResource;
/**
* @var \Magento\Catalog\Model\ProductRepository
*/
private $productRepository;
/**
* @var \Magento\Catalog\Model\CategoryRepository
*/
private $categoryRepository;
protected function setUp(): void
{
$this->indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Indexer\Model\Indexer::class
);
$this->indexer->load('catalog_category_product');
$this->productResource = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\ResourceModel\Product::class
);
$this->productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\ProductRepository::class
);
$this->categoryRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\CategoryRepository::class
);
}
/**
* @magentoAppArea adminhtml
*/
public function testReindex()
{
$categories = $this->getCategories();
/** @var Category $categoryFourth */
$categoryFourth = end($categories);
/** @var \Magento\Catalog\Model\Product $configurableProduct */
$configurableProduct = $this->productRepository->get('configurable');
$configurableProduct->setCategoryIds([$categoryFourth->getId()]);
$this->productRepository->save($configurableProduct);
/** @var Category $categoryThird */
$categoryThird = $categories[2];
$categoryThird->setIsAnchor(true);
$this->categoryRepository->save($categoryThird);
$this->indexer->reindexAll();
$categories = [self::DEFAULT_ROOT_CATEGORY, $categoryThird->getId(), $categoryFourth->getId()];
foreach ($categories as $categoryId) {
$this->assertTrue((bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryId));
}
$this->assertTrue(
(bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryThird->getParentId())
);
}
/**
* @magentoAppArea adminhtml
*/
public function testCategoryMove()
{
$categories = $this->getCategories();
/** @var Category $categoryFourth */
$categoryFourth = end($categories);
$configurableProduct = $this->productRepository->get('configurable');
$configurableProduct->setCategoryIds([$categoryFourth->getId()]);
$this->productRepository->save($configurableProduct);
/** @var Category $categorySecond */
$categorySecond = $categories[1];
$categorySecond->setIsAnchor(true);
$this->categoryRepository->save($categorySecond);
/** @var Category $categoryThird */
$categoryThird = $categories[2];
$categoryThird->setIsAnchor(true);
$this->categoryRepository->save($categoryThird);
$this->indexer->reindexAll();
/**
* Move category from $categoryThird to $categorySecond
*/
$categoryFourth->move($categorySecond->getId(), null);
$categories = [self::DEFAULT_ROOT_CATEGORY, $categorySecond->getId(), $categoryFourth->getId()];
foreach ($categories as $categoryId) {
$this->assertTrue((bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryId));
}
$this->assertFalse(
(bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryThird->getId())
);
}
/**
* @magentoAppArea adminhtml
* @depends testReindex
*/
public function testCategoryDelete()
{
$categories = $this->getCategories();
$configurableProduct = $this->productRepository->get('configurable');
/** @var Category $categoryFourth */
$categoryFourth = end($categories);
$this->categoryRepository->delete($categoryFourth);
/** @var Category $categorySecond */
$categorySecond = $categories[1];
$categories = [$categorySecond->getId(), $categoryFourth->getId()];
foreach ($categories as $categoryId) {
$this->assertFalse((bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryId));
}
$this->assertTrue(
(bool)$this->productResource->canBeShowInCategory(
$configurableProduct,
self::DEFAULT_ROOT_CATEGORY
)
);
}
/**
* @magentoAppArea adminhtml
*/
public function testCategoryCreate()
{
$this->testReindex();
$categories = $this->getCategories();
$configurableProduct = $this->productRepository->get('configurable');
/** @var Category $categorySecond */
$categorySecond = $categories[1];
$categorySecond->setIsAnchor(0);
$this->categoryRepository->save($categorySecond);
/** @var Category $categoryFourth */
$categoryFourth = end($categories);
/** @var Category $categorySixth */
$categorySixth = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Category::class
);
$categorySixth->setName(
'Category 6'
)->setPath(
$categoryFourth->getPath()
)->setAvailableSortBy(
'name'
)->setDefaultSortBy(
'name'
)->setIsActive(
true
);
$this->categoryRepository->save($categorySixth);
$configurableProduct->setCategoryIds([$categorySixth->getId()]);
$configurableProduct->save();
$categories = [self::DEFAULT_ROOT_CATEGORY, $categorySixth->getId(), $categoryFourth->getId()];
foreach ($categories as $categoryId) {
$this->assertTrue((bool)$this->productResource->canBeShowInCategory($configurableProduct, $categoryId));
}
$this->assertFalse(
(bool)$this->productResource->canBeShowInCategory($configurableProduct, $categorySecond->getId())
);
}
/**
* @return Category[]
*/
private function getCategories()
{
/** @var Category $category */
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Category::class
);
$result = $category->getCollection()->addAttributeToSelect('name')->getItems();
$result = array_slice($result, 2);
return array_slice($result, 0, 4);
}
/**
* @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,282 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Model\UrlRewrite as UrlRewriteItem;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\TestCase;
/**
* Test cases related to check that URL rewrite has created or not.
*/
class FindByUrlRewriteTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManger;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var UrlRewriteCollectionFactory
*/
private $urlRewriteCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManger = Bootstrap::getObjectManager();
$this->productResource = $this->objectManger->get(ProductResource::class);
$this->productRepository = $this->objectManger->get(ProductRepositoryInterface::class);
$this->urlRewriteCollectionFactory = $this->objectManger->get(UrlRewriteCollectionFactory::class);
parent::setUp();
}
/**
* Assert that product is available by URL rewrite with different visibility.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @dataProvider visibilityWithExpectedResultDataProvider
* @magentoDbIsolation enabled
*
* @param array $productsData
* @return void
*/
public function testCheckIsUrlRewriteForChildrenProductsHasCreated(array $productsData): void
{
$this->checkConfigurableUrlRewriteWasCreated();
$this->updateProductsVisibility($productsData);
$productIdsBySkus = $this->getProductIdsBySkus($productsData);
$urlRewritesCollection = $this->getUrlRewritesCollectionByProductIds($productIdsBySkus);
$expectedCount = 0;
foreach ($productsData as $productData) {
$productId = $productIdsBySkus[$productData['sku']];
/** @var UrlRewriteItem $urlRewrite */
$urlRewrite = $urlRewritesCollection->getItemByColumnValue(
UrlRewrite::TARGET_PATH,
"catalog/product/view/id/{$productId}"
);
if ($productData['url_rewrite_created']) {
$this->assertNotNull($urlRewrite);
$this->assertEquals($productId, $urlRewrite->getEntityId());
$this->assertEquals('product', $urlRewrite->getEntityType());
$expectedCount++;
} else {
$this->assertNull($urlRewrite);
}
}
$this->assertCount($expectedCount, $urlRewritesCollection);
}
/**
* Return products visibility, expected result and other product additional data.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function visibilityWithExpectedResultDataProvider(): array
{
return [
'visibility_for_both_product_only_catalog' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_IN_CATALOG,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_IN_CATALOG,
'url_rewrite_created' => true,
],
],
],
'visibility_for_both_product_catalog_search' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_BOTH,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_BOTH,
'url_rewrite_created' => true,
],
],
],
'visibility_for_both_product_only_search' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_IN_SEARCH,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_IN_SEARCH,
'url_rewrite_created' => true,
],
],
],
'visibility_for_both_product_not_visible_individuality' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'url_rewrite_created' => false,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'url_rewrite_created' => false,
],
],
],
'visibility_for_one_product_only_catalog' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_IN_CATALOG,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'url_rewrite_created' => false,
],
],
],
'visibility_for_one_product_catalog_search' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_BOTH,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'url_rewrite_created' => false,
],
],
],
'visibility_for_one_product_only_search' => [
[
[
'sku' => 'Simple option 1',
'visibility' => Visibility::VISIBILITY_IN_SEARCH,
'url_rewrite_created' => true,
],
[
'sku' => 'Simple option 2',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'url_rewrite_created' => false,
],
],
],
];
}
/**
* Update products visibility.
*
* @param array $productsData
* @return void
*/
private function updateProductsVisibility(array $productsData): void
{
foreach ($productsData as $productData) {
$product = $this->productRepository->get($productData['sku']);
$product->setVisibility($productData['visibility']);
$this->productRepository->save($product);
}
}
/**
* Get URL rewrite collection by product ids.
*
* @param int[] $productIds
* @param string $storeCode
* @return UrlRewriteCollection
*/
private function getUrlRewritesCollectionByProductIds(
array $productIds,
string $storeCode = 'default'
): UrlRewriteCollection {
$collection = $this->urlRewriteCollectionFactory->create();
$collection->addStoreFilter($storeCode);
$collection->addFieldToFilter(UrlRewrite::ENTITY_TYPE, ['eq' => 'product']);
$collection->addFieldToFilter(UrlRewrite::ENTITY_ID, ['in' => $productIds]);
return $collection;
}
/**
* Check that configurable url rewrite was created.
*
* @return void
*/
private function checkConfigurableUrlRewriteWasCreated(): void
{
$configurableProduct = $this->productRepository->get('Configurable product');
$configurableUrlRewrite = $this->getUrlRewritesCollectionByProductIds([$configurableProduct->getId()])
->getFirstItem();
$this->assertEquals(
$configurableUrlRewrite->getTargetPath(),
"catalog/product/view/id/{$configurableProduct->getId()}"
);
}
/**
* Load all product ids by skus.
*
* @param array $productsData
* @return array
*/
private function getProductIdsBySkus(array $productsData): array
{
$skus = array_column($productsData, 'sku');
return $this->productResource->getProductsIdsBySkus($skus);
}
/**
* @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,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model;
class OptionRepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDbIsolation disabled
*/
public function testGetListWithExtensionAttributes()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productSku = 'configurable';
/** @var \Magento\ConfigurableProduct\Api\OptionRepositoryInterface $optionRepository */
$optionRepository = $objectManager->create(\Magento\ConfigurableProduct\Api\OptionRepositoryInterface::class);
$options = $optionRepository->getList($productSku);
$this->assertCount(1, $options, "Invalid number of option.");
$this->assertNotNull($options[0]->getExtensionAttributes(), "Extension attributes not loaded");
/** @var \Magento\Eav\Model\Entity\Attribute $joinedEntity */
$joinedEntity = $objectManager->create(\Magento\Eav\Model\Entity\Attribute::class);
$joinedEntity->load($options[0]->getId());
$joinedExtensionAttributeValue = $joinedEntity->getAttributeCode();
$result = $options[0]->getExtensionAttributes()->__toArray();
$this->assertEquals(
$joinedExtensionAttributeValue,
$result['test_dummy_attribute'],
"Extension attributes were not loaded correctly"
);
}
/**
* @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,100 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\Product;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable as ConfigurableResource;
/**
* Tests for \Magento\ConfigurableProduct\Model\Product\SaveHandler.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
class SaveHandlerTest extends \PHPUnit\Framework\TestCase
{
/**
* Object under test
*
* @var SaveHandler
*/
private $handler;
/**
* @var Product
*/
private $product;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ConfigurableResource
*/
private $resource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
$this->product = $this->productRepository->get('configurable');
$this->resource = Bootstrap::getObjectManager()->create(ConfigurableResource::class);
$this->handler = Bootstrap::getObjectManager()->create(SaveHandler::class);
}
/**
* @return void
*/
public function testExecuteWithConfigurableProductLinksChanged(): void
{
$childrenIds = $this->product->getTypeInstance()->getChildrenIds($this->product->getId());
$newChildrenIds = [reset($childrenIds[0])];
$product = $this->productRepository->getById($this->product->getId());
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setConfigurableProductLinks($newChildrenIds);
$product->setExtensionAttributes($extensionAttributes);
$this->handler->execute($product);
$childrenIds = $this->product->getTypeInstance()->getChildrenIds($this->product->getId());
$savedChildrenIds = [reset($childrenIds[0])];
self::assertEquals($newChildrenIds, $savedChildrenIds);
}
/**
* @return void
*/
public function testExecuteWithConfigurableProductLinksNotChanged(): void
{
$childrenIds = $this->product->getTypeInstance()->getChildrenIds($this->product->getId())[0];
$product = $this->productRepository->getById($this->product->getId());
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setConfigurableProductLinks($childrenIds);
$product->setExtensionAttributes($extensionAttributes);
$oldProductLinks = $this->getCurrentProductLinks();
$this->handler->execute($product);
$newProductLinks = $this->getCurrentProductLinks();
self::assertEquals($oldProductLinks, $newProductLinks);
}
/**
* @return array
*/
private function getCurrentProductLinks()
{
$select = $this->resource->getConnection()->select()->from(['l' => $this->resource->getMainTable()]);
return $this->resource->getConnection()->fetchAll($select);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model\Product\Type\Configurable;
class AttributeTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute
*/
protected $_model;
protected function setUp(): void
{
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class
);
}
public function testGetLabel()
{
$this->assertEmpty($this->_model->getLabel());
$this->_model->setProductAttribute(new \Magento\Framework\DataObject(['store_label' => 'Store Label']));
$this->assertEquals('Store Label', $this->_model->getLabel());
$this->_model->setUseDefault(
1
)->setProductAttribute(
new \Magento\Framework\DataObject(['store_label' => 'Other Label'])
);
$this->assertEquals('Other Label', $this->_model->getLabel());
}
}
@@ -0,0 +1,265 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Type\AbstractType;
use Magento\Customer\Model\Group;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Catalog\Model\Product\Price\GetPriceIndexDataByProductId;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use PHPUnit\Framework\TestCase;
/**
* Provides tests for configurable product pricing.
*
* @magentoDbIsolation disabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PriceTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var Price
*/
private $priceModel;
/**
* @var GetPriceIndexDataByProductId
*/
private $getPriceIndexDataByProductId;
/**
* @var WebsiteRepositoryInterface
*/
private $websiteRepository;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var ExecuteInStoreContext
*/
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->priceModel = $this->objectManager->create(Price::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->getPriceIndexDataByProductId = $this->objectManager->get(GetPriceIndexDataByProductId::class);
$this->websiteRepository = $this->objectManager->get(WebsiteRepositoryInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/tax_rule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetFinalPrice(): void
{
$this->assertPrice(10);
$this->assertIndexTableData(
'configurable',
['price' => 0, 'final_price' => 0, 'min_price' => 10, 'max_price' => 20, 'tier_price' => null]
);
$this->assertIndexTableData(
'simple_10',
['price' => 10, 'final_price' => 10, 'min_price' => 10, 'max_price' => 10, 'tier_price' => null]
);
$this->assertIndexTableData(
'simple_20',
['price' => 20, 'final_price' => 20, 'min_price' => 20, 'max_price' => 20, 'tier_price' => null]
);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_price_on_second_website.php
* @return void
*/
public function testGetFinalPriceOnSecondWebsite(): void
{
$this->executeInStoreContext->execute('fixture_second_store', [$this, 'assertPrice'], 10);
$this->executeInStoreContext->execute(
'fixture_second_store',
[$this, 'assertIndexTableData'],
'configurable',
['price' => 0, 'final_price' => 0, 'min_price' => 10, 'max_price' => 30, 'tier_price' => null]
);
$this->executeInStoreContext->execute(
'fixture_second_store',
[$this, 'assertIndexTableData'],
'simple_option_1',
['price' => 20, 'final_price' => 10, 'min_price' => 10, 'max_price' => 10, 'tier_price' => null]
);
$this->executeInStoreContext->execute(
'fixture_second_store',
[$this, 'assertIndexTableData'],
'simple_option_2',
['price' => 40, 'final_price' => 30, 'min_price' => 30, 'max_price' => 30, 'tier_price' => null]
);
$this->assertPrice(150);
$this->assertIndexTableData(
'configurable',
['price' => 0, 'final_price' => 0, 'min_price' => 150, 'max_price' => 150, 'tier_price' => null]
);
$this->assertIndexTableData(
'simple_option_1',
['price' => 150, 'final_price' => 150, 'min_price' => 150, 'max_price' => 150, 'tier_price' => null]
);
$this->assertIndexTableData(
'simple_option_2',
['price' => 150, 'final_price' => 150, 'min_price' => 150, 'max_price' => 150, 'tier_price' => null]
);
}
/**
* @magentoConfigFixture current_store tax/display/type 1
* @magentoDataFixture Magento/ConfigurableProduct/_files/tax_rule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetFinalPriceExcludingTax(): void
{
$this->assertPrice(10);
}
/**
* @magentoConfigFixture current_store tax/display/type 2
* @magentoDataFixture Magento/ConfigurableProduct/_files/tax_rule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetFinalPriceIncludingTax(): void
{
//lowest price of configurable variation + 10%
$this->assertPrice(11);
}
/**
* @magentoConfigFixture current_store tax/display/type 3
* @magentoDataFixture Magento/ConfigurableProduct/_files/tax_rule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetFinalPriceIncludingExcludingTax(): void
{
//lowest price of configurable variation + 10%
$this->assertPrice(11);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/tax_rule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @return void
*/
public function testGetFinalPriceWithSelectedSimpleProduct(): void
{
$product = $this->productRepository->get('configurable');
$product->addCustomOption('simple_product', 20, $this->getProduct('simple_20'));
$this->assertPrice(20, $product);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_custom_option_and_simple_tier_price.php
* @return void
*/
public function testGetFinalPriceWithCustomOptionAndSimpleTierPrice(): void
{
$configurable = $this->getProduct('configurable');
$this->assertIndexTableData(
'configurable',
['price' => 0, 'final_price' => 0, 'min_price' => 9, 'max_price' => 30, 'tier_price' => 15]
);
$this->assertIndexTableData(
'simple_10',
['price' => 10, 'final_price' => 9, 'min_price' => 9, 'max_price' => 9, 'tier_price' => null]
);
$this->assertIndexTableData(
'simple_20',
['price' => 20, 'final_price' => 15, 'min_price' => 15, 'max_price' => 15, 'tier_price' => 15]
);
$optionId = $configurable->getOptions()[0]->getId();
$configurable->addCustomOption(AbstractType::OPTION_PREFIX . $optionId, 'text');
$configurable->addCustomOption('option_ids', $optionId);
// First simple special price (9) + Option price (15)
$this->assertPrice(24, $configurable);
$configurable->addCustomOption('simple_product', 20, $this->productRepository->get('simple_20'));
// Second simple tier price (15) + Option price (15)
$this->assertPrice(30, $configurable);
}
/**
* Asserts price data in index table.
*
* @param string $sku
* @param array $expectedPrices
* @return void
*/
public function assertIndexTableData(string $sku, array $expectedPrices): void
{
$data = $this->getPriceIndexDataByProductId->execute(
(int)$this->getProduct($sku)->getId(),
Group::NOT_LOGGED_IN_ID,
(int)$this->storeManager->getStore()->getWebsiteId()
);
$data = reset($data);
foreach ($expectedPrices as $column => $price) {
$this->assertEquals($price, $data[$column], $column);
}
}
/**
* Asserts product final price.
*
* @param float $expectedPrice
* @param ProductInterface|null $product
* @return void
*/
public function assertPrice(float $expectedPrice, ?ProductInterface $product = null): void
{
$product = $product ?: $this->getProduct('configurable');
// final price is the lowest price of configurable variations
$this->assertEquals(
round($expectedPrice, 2),
round((float) $this->priceModel->getFinalPrice(1, $product), 2)
);
}
/**
* 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,121 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\CatalogInventory\Api\Data\StockStatusInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Check is configurable product salable with different conditions
*
* @magentoAppArea frontend
*/
class SalableTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @dataProvider salableDataProvider
*
* @param array $productSkus
* @param array $productData
* @param bool $expectedValue
* @return void
*/
public function testIsSalable(array $productSkus, array $productData, bool $expectedValue): void
{
$this->updateProduct($productSkus, $productData);
$configurableProduct = $this->productRepository->get('configurable', false, null, true);
$this->assertEquals($expectedValue, $configurableProduct->getIsSalable());
}
/**
* @return array
*/
public function salableDataProvider(): array
{
return [
'all children enabled_and_in_stock' => [
'product_skus' => [],
'data' => [],
'expected_value' => true,
],
'one_child_out_of_stock' => [
'product_skus' => ['simple_10'],
'data' => [
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_OUT_OF_STOCK,
],
],
'expected_value' => true,
],
'one_child_disabled' => [
'product_skus' => ['simple_10'],
'data' => ['status' => Status::STATUS_DISABLED],
'expected_value' => true,
],
'all_children_disabled' => [
'product_skus' => ['simple_10', 'simple_20'],
'data' => ['status' => Status::STATUS_DISABLED],
'expected_value' => false,
],
'all_children_out_of_stock' => [
'product_skus' => ['simple_10', 'simple_20'],
'data' => [
'stock_data' => [
'use_config_manage_stock' => 1,
'is_in_stock' => StockStatusInterface::STATUS_OUT_OF_STOCK,
],
],
'expected_value' => false,
]
];
}
/**
* Update product with data
*
* @param array $skus
* @param array $data
* @return void
*/
private function updateProduct(array $skus, array $data): void
{
if (!empty($skus)) {
foreach ($skus as $sku) {
$product = $this->productRepository->get($sku);
$product->addData($data);
$this->productRepository->save($product);
}
}
}
}
@@ -0,0 +1,676 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Magento\ConfigurableProduct\Model\Product\Type;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory;
use PHPUnit\Framework\TestCase;
/**
* Class ConfigurableTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigurableTest extends TestCase
{
/**
* Object under test
*
* @var Configurable
*/
private $model;
/**
* @var Product
*/
private $product;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
protected function setUp(): void
{
$this->productRepository = Bootstrap::getObjectManager()
->create(ProductRepositoryInterface::class);
$this->product = Bootstrap::getObjectManager()
->create(Product::class);
$this->product->load(1);
$this->model = Bootstrap::getObjectManager()
->create(Configurable::class);
// prevent fatal errors by assigning proper "singleton" of type instance to the product
$this->product->setTypeInstance($this->model);
}
public function testGetRelationInfo()
{
$info = $this->model->getRelationInfo();
$this->assertInstanceOf(\Magento\Framework\DataObject::class, $info);
$this->assertEquals('catalog_product_super_link', $info->getTable());
$this->assertEquals('parent_id', $info->getParentFieldName());
$this->assertEquals('product_id', $info->getChildFieldName());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetChildrenIds()
{
$ids = $this->model->getChildrenIds($this->product->getId());
// fixture
$this->assertArrayHasKey(0, $ids);
$this->assertTrue(2 === count($ids[0]));
$ids = $this->model->getChildrenIds($this->product->getId(), false);
$this->assertArrayHasKey(0, $ids);
$this->assertTrue(2 === count($ids[0]));
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testCanUseAttribute()
{
$this->assertFalse($this->model->canUseAttribute($this->_getAttributeByCode('sku')));
$this->assertTrue($this->model->canUseAttribute($this->_getAttributeByCode('test_configurable')));
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testSetGetUsedProductAttributeIds()
{
$testConfigurable = $this->_getAttributeByCode('test_configurable');
$actual = $this->model->getUsedProductAttributeIds($this->product);
$expected = [$testConfigurable->getId()];
$this->assertEquals($expected, $actual);
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testSetUsedProductAttributeIds()
{
$testConfigurable = $this->_getAttributeByCode('test_configurable');
$this->model->setUsedProductAttributeIds([$testConfigurable->getId()], $this->product);
$attributes = $this->product->getData('_cache_instance_configurable_attributes');
$this->assertArrayHasKey(0, $attributes);
$this->assertInstanceOf(
\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class,
$attributes[0]
);
$this->assertSame($testConfigurable, $attributes[0]->getProductAttribute());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetUsedProductAttributes()
{
$testConfigurable = $this->_getAttributeByCode('test_configurable');
$attributeId = (int)$testConfigurable->getId();
$attributes = $this->model->getUsedProductAttributes($this->product);
$this->assertArrayHasKey($attributeId, $attributes);
$this->assertEquals($testConfigurable->getData(), $attributes[$attributeId]->getData());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetConfigurableAttributes()
{
$collection = $this->model->getConfigurableAttributes($this->product);
$this->assertInstanceOf(
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection::class,
$collection
);
$testConfigurable = $this->_getAttributeByCode('test_configurable');
foreach ($collection as $attribute) {
$this->assertInstanceOf(
\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class,
$attribute
);
$this->assertEquals($testConfigurable->getId(), $attribute->getAttributeId());
$options = $attribute->getOptions();
$this->assertCount(2, $options);
// fixture
$this->assertEquals('Option 1', $options[0]['label']);
$this->assertEquals('Option 2', $options[1]['label']);
break;
}
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_custom.php
*/
public function testGetConfigurableAttributesWithSourceModel()
{
$collection = $this->model->getConfigurableAttributes($this->product);
/** @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute $configurableAttribute */
$configurableAttribute = $collection->getFirstItem();
$attribute = $this->_getAttributeByCode('test_configurable_with_sm');
$this->assertSameSize($attribute->getSource()->getAllOptions(), $configurableAttribute->getOptions());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetConfigurableAttributesAsArray()
{
$product = $this->productRepository->getById(1, true);
$attributes = $this->model->getConfigurableAttributesAsArray($product);
$attribute = reset($attributes);
$this->assertArrayHasKey('id', $attribute);
$this->assertArrayHasKey('label', $attribute);
$this->assertArrayHasKey('use_default', $attribute);
$this->assertArrayHasKey('position', $attribute);
$this->assertArrayHasKey('values', $attribute);
$this->assertArrayHasKey(0, $attribute['values']);
$this->assertArrayHasKey(1, $attribute['values']);
foreach ($attribute['values'] as $attributeOption) {
$this->assertArrayHasKey('product_super_attribute_id', $attributeOption);
$this->assertArrayHasKey('value_index', $attributeOption);
$this->assertArrayHasKey('label', $attributeOption);
$this->assertArrayHasKey('default_label', $attributeOption);
$this->assertArrayHasKey('store_label', $attributeOption);
$this->assertArrayHasKey('use_default_value', $attributeOption);
}
$this->assertArrayHasKey('attribute_id', $attribute);
$this->assertArrayHasKey('attribute_code', $attribute);
$this->assertArrayHasKey('frontend_label', $attribute);
$this->assertArrayHasKey('store_label', $attribute);
$testConfigurable = $this->_getAttributeByCode('test_configurable');
$this->assertEquals($testConfigurable->getId(), $attribute['attribute_id']);
}
/**
* @depends testGetConfigurableAttributesAsArray
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetParentIdsByChild()
{
$result = $this->model->getParentIdsByChild(10);
// fixture
$this->assertEquals([$this->product->getId()], $result);
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetConfigurableAttributeCollection()
{
$collection = $this->model->getConfigurableAttributeCollection($this->product);
$this->assertInstanceOf(
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection::class,
$collection
);
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetUsedProductIds()
{
$ids = $this->model->getUsedProductIds($this->product);
$this->assertIsArray($ids);
$this->assertTrue(2 === count($ids)); // impossible to check actual IDs, they are dynamic in the fixture
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetUsedProducts()
{
$products = $this->model->getUsedProducts($this->product);
$this->assertIsArray($products);
$this->assertTrue(2 === count($products));
foreach ($products as $product) {
$this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product);
}
}
/**
* Tests the $requiredAttributes parameter; uses meta_description as an example of an attribute that is not
* included in default attribute select.
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_metadescription.php
*/
public function testGetUsedProductsWithRequiredAttributes()
{
$requiredAttributeIds = [86];
$products = $this->model->getUsedProducts($this->product, $requiredAttributeIds);
foreach ($products as $product) {
self::assertNotNull($product->getData('meta_description'));
}
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_metadescription.php
*/
public function testGetUsedProductsWithoutRequiredAttributes()
{
$products = $this->model->getUsedProducts($this->product);
foreach ($products as $product) {
self::assertNull($product->getData('meta_description'));
}
}
/**
* Test getUsedProducts returns array with same indexes regardless collections was cache or not.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testGetUsedProductsCached()
{
/** @var \Magento\Framework\App\Cache\StateInterface $cacheState */
$cacheState = Bootstrap::getObjectManager()->get(\Magento\Framework\App\Cache\StateInterface::class);
$cacheState->setEnabled(\Magento\Framework\App\Cache\Type\Collection::TYPE_IDENTIFIER, true);
$products = $this->getUsedProducts();
$productsCached = $this->getUsedProducts();
self::assertEquals(
array_keys($products),
array_keys($productsCached)
);
}
public function testGetUsedProductCollection()
{
$this->assertInstanceOf(
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection::class,
$this->model->getUsedProductCollection($this->product)
);
}
public function testBeforeSave()
{
$this->assertEmpty($this->product->getTypeHasOptions());
$this->assertEmpty($this->product->getTypeHasRequiredOptions());
$this->product->setCanSaveConfigurableAttributes(true);
$this->product->setConfigurableAttributesData([['values' => 'not empty']]);
$this->model->beforeSave($this->product);
$this->assertTrue($this->product->getTypeHasOptions());
$this->assertTrue($this->product->getTypeHasRequiredOptions());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testIsSalable()
{
$this->product->unsetData('is_salable');
$this->assertTrue($this->model->isSalable($this->product));
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @depends testGetConfigurableAttributesAsArray
*/
public function testGetProductByAttributes()
{
$attributes = $this->model->getConfigurableAttributesAsArray($this->product);
$attribute = reset($attributes);
$optionValueId = $attribute['values'][0]['value_index'];
$product = $this->model->getProductByAttributes(
[$attribute['attribute_id'] => $optionValueId],
$this->product
);
$this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product);
$this->assertEquals("simple_10", $product->getSku());
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @depends testGetConfigurableAttributesAsArray
*/
public function testGetSelectedAttributesInfo()
{
/** @var $serializer \Magento\Framework\Serialize\Serializer\Json */
$serializer = Bootstrap::getObjectManager()->create(\Magento\Framework\Serialize\Serializer\Json::class);
$product = $this->productRepository->getById(1, true);
$attributes = $this->model->getConfigurableAttributesAsArray($product);
$attribute = reset($attributes);
$optionValueId = $attribute['values'][0]['value_index'];
$product->addCustomOption('attributes',
$serializer->serialize([$attribute['attribute_id'] => $optionValueId])
);
$info = $this->model->getSelectedAttributesInfo($product);
$this->assertEquals('Test Configurable', $info[0]['label']);
$this->assertEquals('Option 1', $info[0]['value']);
}
/**
* @covers \Magento\ConfigurableProduct\Model\Product\Type\Configurable::getConfigurableAttributes()
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testGetSelectedAttributesInfoForStore()
{
/** @var $serializer \Magento\Framework\Serialize\Serializer\Json */
$serializer = Bootstrap::getObjectManager()->create(\Magento\Framework\Serialize\Serializer\Json::class);
$attributes = $this->model->getConfigurableAttributesAsArray($this->product);
$attribute = reset($attributes);
$optionValueId = $attribute['values'][0]['value_index'];
$this->product->addCustomOption(
'attributes',
$serializer->serialize([$attribute['attribute_id'] => $optionValueId])
);
$configurableAttr = $this->model->getConfigurableAttributes($this->product);
$attribute = $configurableAttr->getFirstItem();
$attribute->getProductAttribute()->setStoreLabel('store label');
$info = $this->model->getSelectedAttributesInfo($this->product);
$this->assertEquals('store label', $info[0]['label']);
$this->assertEquals('Option 1', $info[0]['value']);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
* @depends testGetConfigurableAttributesAsArray
*/
public function testPrepareForCart()
{
$attributes = $this->model->getConfigurableAttributesAsArray($this->product);
$attribute = reset($attributes);
$optionValueId = $attribute['values'][0]['value_index'];
$buyRequest = new \Magento\Framework\DataObject(
['qty' => 5, 'super_attribute' => [$attribute['attribute_id'] => $optionValueId]]
);
$result = $this->model->prepareForCart($buyRequest, $this->product);
$this->assertIsArray($result);
$this->assertTrue(2 === count($result));
foreach ($result as $product) {
$this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product);
}
$this->assertInstanceOf(\Magento\Framework\DataObject::class, $result[1]->getCustomOption('parent_product_id'));
}
public function testGetSpecifyOptionMessage()
{
$this->assertEquals(
'You need to choose options for your item.',
(string)$this->model->getSpecifyOptionMessage()
);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
* @depends testGetConfigurableAttributesAsArray
* @depends testPrepareForCart
*/
public function testGetOrderOptions()
{
$product = $this->_prepareForCart();
$result = $this->model->getOrderOptions($product);
$this->assertArrayHasKey('info_buyRequest', $result);
$this->assertArrayHasKey('attributes_info', $result);
$this->assertEquals('Test Configurable', $result['attributes_info'][0]['label']);
$this->assertEquals('Option 1', $result['attributes_info'][0]['value']);
$this->assertArrayHasKey('product_calculations', $result);
$this->assertArrayHasKey('shipment_type', $result);
$this->assertEquals(
\Magento\Catalog\Model\Product\Type\AbstractType::CALCULATE_PARENT,
$result['product_calculations']
);
$this->assertEquals(
\Magento\Catalog\Model\Product\Type\AbstractType::SHIPMENT_TOGETHER,
$result['shipment_type']
);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
* @depends testGetConfigurableAttributesAsArray
* @depends testPrepareForCart
*/
public function testIsVirtual()
{
$product = $this->_prepareForCart();
$this->assertFalse($this->model->isVirtual($product));
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testHasOptions()
{
$this->assertTrue($this->model->hasOptions($this->product));
}
public function testGetWeight()
{
$this->assertEmpty($this->model->getWeight($this->product));
$this->product->setCustomOptions(
[
'simple_product' => new \Magento\Framework\DataObject(
[
'product' => new \Magento\Framework\DataObject(['weight' => 2]),
]
),
]
);
$this->assertEquals(2, $this->model->getWeight($this->product));
}
public function testAssignProductToOption()
{
$option = new \Magento\Framework\DataObject();
$this->model->assignProductToOption('test', $option, $this->product);
$this->assertEquals('test', $option->getProduct());
// other branch of logic depends on \Magento\Sales module
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testGetProductsToPurchaseByReqGroups()
{
$result = $this->model->getProductsToPurchaseByReqGroups($this->product);
$this->assertArrayHasKey(0, $result);
$this->assertIsArray($result[0]);
$this->assertTrue(2 === count($result[0]));
// fixture has 2 simple products
foreach ($result[0] as $product) {
$this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product);
}
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testGetSku()
{
$this->assertEquals('configurable', $this->model->getSku($this->product));
$product = $this->_prepareForCart();
$this->assertStringStartsWith('simple_', $this->model->getSku($product));
}
public function testProcessBuyRequest()
{
$buyRequest = new \Magento\Framework\DataObject(['super_attribute' => ['10', 'string']]);
$result = $this->model->processBuyRequest($this->product, $buyRequest);
$this->assertEquals(['super_attribute' => [10]], $result);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testSaveProductRelationsOneChild()
{
$oldChildrenIds = $this->product->getTypeInstance()
->getChildrenIds($this->product->getId());
$oldChildrenIds = reset($oldChildrenIds);
$oneChildId = reset($oldChildrenIds);
self::assertNotEmpty($oldChildrenIds);
self::assertNotEmpty($oneChildId);
$product = $this->productRepository->getById($this->product->getId());
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setConfigurableProductLinks([$oneChildId]);
$product->setExtensionAttributes($extensionAttributes);
$this->productRepository->save($product);
self::assertEquals(
[
[
$oneChildId => $oneChildId
]
],
$this->model->getChildrenIds($this->product->getId())
);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppIsolation enabled
*/
public function testSaveProductRelationsNoChildren()
{
$childrenIds = $this->product->getTypeInstance()
->getChildrenIds($this->product->getId());
self::assertNotEmpty(reset($childrenIds));
$product = $this->productRepository->getById($this->product->getId(), true);
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setConfigurableProductLinks([]);
$product->setExtensionAttributes($extensionAttributes);
$this->productRepository->save($product);
self::assertEquals(
[
[]
],
$this->model->getChildrenIds($this->product->getId())
);
}
/**
* Find and instantiate a catalog attribute model by attribute code
*
* @param string $code
* @return \Magento\Catalog\Model\ResourceModel\Eav\Attribute
*/
protected function _getAttributeByCode($code)
{
return Bootstrap::getObjectManager()->get(
\Magento\Eav\Model\Config::class
)->getAttribute(
'catalog_product',
$code
);
}
/**
* Select one of the options and "prepare for cart" with a proper buy request
*
* @return ProductInterface
*/
protected function _prepareForCart()
{
$product = $this->productRepository->getById(1, true);
$attributes = $this->model->getConfigurableAttributesAsArray($product);
$attribute = reset($attributes);
$optionValueId = $attribute['values'][0]['value_index'];
$buyRequest = new \Magento\Framework\DataObject(
['qty' => 5, 'super_attribute' => [$attribute['attribute_id'] => $optionValueId]]
);
$this->model->prepareForCart($buyRequest, $product);
return $product;
}
/**
* @return ProductInterface[]
*/
protected function getUsedProducts()
{
$product = Bootstrap::getObjectManager()->create(Product::class);
$product->load(1);
return $this->model->getUsedProducts($product);
}
/**
* Unable to save product required option to product which is a part of configurable product
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @return void
*/
public function testAddCustomOptionToConfigurableChildProduct(): void
{
$this->expectErrorMessage(
'Required custom options cannot be added to a simple product that is a part of a composite product.'
);
$sku = 'Simple option 1';
$product = $this->productRepository->get($sku);
$optionRepository = Bootstrap::getObjectManager()->get(ProductCustomOptionInterfaceFactory::class);
$createdOption = $optionRepository->create(
['data' => ['title' => 'drop_down option', 'type' => 'drop_down', 'sort_order' => 4, 'is_require' => 1]]
);
$createdOption->setProductSku($product->getSku());
$product->setOptions([$createdOption]);
$this->productRepository->save($product);
$product = $this->productRepository->get($sku);
$this->assertEmpty($product->getOptions());
}
}
@@ -0,0 +1,169 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for simple products generation by saving a configurable product.
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
class VariationHandlerTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var VariationHandler
*/
private $variationHandler;
/**
* @var ProductInterface
*/
private $product;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->variationHandler = $this->objectManager->create(VariationHandler::class);
$this->product = $this->productRepository->get('configurable');
$this->stockRegistry = $this->objectManager->get(StockRegistryInterface::class);
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @dataProvider generateSimpleProductsDataProvider
* @param array $productsData
* @return void
*/
public function testGenerateSimpleProducts(array $productsData): void
{
$this->product->setImage('some_test_image.jpg')
->setSmallImage('some_test_image.jpg')
->setThumbnail('some_test_image.jpg')
->setSwatchImage('some_test_image.jpg')
->setNewVariationsAttributeSetId($this->product->getDefaultAttributeSetId());
$generatedProducts = $this->variationHandler->generateSimpleProducts($this->product, $productsData);
$this->assertCount(3, $generatedProducts);
foreach ($generatedProducts as $productId) {
$stockItem = $this->stockRegistry->getStockItem($productId);
$product = $this->productRepository->getById($productId);
$this->assertNotNull($product->getName());
$this->assertNotNull($product->getSku());
$this->assertNotNull($product->getPrice());
$this->assertNotNull($product->getWeight());
$this->assertEquals('1', $stockItem->getIsInStock());
$this->assertNull($product->getImage());
$this->assertNull($product->getSmallImage());
$this->assertNull($product->getThumbnail());
$this->assertNull($product->getSwatchImage());
}
}
/**
* @param array $productsData
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @dataProvider generateSimpleProductsWithPartialDataDataProvider
* @return void
*/
public function testGenerateSimpleProductsWithPartialData(array $productsData): void
{
$this->product->setNewVariationsAttributeSetId(4);
$generatedProducts = $this->variationHandler->generateSimpleProducts($this->product, $productsData);
$parentStockItem = $this->stockRegistry->getStockItem($this->product->getId());
foreach ($generatedProducts as $productId) {
$stockItem = $this->stockRegistry->getStockItem($productId);
$this->assertEquals($parentStockItem->getManageStock(), $stockItem->getManageStock());
$this->assertEquals('1', $stockItem->getIsInStock());
}
}
/**
* @return array
*/
public function generateSimpleProductsDataProvider(): array
{
return [
[
[
[
'name' => '1-aaa',
'configurable_attribute' => '{"configurable_attribute":"25"}',
'price' => '3',
'sku' => '1-aaa',
'quantity_and_stock_status' => ['qty' => '5'],
'weight' => '6',
],
[
'name' => '1-bbb',
'configurable_attribute' => '{"configurable_attribute":"24"}',
'price' => '3',
'sku' => '1-bbb',
'quantity_and_stock_status' => ['qty' => '5'],
'weight' => '6'
],
[
'name' => '1-ccc',
'configurable_attribute' => '{"configurable_attribute":"23"}',
'price' => '3',
'sku' => '1-ccc',
'quantity_and_stock_status' => ['qty' => '5'],
'weight' => '6'
],
],
]
];
}
/**
* @return array
*/
public function generateSimpleProductsWithPartialDataDataProvider(): array
{
return [
[
[
[
'name' => '1-aaa',
'configurable_attribute' => '{"configurable_attribute":"23"}',
'price' => '3',
'sku' => '1-aaa-1',
'quantity_and_stock_status' => ['qty' => ''],
'weight' => '6',
],
],
]
];
}
}
@@ -0,0 +1,49 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductTest extends \PHPUnit\Framework\TestCase
{
/**
* Check that no children identities are added to the parent product in frontend area
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppArea frontend
* @return void
*/
public function testGetIdentitiesForConfigurableProductOnStorefront(): void
{
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$configurableProduct = $productRepository->get('configurable');
$expectedIdentities = [
'cat_p_' . $configurableProduct->getId(),
'cat_p'
];
$this->assertEquals($expectedIdentities, $configurableProduct->getIdentities());
}
/**
* Check that no children identities are added to the parent product in frontend area
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppArea adminhtml
* @return void
*/
public function testGetIdentitiesForConfigurableProductInAdminArea(): void
{
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$configurableProduct = $productRepository->get('configurable');
$expectedIdentities = [
'cat_p_' . $configurableProduct->getId(),
];
$this->assertEquals($expectedIdentities, $configurableProduct->getIdentities());
}
}
@@ -0,0 +1,166 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\TestFramework\Catalog\Model\Layer\QuickSearchByQuery;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Test cases related to find configurable product via quick search using search engine.
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
class QuickSearchTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var QuickSearchByQuery
*/
private $quickSearchByQuery;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->quickSearchByQuery = $this->objectManager->get(QuickSearchByQuery::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
parent::setUp();
}
/**
* Assert that configurable child products has not found by query using mysql search engine.
*
* @return void
*/
public function testChildProductsHasNotFoundedByQuery(): void
{
$this->checkThatOnlyConfigurableProductIsAvailableBySearch('Configurable Option');
}
/**
* Assert that child product of configurable will be available by search after
* set to product visibility by catalog and search using mysql search engine.
*
* @dataProvider productAvailabilityInSearchByVisibilityDataProvider
*
* @param int $visibility
* @param bool $expectedResult
* @return void
*/
public function testOneOfChildIsAvailableBySearch(int $visibility, bool $expectedResult): void
{
$this->checkThatOnlyConfigurableProductIsAvailableBySearch('Configurable Option');
$this->updateProductVisibility($visibility);
$this->checkProductAvailabilityInSearch($expectedResult);
$this->checkThatOnlyConfigurableProductIsAvailableBySearch('White');
}
/**
* Return data with product visibility and expected result.
*
* @return array
*/
public function productAvailabilityInSearchByVisibilityDataProvider(): array
{
return [
'visible_catalog_only' => [
Visibility::VISIBILITY_IN_CATALOG,
false,
],
'visible_catalog_and_search' => [
Visibility::VISIBILITY_BOTH,
true,
],
'visible_search_only' => [
Visibility::VISIBILITY_IN_SEARCH,
true,
],
'visible_search_not_visible_individuality' => [
Visibility::VISIBILITY_NOT_VISIBLE,
false,
],
];
}
/**
* Assert that configurable product was found by option value using mysql search engine.
*
*
* @return void
*/
public function testSearchByOptionValue(): void
{
$this->checkThatOnlyConfigurableProductIsAvailableBySearch('Option 1');
}
/**
* Assert that anyone child product is not available by quick search.
*
* @param string $searchQuery
*
* @return void
*/
private function checkThatOnlyConfigurableProductIsAvailableBySearch(string $searchQuery): void
{
$searchResult = $this->quickSearchByQuery->execute($searchQuery);
$this->assertCount(1, $searchResult->getItems());
/** @var Product $configurableProduct */
$configurableProduct = $searchResult->getFirstItem();
$this->assertEquals('Configurable product', $configurableProduct->getSku());
}
/**
* Update product visibility.
*
* @param int $visibility
* @return void
*/
private function updateProductVisibility(int $visibility): void
{
$childProduct = $this->productRepository->get('Simple option 1');
$childProduct->setVisibility($visibility);
$this->productRepository->save($childProduct);
}
/**
* Assert that configurable and one of child product is available by search.
*
* @param bool $firstChildIsVisible
* @return void
*/
private function checkProductAvailabilityInSearch(bool $firstChildIsVisible): void
{
$searchResult = $this->quickSearchByQuery->execute('Black');
$this->assertNotNull($searchResult->getItemByColumnValue(Product::SKU, 'Configurable product'));
$this->assertEquals(
$firstChildIsVisible,
(bool)$searchResult->getItemByColumnValue(Product::SKU, 'Simple option 1')
);
$this->assertNull($searchResult->getItemByColumnValue(Product::SKU, 'Simple option 2'));
}
}
@@ -0,0 +1,218 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\ResourceModel\Product\Indexer\Price;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Indexer\Product\Price\Processor as PriceIndexerProcessor;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\CatalogInventory\Model\Stock;
use Magento\CatalogInventory\Api\StockItemRepositoryInterface;
use PHPUnit\Framework\TestCase;
use Magento\Catalog\Api\Data\ProductInterface;
/**
* Test reindex of configurable products
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
*/
class ConfigurableTest extends TestCase
{
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var StockItemRepositoryInterface
*/
private $stockRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
$this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$this->stockRepository = Bootstrap::getObjectManager()->get(StockItemRepositoryInterface::class);
}
/**
* Test get product final price if one of child is disabled
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDbIsolation disabled
*
* @return void
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\StateException
*/
public function testGetProductFinalPriceIfOneOfChildIsDisabled(): void
{
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(10, $configurableProduct->getMinimalPrice());
$childProduct = $this->productRepository->getById(10, false, null, true);
$childProduct->setStatus(Status::STATUS_DISABLED);
// update in global scope
$currentStoreId = $this->storeManager->getStore()->getId();
$this->storeManager->setCurrentStore(Store::ADMIN_CODE);
$this->productRepository->save($childProduct);
$this->storeManager->setCurrentStore($currentStoreId);
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(20, $configurableProduct->getMinimalPrice());
}
/**
* Test get product final price if one of child is disabled per store
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDbIsolation disabled
*
* @return void
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\StateException
*/
public function testGetProductFinalPriceIfOneOfChildIsDisabledPerStore(): void
{
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(10, $configurableProduct->getMinimalPrice());
$childProduct = $this->productRepository->get('simple_10', false, null, true);
$childProduct->setStatus(Status::STATUS_DISABLED);
// update in default store scope
$currentStoreId = $this->storeManager->getStore()->getId();
$defaultStore = $this->storeManager->getDefaultStoreView();
$this->storeManager->setCurrentStore($defaultStore->getId());
$this->productRepository->save($childProduct);
$this->storeManager->setCurrentStore($currentStoreId);
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(20, $configurableProduct->getMinimalPrice());
}
/**
* Test get product minimal price if one child is out of stock
*
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDbIsolation disabled
*
* @return void
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function testGetProductMinimalPriceIfOneOfChildIsOutOfStock(): void
{
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(10, $configurableProduct->getMinimalPrice());
$childProduct = $this->productRepository->getById(10, false, null, true);
$stockItem = $childProduct->getExtensionAttributes()->getStockItem();
$stockItem->setIsInStock(Stock::STOCK_OUT_OF_STOCK);
$this->stockRepository->save($stockItem);
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(20, $configurableProduct->getMinimalPrice());
}
/**
* @magentoDataFixture Magento/Catalog/_files/enable_price_index_schedule.php
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_assigned_simples.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testReindexWithCorrectPriority()
{
$configurableProduct = $this->productRepository->get('configurable');
$childProduct1 = $this->productRepository->get('simple_1');
$childProduct2 = $this->productRepository->get('simple_2');
$priceIndexerProcessor = Bootstrap::getObjectManager()->get(PriceIndexerProcessor::class);
$priceIndexerProcessor->reindexList(
[$configurableProduct->getId(), $childProduct1->getId(), $childProduct2->getId()],
true
);
$configurableProduct = $this->getConfigurableProductFromCollection((int)$configurableProduct->getId());
$this->assertEquals($childProduct1->getPrice(), $configurableProduct->getMinimalPrice());
}
/**
* Test get product minimal price if all children is out of stock
*
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoDbIsolation disabled
*
* @return void
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function testReindexIfAllChildrenIsOutOfStock(): void
{
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(10, $configurableProduct->getMinimalPrice());
$childProduct1 = $this->productRepository->getById(10, false, null, true);
$stockItem = $childProduct1->getExtensionAttributes()->getStockItem();
$stockItem->setIsInStock(Stock::STOCK_OUT_OF_STOCK);
$this->stockRepository->save($stockItem);
$childProduct2 = $this->productRepository->getById(20, false, null, true);
$stockItem = $childProduct2->getExtensionAttributes()->getStockItem();
$stockItem->setIsInStock(Stock::STOCK_OUT_OF_STOCK);
$this->stockRepository->save($stockItem);
$configurableProduct1 = $this->productRepository->getById(1, false, null, true);
$stockItem = $configurableProduct1->getExtensionAttributes()->getStockItem();
$stockItem->setIsInStock(Stock::STOCK_OUT_OF_STOCK);
$this->stockRepository->save($stockItem);
$configurableProduct = $this->getConfigurableProductFromCollection(1);
$this->assertEquals(10, $configurableProduct->getMinimalPrice());
}
/**
* Retrieve configurable product.
* Returns Configurable product that was created by Magento/ConfigurableProduct/_files/product_configurable.php
* fixture
*
* @param int $productId
* @return ProductInterface
*/
private function getConfigurableProductFromCollection(int $productId): ProductInterface
{
/** @var Collection $collection */
$collection = Bootstrap::getObjectManager()->get(CollectionFactory::class)
->create();
/** @var ProductInterface $configurableProduct */
$configurableProduct = $collection
->addIdFilter([$productId])
->addMinimalPrice()
->load()
->getFirstItem();
return $configurableProduct;
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model\ResourceModel\Product\Indexer\Stock;
class ConfigurableTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testReindexAll()
{
/** @var \Magento\CatalogInventory\Model\Indexer\Stock\Processor $processor */
$processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\CatalogInventory\Model\Indexer\Stock\Processor::class
);
$processor->reindexAll();
/** @var \Magento\Catalog\Model\CategoryFactory $categoryFactory */
$categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\CategoryFactory::class
);
$category = $categoryFactory->create()->load(2);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\ResourceModel\Product\Collection::class
);
$productCollection->addUrlRewrite($category->getId());
$productCollection->addAttributeToSelect('name');
$productCollection->joinField(
'qty',
'cataloginventory_stock_status',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
$this->assertCount(3, $productCollection);
$expectedResult = [
'Configurable OptionOption 1' => 1000,
'Configurable OptionOption 2' => 1000,
'Configurable Product' => 0
];
/** @var $product \Magento\Catalog\Model\Product */
foreach ($productCollection as $product) {
$this->assertEquals($expectedResult[$product->getName()], $product->getQty());
}
}
}
@@ -0,0 +1,145 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model\ResourceModel\Product;
use Magento\Catalog\Model\ResourceModel\Product\Relation;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\ConfigurableProduct\Test\Fixture\Attribute as AttributeFixture;
use Magento\ConfigurableProduct\Test\Fixture\Product as ConfigurableProductFixture;
use Magento\Framework\ObjectManagerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests Catalog Product Relation resource model.
*
* @see Relation
*/
class RelationTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Relation
*/
private $model;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->get(Relation::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
}
/**
* Tests that getRelationsByChildren will return parent products entity ids of child products entity ids.
*
*/
#[
DataFixture(ProductFixture::class, ['sku' => 'simple_10'], 'p1'),
DataFixture(ProductFixture::class, ['sku' => 'simple_20'], 'p2'),
DataFixture(ProductFixture::class, ['sku' => 'simple_30'], 'p3'),
DataFixture(ProductFixture::class, ['sku' => 'simple_40'], 'p4'),
DataFixture(AttributeFixture::class, as: 'attr'),
DataFixture(
ConfigurableProductFixture::class,
['sku' => 'conf1','_options' => ['$attr$'],'_links' => ['$p1$','$p2$']],
'conf1'
),
DataFixture(
ConfigurableProductFixture::class,
['sku' => 'conf2','_options' => ['$attr$'],'_links' => ['$p3$','$p4$']],
'conf2'
),
]
public function testGetRelationsByChildren(): void
{
$childSkusOfParentSkus = [
'conf1' => ['simple_10', 'simple_20'],
'conf2' => ['simple_30', 'simple_40'],
];
$configurableSkus = [
'conf1',
'conf2',
'simple_10',
'simple_20',
'simple_30',
'simple_40',
];
$configurableIdsOfSkus = [];
$searchCriteria = $this->searchCriteriaBuilder->addFilter('sku', $configurableSkus, 'in')
->create();
$configurableProducts = $this->productRepository->getList($searchCriteria)
->getItems();
$childIds = [];
foreach ($configurableProducts as $product) {
$configurableIdsOfSkus[$product->getSku()] = $product->getId();
if ($product->getTypeId() != 'configurable') {
$childIds[] = $product->getId();
}
}
$parentIdsOfChildIds = [];
foreach ($childSkusOfParentSkus as $parentSku => $childSkus) {
foreach ($childSkus as $childSku) {
$childId = $configurableIdsOfSkus[$childSku];
$parentIdsOfChildIds[$childId][] = $configurableIdsOfSkus[$parentSku];
}
}
/**
* Assert there are parent configurable products ids in result of getRelationsByChildren method
* and they are related to child ids.
*/
$result = $this->model->getRelationsByChildren($childIds);
$sortedResult = $this->sortParentIdsOfChildIds($result);
$sortedExpected = $this->sortParentIdsOfChildIds($parentIdsOfChildIds);
$this->assertEquals($sortedExpected, $sortedResult);
}
/**
* Sorts the "Parent Ids Of Child Ids" type of the array
*
* @param array $array
* @return array
*/
private function sortParentIdsOfChildIds(array $array): array
{
foreach ($array as &$parentIds) {
sort($parentIds, SORT_NUMERIC);
}
ksort($array, SORT_NUMERIC);
return $array;
}
}
@@ -0,0 +1,106 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Model\Sales\AdminOrder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Model\Quote\Address\Rate;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use Magento\Sales\Model\AdminOrder\Create;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item as OrderItem;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Reorder with Configurable product integration tests.
*
* @see Create
* @magentoAppArea adminhtml
*/
class ReorderTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Create
*/
private $model;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model =$this->objectManager->get(Create::class);
}
/**
* Check Custom Price after reordering with Configurable product.
*
* @return void
* @magentoDataFixture Magento/ConfigurableProduct/_files/order_item_with_configurable_and_options.php
*/
public function testReorderConfigurableProductWithCustomPrice(): void
{
$customPrice = 300;
/** @var $order Order */
$order = $this->objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$this->model->initFromOrder($order);
/** @var QuoteItem[] $quoteItems */
$quoteItems = $this->model->getQuote()->getAllItems();
$firstQuoteItem = array_shift($quoteItems);
self::assertNull($firstQuoteItem->getParentItemId());
self::assertEquals($customPrice, (int)$firstQuoteItem->getCustomPrice());
foreach ($quoteItems as $quoteItem) {
self::assertEquals($firstQuoteItem->getId(), $quoteItem->getParentItemId());
self::assertEquals(0, (int)$quoteItem->getCustomPrice());
}
$customerMock = $this->getMockBuilder(\Magento\Customer\Model\Data\Customer::class)
->disableOriginalConstructor()
->setMethods(
[
'getGroupId',
'getEmail',
'_getExtensionAttributes'
]
)->getMock();
$customerMock->method('getGroupId')
->willReturn(1);
$customerMock->method('getEmail')
->willReturn('customer@example.com');
$customerMock->method('_getExtensionAttributes')
->willReturn(null);
$this->model->getQuote()->setCustomer($customerMock);
$shippingMethod = 'freeshipping_freeshipping';
/** @var Rate $rate */
$rate = $this->objectManager->create(Rate::class);
$rate->setCode($shippingMethod);
$this->model->getQuote()->getShippingAddress()->addShippingRate($rate);
$this->model->setPaymentData(['method' => 'checkmo']);
$this->model->setIsValidate(true)->importPostData(['shipping_method' => $shippingMethod]);
$newOrder = $this->model->createOrder();
/** @var OrderItem[] $orderItems */
$orderItems = $newOrder->getAllItems();
$firstOrderItem = array_shift($orderItems);
self::assertNull($firstOrderItem->getParentItemId());
self::assertEquals($customPrice, (int)$firstOrderItem->getPrice());
foreach ($orderItems as $orderItem) {
self::assertEquals($firstOrderItem->getId(), $orderItem->getParentItemId());
self::assertEquals(0, (int)$orderItem->getPrice());
}
}
}