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,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Category\Checkboxes;
use Magento\Catalog\Helper\DefaultCategory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks category chooser block behaviour
*
* @see \Magento\Catalog\Block\Adminhtml\Category\Checkboxes\Tree
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class TreeTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Tree */
private $block;
/** @var SerializerInterface */
private $json;
/** @var DefaultCategory */
private $defaultCategoryHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Tree::class);
$this->json = $this->objectManager->get(SerializerInterface::class);
$this->defaultCategoryHelper = $this->objectManager->get(DefaultCategory::class);
}
/**
* @return void
*/
public function testSetGetCategoryIds(): void
{
$this->block->setCategoryIds([1, 4, 7, 56, 2]);
$this->assertEquals([1, 4, 7, 56, 2], $this->block->getCategoryIds());
}
/**
* @magentoDataFixture Magento/Catalog/_files/categories.php
*
* @return void
*/
public function testGetTreeJson(): void
{
$jsonTree = $this->block->getTreeJson();
$this->assertStringContainsString('Default Category (4)', $jsonTree);
$this->assertStringContainsString('Category 1.1 (2)', $jsonTree);
$this->assertStringContainsString('Category 1.1.1 (1)', $jsonTree);
$this->assertStringContainsString('Category 2 (0)', $jsonTree);
$this->assertStringContainsString('Movable (0)', $jsonTree);
$this->assertStringContainsString('Movable Position 1 (0)', $jsonTree);
$this->assertStringContainsString('Movable Position 2 (2)', $jsonTree);
$this->assertStringContainsString('Movable Position 3 (2)', $jsonTree);
$this->assertStringContainsString('Category 12 (2)', $jsonTree);
$this->assertStringMatchesFormat('%s"path":"1\/2\/%s\/%s\/%s"%s', $jsonTree);
}
/**
* @return void
*/
public function testGetTreeJsonWithSelectedCategory(): void
{
$this->block->setCategoryIds($this->defaultCategoryHelper->getId());
$result = $this->json->unserialize($this->block->getTreeJson());
$item = reset($result);
$this->assertNotEmpty($item);
$this->assertStringContainsString('Default Category', $item['text']);
$this->assertTrue($item['checked']);
}
}
@@ -0,0 +1,177 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Category\Tab;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\Framework\ObjectManagerInterface;
use Magento\Catalog\Api\Data\ProductInterface;
/**
* Checks grid data on the tab 'Products in Category' category view page.
*
* @see \Magento\Catalog\Block\Adminhtml\Category\Tab\Product
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class ProductTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var Registry */
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('category');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_with_two_products.php
* @magentoDataFixture Magento/Catalog/_files/product_associated.php
* @magentoDataFixture Magento/Catalog/_files/simple_product_disabled.php
* @dataProvider optionsFilterProvider
* @param string $filterColumn
* @param int $categoryId
* @param int $storeId
* @param array $items
* @return void
*/
public function testFilterProductInCategory(string $filterColumn, int $categoryId, int $storeId, array $items): void
{
$collection = $this->filterProductInGrid($filterColumn, $categoryId, $storeId);
$this->assertCount(count($items), $collection->getItems());
foreach ($items as $item) {
$this->assertNotNull($collection->getItemByColumnValue(ProductInterface::SKU, $item));
}
}
/**
* @magentoDataFixture Magento/Catalog/_files/category.php
* @return void
*/
public function testEmptyProductIdColumnFilter(): void
{
$this->assertCount(0, $this->filterProductInGrid('in_category=1', 333, 1)->getItems());
}
/**
* Different variations for filter test.
*
* @return array
*/
public function optionsFilterProvider(): array
{
return [
'filter_yes' => [
'filter_column' => 'in_category=1',
'id_category' => 333,
'store_id' => 1,
'items' => [
'simple333',
'simple2',
],
],
'filter_no' => [
'filter_column' => 'in_category=0',
'id_category' => 333,
'store_id' => 1,
'items' => [
'product_disabled',
'simple',
],
],
'filter_any' => [
'filter_column' => "",
'id_category' => 333,
'store_id' => 1,
'items' => [
'product_disabled',
'simple333',
'simple2',
'simple',
],
],
'flag_status' => [
'filter_column' => 'status=1',
'id_category' => 333,
'store_id' => 1,
'items' => [
'simple333',
'simple2',
'simple',
],
],
];
}
/**
* Filter product in grid
*
* @param string $filterOption
* @param int $categoryId
* @param int $storeId
* @return AbstractCollection
*/
private function filterProductInGrid(string $filterOption, int $categoryId, int $storeId): AbstractCollection
{
$this->registerCategory($this->categoryRepository->get($categoryId));
$block = $this->layout->createBlock(Product::class);
$block->getRequest()->setParams([
'id' => $categoryId,
'filter' => base64_encode($filterOption),
'store' => $storeId,
]);
$block->toHtml();
return $block->getCollection();
}
/**
* Register category in registry
*
* @param CategoryInterface $category
* @return void
*/
private function registerCategory(CategoryInterface $category): void
{
$this->registry->unregister('category');
$this->registry->register('category', $category);
}
}
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Category;
/**
* @magentoAppArea adminhtml
*/
class TreeTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Catalog\Block\Adminhtml\Category\Tree */
protected $_block;
protected function setUp(): void
{
parent::setUp();
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Block\Adminhtml\Category\Tree::class
);
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Adminhtml\Category\Tree::class,
'',
[]
);
}
public function testGetSuggestedCategoriesJson()
{
$this->assertEquals(
'[{"id":"2","children":[],"is_active":"1","label":"Default Category"}]',
$this->_block->getSuggestedCategoriesJson('Default')
);
$this->assertEquals('[]', $this->_block->getSuggestedCategoriesJson(strrev('Default')));
}
}
@@ -0,0 +1,65 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab;
/**
* @magentoAppArea adminhtml
*/
class FrontTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front
*/
private $block;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $layout \Magento\Framework\View\Layout */
$layout = $this->objectManager->create(\Magento\Framework\View\LayoutInterface::class);
$this->block = $layout->createBlock(\Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front::class);
}
/**
* @param $attributeCode
* @dataProvider toHtmlDataProvider
*/
public function testToHtml($attributeCode)
{
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $model */
$model = $this->objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$model->loadByCode(\Magento\Catalog\Model\Product::ENTITY, $attributeCode);
/** @var \Magento\Framework\Registry $coreRegistry */
$coreRegistry = $this->objectManager->get(\Magento\Framework\Registry::class);
$coreRegistry->unregister('entity_attribute');
$coreRegistry->register('entity_attribute', $model);
$this->assertMatchesRegularExpression('/<select\sid="is_searchable".*disabled="disabled"/', $this->block->toHtml());
}
/**
* @return array
*/
public function toHtmlDataProvider()
{
return [
['visibility'],
['url_key'],
['status'],
['price_type'],
['category_ids'],
['media_gallery'],
['country_of_manufacture'],
];
}
}
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Attribute\Set\Toolbar;
/**
* @magentoAppArea adminhtml
*/
class AddTest extends \PHPUnit\Framework\TestCase
{
public function testToHtmlFormId()
{
/** @var $layout \Magento\Framework\View\Layout */
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$block = $layout->addBlock(\Magento\Catalog\Block\Adminhtml\Product\Attribute\Set\Toolbar\Add::class, 'block');
$block->setArea('adminhtml')->unsetChild('setForm');
$childBlock = $layout->addBlock(\Magento\Framework\View\Element\Template::class, 'setForm', 'block');
$form = new \Magento\Framework\DataObject();
$childBlock->setForm($form);
$expectedId = '12121212';
$this->assertStringNotContainsString($expectedId, $block->toHtml());
$form->setId($expectedId);
$this->assertStringContainsString($expectedId, $block->toHtml());
}
}
@@ -0,0 +1,621 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Block\Product\View\Options\AbstractRenderCustomOptionsTest;
use Magento\Catalog\Helper\Product as HelperProduct;
use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface;
use Magento\Catalog\Model\Product\Option;
use Magento\Catalog\Model\Product\Option\Value;
use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\TestFramework\Helper\Xpath;
/**
* Test cases related to check that simple product custom option renders as expected.
*
* @magentoAppArea adminhtml
*/
class OptionsTest extends AbstractRenderCustomOptionsTest
{
/** @var HelperProduct */
private $helperProduct;
/** @var DataObjectFactory */
private $dataObjectFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->helperProduct = $this->objectManager->get(HelperProduct::class);
$this->dataObjectFactory = $this->objectManager->get(DataObjectFactory::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @return void
*/
public function testRenderCustomOptionsWithoutOptions(): void
{
$product = $this->productRepository->get('simple');
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
"//fieldset[@id='product_composite_configure_fields_options']",
$this->getOptionHtml($product)
),
'The option block is expected to be empty!'
);
}
/**
* Check that options from text group(field, area) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider renderCustomOptionsFromTextGroupProvider
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromTextGroup(array $optionData, array $checkArray): void
{
$this->assertTextOptionRenderingOnProduct('simple', $optionData, $checkArray);
}
/**
* Provides test data to verify the display of text type options.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @return array
*/
public function renderCustomOptionsFromTextGroupProvider(): array
{
return [
'type_text_required_field' => [
[
Option::KEY_TITLE => 'Test option type text 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 0,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
],
[
'contains' => [
'block_with_required_class' => '<div class="field admin__field">',
'title' => 'Test option type text 1',
],
'equals_xpath' => [
'zero_price' => [
'xpath' => "//label[contains(@class, 'admin__field-label')]/span",
'message' => 'Expected empty price is incorrect or missing!',
'expected' => 0,
],
],
],
],
'type_text_is_required_option' => [
[
Option::KEY_TITLE => 'Test option type text 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 0,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
],
[
'contains' => [
'block_with_required_class' => '<div class="field admin__field required _required">',
],
],
],
'type_text_fixed_positive_price' => [
[
Option::KEY_TITLE => 'Test option type text 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
],
[
'contains' => [
'price' => 'data-price-amount="50"',
],
'equals_xpath' => [
'sign_price' => [
'xpath' => "//label[contains(@class, 'admin__field-label')]/span[contains(text(), '+')]",
'message' => 'Expected positive price is incorrect or missing!',
],
],
],
],
'type_text_fixed_negative_price' => [
[
Option::KEY_TITLE => 'Test option type text 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => -50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
],
[
'contains' => [
'price' => 'data-price-amount="50"',
],
'equals_xpath' => [
'sign_price' => [
'xpath' => "//label[contains(@class, 'admin__field-label')]/span[contains(text(), '-')]",
'message' => 'Expected negative price is incorrect or missing!',
],
],
],
],
'type_text_percent_price' => [
[
Option::KEY_TITLE => 'Test option type text 5',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_MAX_CHARACTERS => 0,
],
[
'contains' => [
'price' => 'data-price-amount="5"',
],
],
],
'type_text_max_characters' => [
[
Option::KEY_TITLE => 'Test option type text 6',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 99,
],
[
'max_characters' => (string)__('Maximum number of characters:') . ' <strong>99</strong>',
],
],
'type_field' => [
[
Option::KEY_TITLE => 'Test option type field 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
'configure_option_value' => 'Type field option value',
],
[
'equals_xpath' => [
'control_price_attribute' => [
'xpath' => "//input[@id='options_%s_text' and @price='%s']",
'message' => 'Expected input price is incorrect or missing!',
],
'default_option_value' => [
'xpath' => "//input[@id='options_%s_text' and @value='Type field option value']",
'message' => 'Expected input default value is incorrect or missing!',
],
],
],
],
'type_area' => [
[
Option::KEY_TITLE => 'Test option type area 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_MAX_CHARACTERS => 0,
'configure_option_value' => 'Type area option value',
],
[
'equals_xpath' => [
'control_price_attribute' => [
'xpath' => "//textarea[@id='options_%s_text' and @price='%s']",
'message' => 'Expected textarea price is incorrect or missing!',
],
'default_option_value' => [
'xpath' => "//textarea[@id='options_%s_text' "
. "and contains(text(), 'Type area option value')]",
'message' => 'Expected textarea default value is incorrect or missing!',
],
],
],
],
];
}
/**
* Check that options from select group(drop-down, radio buttons, checkbox, multiple select) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider renderCustomOptionsFromSelectGroupProvider
* @param array $optionData
* @param array $optionValueData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromSelectGroup(
array $optionData,
array $optionValueData,
array $checkArray
): void {
$this->assertSelectOptionRenderingOnProduct('simple', $optionData, $optionValueData, $checkArray);
}
/**
* Provides test data to verify the display of select type options.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @return array
*/
public function renderCustomOptionsFromSelectGroupProvider(): array
{
return [
'type_select_required_field' => [
[
Option::KEY_TITLE => 'Test option type select 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Select value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'contains' => [
'block_with_required_class' => '<div class="admin__field field">',
'title' => '<span>Test option type select 1</span>',
],
'equals_xpath' => [
'required_element' => [
'xpath' => "//select[@id='select_%s']",
'message' => 'Expected select type is incorrect or missing!',
],
],
],
],
'type_select_is_required_option' => [
[
Option::KEY_TITLE => 'Test option type select 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Select value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'contains' => [
'block_with_required_class' => '<div class="admin__field field _required">',
],
],
],
'type_drop_down_with_selected' => [
[
Option::KEY_TITLE => 'Test option type drop-down 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 0,
'configure_option_value' => 'Drop-down value 1',
],
[
Value::KEY_TITLE => 'Drop-down value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'equals_xpath' => [
'element_type' => [
'xpath' => "//select[contains(@class, 'admin__control-select')]",
'message' => 'Expected drop down type is incorrect or missing!',
],
'default_value' => [
'xpath' => "//option[contains(text(), '" . __('-- Please Select --') . "')]",
'message' => 'Expected default value is incorrect or missing!',
],
'selected_value' => [
'xpath' => "//option[@selected='selected' and contains(text(), 'Drop-down value 1')]",
'message' => 'Expected selected value is incorrect or missing!',
],
],
],
],
'type_multiple_with_selected' => [
[
Option::KEY_TITLE => 'Test option type multiple 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE,
Option::KEY_IS_REQUIRE => 0,
'configure_option_value' => 'Multiple value 1',
],
[
Value::KEY_TITLE => 'Multiple value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'equals_xpath' => [
'element_type' => [
'xpath' => "//select[contains(@class, 'admin__control-multiselect') "
. "and @multiple='multiple']",
'message' => 'Expected multiple type is incorrect or missing!',
],
'selected_value' => [
'xpath' => "//option[@selected='selected' and contains(text(), 'Multiple value 1')]",
'message' => 'Expected selected value is incorrect or missing!',
],
],
],
],
'type_checkable_required_field' => [
[
Option::KEY_TITLE => 'Test option type checkable 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Checkable value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'equals_xpath' => [
'required_checkable_option' => [
'xpath' => "//div[@id='options-%s-list']",
'message' => 'Expected checkable option is incorrect or missing!',
],
'option_value_title' => [
'xpath' => "//label[@for='options_%s_2']/span[contains(text(), 'Checkable value 1')]",
'message' => 'Expected option value title is incorrect or missing!',
],
],
],
],
'type_radio_is_required_option' => [
[
Option::KEY_TITLE => 'Test option type radio 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Radio value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'equals_xpath' => [
'span_container' => [
'xpath' => "//span[@id='options-%s-container']",
'message' => 'Expected span container is incorrect or missing!',
],
'default_option_value' => [
'xpath' => "//label[@for='options_%s']/span[contains(text(), '" . __('None') . "')]",
'message' => 'Expected default option value is incorrect or missing!',
'expected' => 0,
],
],
],
],
'type_radio_with_selected' => [
[
Option::KEY_TITLE => 'Test option type radio 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 0,
'configure_option_value' => 'Radio value 1',
],
[
Value::KEY_TITLE => 'Radio value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
],
[
'equals_xpath' => [
'default_option_value' => [
'xpath' => "//label[@for='options_%s']/span[contains(text(), '" . __('None') . "')]",
'message' => 'Expected default option value is incorrect or missing!',
],
'element_type' => [
'xpath' => "//input[@id='options_%s_2' and contains(@class, 'admin__control-radio')]",
'message' => 'Expected radio type is incorrect or missing!',
],
'selected_value' => [
'xpath' => "//input[@id='options_%s_2' and @checked='checked']",
'message' => 'Expected selected option value is incorrect or missing!',
],
],
],
],
'type_checkbox_is_required_option' => [
[
Option::KEY_TITLE => 'Test option type checkbox 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Checkbox value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => '',
],
[
'equals_xpath' => [
'span_container' => [
'xpath' => "//span[@id='options-%s-container']",
'message' => 'Expected span container is incorrect or missing!',
],
],
],
],
'type_checkbox_with_selected' => [
[
Option::KEY_TITLE => 'Test option type checkbox 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 0,
'configure_option_value' => 'Checkbox value 1',
],
[
Value::KEY_TITLE => 'Checkbox value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => '',
],
[
'equals_xpath' => [
'element_type' => [
'xpath' => "//input[@id='options_%s_2' and contains(@class, 'admin__control-checkbox')]",
'message' => 'Expected checkbox type is incorrect or missing!',
],
'selected_value' => [
'xpath' => "//input[@id='options_%s_2' and @checked='checked']",
'message' => 'Expected selected option value is incorrect or missing!',
],
],
],
],
];
}
/**
* @inheritdoc
*/
protected function addOptionToProduct(
ProductInterface $product,
array $optionData,
array $optionValueData = []
): ProductInterface {
$product = parent::addOptionToProduct($product, $optionData, $optionValueData);
if (isset($optionData['configure_option_value'])) {
$optionValue = $optionData['configure_option_value'];
$option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]);
if (!empty($optionValueData)) {
$optionValueObject = $this->findOptionValueByTitle($option, $optionValue);
$optionValue = $option->getType() === Option::OPTION_TYPE_CHECKBOX
? [$optionValueObject->getOptionTypeId()]
: $optionValueObject->getOptionTypeId();
}
/** @var DataObject $request */
$buyRequest = $this->dataObjectFactory->create();
$buyRequest->setData([
'qty' => 1,
'options' => [$option->getId() => $optionValue],
]);
$this->helperProduct->prepareProductOptions($product, $buyRequest);
}
return $product;
}
/**
* @inheritdoc
*/
protected function baseOptionAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
if (isset($checkArray['contains'])) {
foreach ($checkArray['contains'] as $needle) {
$this->assertStringContainsString($needle, $optionHtml);
}
}
}
/**
* @inheritdoc
*/
protected function additionalTypeTextAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
parent::additionalTypeTextAsserts($option, $optionHtml, $checkArray);
if (isset($checkArray['equals_xpath'])) {
foreach ($checkArray['equals_xpath'] as $key => $value) {
$value['args'] = $key === 'control_price_attribute' ? [(float)$option->getPrice()] : [];
$this->assertEqualsXpath($option, $optionHtml, $value);
}
}
}
/**
* @inheritdoc
*/
protected function additionalTypeSelectAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
parent::additionalTypeSelectAsserts($option, $optionHtml, $checkArray);
if (isset($checkArray['equals_xpath'])) {
foreach ($checkArray['equals_xpath'] as $value) {
$this->assertEqualsXpath($option, $optionHtml, $value);
}
}
}
/**
* @inheritdoc
*/
protected function getHandlesList(): array
{
return [
'default',
'CATALOG_PRODUCT_COMPOSITE_CONFIGURE',
'catalog_product_view_type_simple',
];
}
/**
* @inheritdoc
*/
protected function getMaxCharactersCssClass(): string
{
return 'class="note"';
}
/**
* @inheritdoc
*/
protected function getOptionsBlockName(): string
{
return 'product.composite.fieldset.options';
}
/**
* Checks that the xpath string is equal to the expected value
*
* @param ProductCustomOptionInterface $option
* @param string $html
* @param array $xpathData
* @return void
*/
private function assertEqualsXpath(ProductCustomOptionInterface $option, string $html, array $xpathData): void
{
$args = array_merge([$option->getOptionId()], $xpathData['args'] ?? []);
$expected = $xpathData['expected'] ?? 1;
$this->assertEquals(
$expected,
Xpath::getElementsCountForXpath(sprintf($xpathData['xpath'], ...$args), $html),
$xpathData['message']
);
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\Product as HelperProduct;
use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test Qty block in composite product configuration layout
*
* @see \Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Qty
* @magentoAppArea adminhtml
*/
class QtyTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Qty */
private $block;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Registry */
private $registry;
/** @var HelperProduct */
private $helperProduct;
/** @var DataObjectFactory */
private $dataObjectFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Qty::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->helperProduct = $this->objectManager->get(HelperProduct::class);
$this->dataObjectFactory = $this->objectManager->get(DataObjectFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_product');
$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);
$this->assertEquals(
$product->getId(),
$this->block->getProduct()->getId(),
'The expected product is missing in the Qty block!'
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @dataProvider getQtyValueProvider
* @param bool $isQty
* @param int $qty
* @return void
*/
public function testGetQtyValue(bool $isQty = false, int $qty = 1): void
{
$product = $this->productRepository->get('simple-1');
if ($isQty) {
/** @var DataObject $request */
$buyRequest = $this->dataObjectFactory->create();
$buyRequest->setData(['qty' => $qty]);
$this->helperProduct->prepareProductOptions($product, $buyRequest);
}
$this->registerProduct($product);
$this->assertEquals($qty, $this->block->getQtyValue(), 'Expected block qty value is incorrect!');
}
/**
* Provides test data to verify block qty value.
*
* @return array
*/
public function getQtyValueProvider(): array
{
return [
'with_qty' => [
'is_qty' => true,
'qty' => 5,
],
'without_qty' => [],
];
}
/**
* Register the product
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('current_product');
$this->registry->unregister('product');
$this->registry->register('current_product', $product);
$this->registry->register('product', $product);
}
}
@@ -0,0 +1,121 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Composite;
use Magento\Backend\Model\View\Result\Page;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Test Fieldset block in composite product configuration layout
*
* @see \Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset
* @magentoAppArea adminhtml
*/
class FieldsetTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Page */
private $page;
/** @var Registry */
private $registry;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var string */
private $fieldsetXpath = "//fieldset[@id='product_composite_configure_fields_%s']";
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->page = $this->objectManager->get(PageFactory::class)->create();
$this->registry = $this->objectManager->get(Registry::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_product');
$this->registry->unregister('product');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_options.php
* @return void
*/
public function testRenderHtml(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$this->preparePage();
$fieldsetBlock = $this->page->getLayout()->getBlock('product.composite.fieldset');
$this->assertNotFalse($fieldsetBlock, 'Expected fieldset block is missing!');
$html = $fieldsetBlock->toHtml();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($this->fieldsetXpath, 'options'), $html),
'Expected options block is missing!'
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($this->fieldsetXpath, 'qty'), $html),
'Expected qty block is missing!'
);
}
/**
* Prepare page layout
*
* @return void
*/
private function preparePage(): void
{
$this->page->addHandle([
'default',
'CATALOG_PRODUCT_COMPOSITE_CONFIGURE',
'catalog_product_view_type_simple',
]);
$this->page->getLayout()->generateXml();
}
/**
* Register the product
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('current_product');
$this->registry->unregister('product');
$this->registry->register('current_product', $product);
$this->registry->register('product', $product);
}
}
@@ -0,0 +1,49 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Edit;
/**
* @magentoAppArea adminhtml
*/
class JsTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testGetAllRatesByProductClassJson()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Tax\Model\Calculation\Rule $fixtureTaxRule */
$fixtureTaxRule = $objectManager->create(\Magento\Tax\Model\Calculation\Rule::class);
$fixtureTaxRule->load('Test Rule', 'code');
$defaultCustomerTaxClass = 3;
$fixtureTaxRule
->setCustomerTaxClassIds(array_merge($fixtureTaxRule->getCustomerTaxClasses(), [$defaultCustomerTaxClass]))
->setProductTaxClassIds($fixtureTaxRule->getProductTaxClasses())
->setTaxRateIds($fixtureTaxRule->getRates())
->saveCalculationData();
/** @var \Magento\Catalog\Block\Adminhtml\Product\Edit\Js $block */
$block = $objectManager->create(\Magento\Catalog\Block\Adminhtml\Product\Edit\Js::class);
$jsonResult = $block->getAllRatesByProductClassJson();
$this->assertJson($jsonResult, 'Resulting JSON is invalid.');
$decodedResult = json_decode($jsonResult, true);
$this->assertNotNull($decodedResult, 'Cannot decode resulting JSON.');
$noneTaxClass = 0;
$defaultProductTaxClass = 2;
$expectedProductTaxClasses = array_unique(
array_merge($fixtureTaxRule->getProductTaxClasses(), [$defaultProductTaxClass, $noneTaxClass])
);
foreach ($expectedProductTaxClasses as $taxClassId) {
$this->assertArrayHasKey(
"value_{$taxClassId}",
$decodedResult,
"Rates for tax class with ID '{$taxClassId}' is missing."
);
}
$this->assertStringContainsString('7.5', $jsonResult, 'Rates for tax classes looks to be invalid.');
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Base alert's tab test logic
*/
abstract class AbstractAlertTest extends TestCase
{
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var RequestInterface */
protected $request;
/** @var StoreManagerInterface */
private $storeManager;
/** @var ProductResource */
private $productResource;
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because module Magento_Catalog is independent of Magento_ProductAlert
if (!$moduleManager->isEnabled('Magento_ProductAlert')) {
self::markTestSkipped('Magento_ProductAlert module disabled.');
}
}
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->request = $this->objectManager->get(RequestInterface::class);
$this->productResource = $this->objectManager->get(ProductResource::class);
}
/**
* Prepare request
*
* @param string|null $sku
* @param string|null $storeCode
* @return void
*/
protected function prepareRequest(?string $sku = null, ?string $storeCode = null): void
{
$productId = (int)$this->productResource->getIdBySku($sku);
$storeId = $storeCode ? (int)$this->storeManager->getStore($storeCode)->getId() : null;
$this->request->setParams(['id' => $productId, 'store' => $storeId]);
}
/**
* Assert grid url
*
* @param string $url
* @param string|null $storeCode
* @return void
*/
protected function assertGridUrl(string $url, ?string $storeCode): void
{
$storeId = $storeCode ? (int)$this->storeManager->getStore($storeCode)->getId() : Store::DEFAULT_STORE_ID;
$this->assertStringContainsString(sprintf('/store/%s', $storeId), $url);
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts;
use Magento\Framework\View\LayoutInterface;
/**
* Check price alert grid
*
* @see \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts\Price
*
* @magentoAppArea adminhtml
*/
class PriceTest extends AbstractAlertTest
{
/** @var Price */
private $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Price::class);
}
/**
* @dataProvider alertsDataProvider
*
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/ProductAlert/_files/product_alert.php
* @magentoDataFixture Magento/ProductAlert/_files/price_alert_on_second_website.php
*
* @param string $sku
* @param string $expectedEmail
* @param string|null $storeCode
* @return void
*/
public function testGridCollectionWithStoreId(string $sku, string $expectedEmail, ?string $storeCode = null): void
{
$this->prepareRequest($sku, $storeCode);
$collection = $this->block->getPreparedCollection();
$this->assertCount(1, $collection);
$this->assertEquals($expectedEmail, $collection->getFirstItem()->getEmail());
}
/**
* @return array
*/
public function alertsDataProvider(): array
{
return [
'without_store_id_filter' => [
'product_sku' => 'simple',
'expected_customer_emails' => 'customer@example.com',
],
'with_store_id_filter' => [
'product_sku' => 'simple_on_second_website_for_price_alert',
'expected_customer_emails' => 'customer_second_ws_with_addr@example.com',
'store_code' => 'fixture_third_store',
],
];
}
/**
* @dataProvider storeProvider
*
* @param string|null $storeCode
* @return void
*/
public function testGetGridUrl(?string $storeCode): void
{
$this->prepareRequest(null, $storeCode);
$this->assertGridUrl($this->block->getGridUrl(), $storeCode);
}
/**
* @return array
*/
public function storeProvider(): array
{
return [
'without_store_id_param' => [
'store_code' => null,
],
'with_store_id_param' => [
'store_code' => 'default',
],
];
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts;
use Magento\Framework\View\LayoutInterface;
/**
* Check stock alert grid
*
* @see \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts\Stock
*
* @magentoAppArea adminhtml
*/
class StockTest extends AbstractAlertTest
{
/** @var Stock */
private $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Stock::class);
}
/**
* @dataProvider alertsDataProvider
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/ProductAlert/_files/product_alert.php
* @magentoDataFixture Magento/ProductAlert/_files/stock_alert_on_second_website.php
*
* @param string $sku
* @param string $expectedEmail
* @param string|null $storeCode
* @return void
*/
public function testGridCollectionWithStoreId(string $sku, string $expectedEmail, ?string $storeCode = null): void
{
$this->prepareRequest($sku, $storeCode);
$collection = $this->block->getPreparedCollection();
$this->assertCount(1, $collection);
$this->assertEquals($expectedEmail, $collection->getFirstItem()->getEmail());
}
/**
* @return array
*/
public function alertsDataProvider(): array
{
return [
'without_store_id_filter' => [
'product_sku' => 'simple',
'expected_customer_emails' => 'customer@example.com',
],
'with_store_id_filter' => [
'product_sku' => 'simple_on_second_website',
'expected_customer_emails' => 'customer_second_ws_with_addr@example.com',
'store_code' => 'fixture_third_store',
],
];
}
/**
* @dataProvider storeProvider
*
* @param string|null $storeCode
* @return void
*/
public function testGetGridUrl(?string $storeCode): void
{
$this->prepareRequest(null, $storeCode);
$this->assertGridUrl($this->block->getGridUrl(), $storeCode);
}
/**
* @return array
*/
public function storeProvider(): array
{
return [
'without_store_id_param' => [
'store_code' => null,
],
'with_store_id_param' => [
'store_code' => 'default',
],
];
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options;
/**
* @magentoAppArea adminhtml
*/
class OptionTest extends \PHPUnit\Framework\TestCase
{
public function testGetOptionValuesCaching()
{
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Option::class
);
/** @var $productWithOptions \Magento\Catalog\Model\Product */
$productWithOptions = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$productWithOptions->setTypeId(
'simple'
)->setId(
1
)->setAttributeSetId(
4
)->setWebsiteIds(
[1]
)->setName(
'Simple Product With Custom Options'
)->setSku(
'simple'
)->setPrice(
10
)->setMetaTitle(
'meta title'
)->setMetaKeyword(
'meta keyword'
)->setMetaDescription(
'meta description'
)->setVisibility(
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
)->setStatus(
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
);
$product = clone $productWithOptions;
/** @var $option \Magento\Catalog\Model\Product\Option */
$option = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product\Option::class,
['data' => ['id' => 1, 'title' => 'some_title']]
);
$productWithOptions->setOptions([$option]);
$block->setProduct($productWithOptions);
$this->assertNotEmpty($block->getOptionValues());
$block->setProduct($product);
$this->assertNotEmpty($block->getOptionValues());
$block->setIgnoreCaching(true);
$this->assertEmpty($block->getOptionValues());
}
}
@@ -0,0 +1,28 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Type;
/**
* @magentoAppArea adminhtml
*/
class SelectTest extends \PHPUnit\Framework\TestCase
{
public function testToHtmlFormId()
{
/** @var $layout \Magento\Framework\View\Layout */
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Type\Select */
$block = $layout->createBlock(
\Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Type\Select::class,
'select'
);
$html = $block->getPriceTypeSelectHtml();
$this->assertStringContainsString('select_<%- data.select_id %>', $html);
$this->assertStringContainsString('[<%- data.select_id %>]', $html);
}
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Helper\Form;
class CategoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppArea adminhtml
*/
public function testGetAfterElementHtml()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\Layout::class,
['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE]
);
$authorization = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\AuthorizationInterface::class,
['aclPolicy' => new \Magento\Framework\Authorization\Policy\DefaultPolicy()]
);
$block = $objectManager->create(
\Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Category::class,
['layout' => $layout, 'authorization' => $authorization]
);
/** @var $formFactory \Magento\Framework\Data\FormFactory */
$formFactory = $objectManager->get(\Magento\Framework\Data\FormFactory::class);
$form = $formFactory->create();
$block->setForm($form);
$this->assertMatchesRegularExpression('/<button[^>]*New\sCategory[^>]*>/', $block->getAfterElementHtml());
}
}
@@ -0,0 +1,272 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Gallery\UpdateHandler;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Registry;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ContentTest extends \PHPUnit\Framework\TestCase
{
/**
* Test subject.
*
* @var Content
*/
private $block;
/**
* @var Registry
*/
private $registry;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @var StoreRepositoryInterface
*/
private $storeRepository;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$gallery = Bootstrap::getObjectManager()->get(Gallery::class);
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$this->block = $layout->createBlock(
Content::class,
'block'
);
$this->block->setElement($gallery);
$this->registry = Bootstrap::getObjectManager()->get(Registry::class);
$this->dataPersistor = Bootstrap::getObjectManager()->get(DataPersistorInterface::class);
$this->storeRepository = Bootstrap::getObjectManager()->create(StoreRepositoryInterface::class);
$this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
}
public function testGetUploader()
{
$this->assertInstanceOf(\Magento\Backend\Block\Media\Uploader::class, $this->block->getUploader());
}
/**
* Test get images json using registry or data persistor.
*
* @dataProvider getImagesAndImageTypesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_image.php
* @magentoAppIsolation enabled
* @param bool $isProductNew
* @return void
*/
public function testGetImagesJson(bool $isProductNew)
{
$this->prepareProduct($isProductNew);
$imagesJson = $this->block->getImagesJson();
$images = json_decode($imagesJson);
$image = array_shift($images);
$this->assertMatchesRegularExpression('~/m/a/magento_image~', $image->file);
$this->assertSame('image', $image->media_type);
$this->assertSame('Image Alt Text', $image->label);
$this->assertSame('Image Alt Text', $image->label_default);
$this->assertMatchesRegularExpression('~/media/catalog/product/m/a/magento_image~', $image->url);
}
/**
* Test get image types json using registry or data persistor.
*
* @dataProvider getImagesAndImageTypesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_image.php
* @magentoAppIsolation enabled
* @param bool $isProductNew
* @return void
*/
public function testGetImageTypes(bool $isProductNew)
{
$this->prepareProduct($isProductNew);
$imageTypes = $this->block->getImageTypes();
foreach ($imageTypes as $type => $image) {
$this->assertSame($type, $image['code']);
$type !== 'swatch_image'
? $this->assertMatchesRegularExpression('/\/m\/a\/magento_image/', $image['value'])
: $this->assertNull($image['value']);
$this->assertSame('[STORE VIEW]', $image['scope']->getText());
$this->assertSame(sprintf('product[%s]', $type), $image['name']);
}
}
/**
* Provide test data for testGetImagesJson() and tesGetImageTypes().
*
* @return array
*/
public function getImagesAndImageTypesDataProvider()
{
return [
[
'isProductNew' => true,
],
[
'isProductNew' => false,
],
];
}
/**
* Tests images positions in store view
*
* @magentoDataFixture Magento/Catalog/_files/product_with_image.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @dataProvider imagesPositionStoreViewDataProvider
* @param string $addFromStore
* @param array $newImages
* @param string $viewFromStore
* @param array $expectedImages
* @return void
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function testImagesPositionStoreView(
string $addFromStore,
array $newImages,
string $viewFromStore,
array $expectedImages
): void {
$storeId = (int)$this->storeRepository->get($addFromStore)->getId();
$product = $this->getProduct($storeId);
$images = $product->getData('media_gallery')['images'];
$images = array_merge($images, $newImages);
$product->setData('media_gallery', ['images' => $images]);
$updateHandler = Bootstrap::getObjectManager()->create(UpdateHandler::class);
$updateHandler->execute($product);
$storeId = (int)$this->storeRepository->get($viewFromStore)->getId();
$product = $this->getProduct($storeId);
$this->registry->register('current_product', $product);
$actualImages = array_map(
function ($item) {
return [
'file' => $item['file'],
'label' => $item['label'],
'position' => $item['position'],
];
},
json_decode($this->block->getImagesJson(), true)
);
$this->assertEquals($expectedImages, array_values($actualImages));
}
/**
* @return array[]
*/
public function imagesPositionStoreViewDataProvider(): array
{
return [
[
'fixture_second_store',
[
[
'file' => '/m/a/magento_small_image.jpg',
'position' => 2,
'label' => 'New Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
]
],
'default',
[
[
'file' => '/m/a/magento_image.jpg',
'label' => 'Image Alt Text',
'position' => 1,
],
[
'file' => '/m/a/magento_small_image.jpg',
'label' => null,
'position' => 2,
],
]
],
[
'fixture_second_store',
[
[
'file' => '/m/a/magento_small_image.jpg',
'position' => 2,
'label' => 'New Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
]
],
'fixture_second_store',
[
[
'file' => '/m/a/magento_image.jpg',
'label' => 'Image Alt Text',
'position' => 1,
],
[
'file' => '/m/a/magento_small_image.jpg',
'label' => 'New Image Alt Text',
'position' => 2,
],
]
]
];
}
/**
* Returns product for testing.
*
* @param int $storeId
* @param string $sku
* @return ProductInterface
*/
private function getProduct(int $storeId = Store::DEFAULT_STORE_ID, string $sku = 'simple'): ProductInterface
{
return $this->productRepository->get($sku, false, $storeId, true);
}
/**
* Prepare product, and set it to registry and data persistor.
*
* @param bool $isProductNew
* @return void
*/
private function prepareProduct(bool $isProductNew)
{
$product = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class)->get('simple');
if ($isProductNew) {
$newProduct = Bootstrap::getObjectManager()->create(Product::class);
$this->registry->register('current_product', $newProduct);
$productData['product'] = $product->getData();
$dataPersistor = Bootstrap::getObjectManager()->get(DataPersistorInterface::class);
$dataPersistor->set('catalog_product', $productData);
} else {
$this->registry->register('current_product', $product);
}
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Helper\Form;
class WeightTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
/**
* @var \Magento\Framework\Data\FormFactory
*/
protected $_formFactory;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_formFactory = $this->_objectManager->create(\Magento\Framework\Data\FormFactory::class);
}
/**
* @param string $type
* @dataProvider virtualTypesDataProvider
*/
public function testProductWithoutWeight($type)
{
/** @var $currentProduct \Magento\Catalog\Model\Product */
$currentProduct = $this->_objectManager->create(\Magento\Catalog\Model\Product::class);
$currentProduct->setTypeInstance($this->_objectManager->create($type));
/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight */
$block = $this->_objectManager->create(\Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight::class);
$form = $this->_formFactory->create();
$form->setDataObject($currentProduct);
$block->setForm($form);
$this->assertMatchesRegularExpression(
'/value="0".*checked="checked"/',
$block->getElementHtml(),
'"Does this have a weight" is set to "Yes" for virtual products'
);
}
/**
* @return array
*/
public static function virtualTypesDataProvider()
{
return [
[\Magento\Catalog\Model\Product\Type\Virtual::class],
[\Magento\Downloadable\Model\Product\Type::class]
];
}
/**
* @param string $type
* @dataProvider physicalTypesDataProvider
*/
public function testProductHasWeight($type)
{
/** @var $currentProduct \Magento\Catalog\Model\Product */
$currentProduct = $this->_objectManager->create(\Magento\Catalog\Model\Product::class);
$currentProduct->setTypeInstance($this->_objectManager->create($type));
/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight */
$block = $this->_objectManager->create(\Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight::class);
$form = $this->_formFactory->create();
$form->setDataObject($currentProduct);
$block->setForm($form);
$this->assertDoesNotMatchRegularExpression(
'/value="0".*checked="checked"/',
$block->getElementHtml(),
'"Does this have a weight" is set to "No" for physical products'
);
}
/**
* @return array
*/
public static function physicalTypesDataProvider()
{
return [[\Magento\Catalog\Model\Product\Type\Simple::class], [\Magento\Bundle\Model\Product\Type::class]];
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Options;
/**
* @magentoAppArea adminhtml
*/
class AjaxTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Block\Adminhtml\Product\Options\Ajax
*/
protected $_block = null;
protected function setUp(): void
{
parent::setUp();
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Adminhtml\Product\Options\Ajax::class
);
}
public function testToHtmlWithoutProducts()
{
$this->assertEquals(json_encode([]), $this->_block->toHtml());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_with_options.php
*/
public function testToHtml()
{
/** @var \Magento\TestFramework\ObjectManager $objectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$objectManager->get(\Magento\Framework\Registry::class)
->register(
'import_option_products',
[$productRepository->get('simple')->getId()]
);
$result = json_decode($this->_block->toHtml(), true);
$this->assertEquals('test_option_code_1', $result[0]['title']);
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Theme\Block\Html\Breadcrumbs as ThemeBreadcrumbs;
use PHPUnit\Framework\TestCase;
/**
* Checks the behavior of breadcrumbs on the category view page.
*
* @magentoAppArea frontend
*/
class BreadcrumbsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var Registry */
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryRepository = $this->objectManager->create(CategoryRepositoryInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
}
/**
* Checks the order of categories in breadcrumbs.
*
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @return void
*/
public function testCategoriesSequence(): void
{
$category = $this->categoryRepository->get(402);
$this->registry->register('current_category', $category);
$themeBreadcrumbs = $this->layout->createBlock(ThemeBreadcrumbs::class, 'breadcrumbs');
$this->layout->createBlock(Breadcrumbs::class);
$html = $themeBreadcrumbs->toHtml();
$actualCategories = preg_replace('/\s+/', '', strip_tags($html));
$expectedCategories = __('Home') . 'Category1' . 'Category1.1' . 'Category1.1.1';
self::assertEquals(
$expectedCategories,
$actualCategories,
'The order of categories in breadcrumbs is not correct!'
);
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Category;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
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;
/**
* Category title check
*
* @magentoAppArea frontend
* @see \Magento\Theme\Block\Html\Title
*/
class TitleTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var StoreManagerInterface */
private $storeManager;
/** @var Registry */
private $registry;
/** @var PageFactory */
private $pageFactory;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_category');
parent::tearDown();
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoDataFixture Magento/Store/_files/store.php
* @return void
*/
public function testCategoryNameOnStoreView(): void
{
$id = 333;
$categoryNameForSecondStore = 'Category Name For Second Store';
$this->executeInStoreContext->execute(
'test',
[$this, 'updateCategoryName'],
$this->categoryRepository->get($id),
$categoryNameForSecondStore
);
$this->registerCategory($this->categoryRepository->get($id));
$this->assertStringContainsString('Category 1', $this->getBlockTitle(), 'Wrong category name');
$this->registerCategory($this->categoryRepository->get($id, $this->storeManager->getStore('test')->getId()));
$this->assertStringContainsString($categoryNameForSecondStore, $this->getBlockTitle(), 'Wrong category name');
}
/**
* Update category name
*
* @param CategoryInterface $category
* @param string $categoryName
* @return void
*/
public function updateCategoryName(CategoryInterface $category, string $categoryName): void
{
$category->setName($categoryName);
$this->categoryRepository->save($category);
}
/**
* Get title block
*
* @return string
*/
private function getBlockTitle(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'catalog_category_view',
]);
$page->getLayout()->generateXml();
$block = $page->getLayout()->getBlock('page.main.title');
$this->assertNotFalse($block);
return $block->stripTags($block->toHtml());
}
/**
* Register category in registry
*
* @param CategoryInterface $category
* @return void
*/
private function registerCategory(CategoryInterface $category): void
{
$this->registry->unregister('current_category');
$this->registry->register('current_category', $category);
}
}
@@ -0,0 +1,528 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Category;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\ResourceModel\Category\Collection;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Data\Tree\Node;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Theme\Block\Html\Topmenu;
use PHPUnit\Framework\TestCase;
/**
* Class checks top menu link behaviour.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class TopMenuTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var Topmenu */
private $block;
/** @var CategoryFactory */
private $categoryFactory;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryFactory = $this->objectManager->get(CategoryFactory::class);
$this->categoryRepository = $this->objectManager->create(CategoryRepositoryInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Topmenu::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* Checks menu item displaying.
*
* @magentoDataFixture Magento/Catalog/_files/category.php
* @return void
*/
public function testTopMenuItemDisplay(): void
{
$output = $this->block->getHtml('level-top', 'submenu', 0);
$this->assertStringContainsString('Category 1', $output);
}
/**
* Checks that menu item is not displayed if the category is disabled or include in menu is disabled.
*
* @dataProvider invisibilityDataProvider
* @param array $data
* @return void
*/
public function testTopMenuItemInvisibility(array $data): void
{
$category = $this->categoryFactory->create();
$category->setData($data);
$this->categoryRepository->save($category);
$output = $this->block->getHtml('level-top', 'submenu', 0);
$this->assertEmpty($output, 'The category is displayed in top menu navigation');
}
/**
* @return array
*/
public function invisibilityDataProvider(): array
{
return [
'include_in_menu_disable' => [
'data' => [
'name' => 'Test Category',
'path' => '1/2/',
'is_active' => '1',
'include_in_menu' => false,
],
],
'category_disable' => [
'data' => [
'name' => 'Test Category 2',
'path' => '1/2/',
'is_active' => false,
'include_in_menu' => true,
],
],
];
}
/**
* Check category visibility in the category tree in the menu
*
* @dataProvider categoriesVisibleInTreeProvider
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoAppIsolation enabled
* @param array $categories
* @param array $expectedCategories
* @return void
*/
public function testCategoriesInTreeVisible(array $categories, array $expectedCategories): void
{
$this->updateCategories($categories);
$output = $this->block->getHtml('level-top', 'submenu', 0);
foreach ($expectedCategories as $data) {
$this->assertStringContainsString(
$data['name'],
$output,
'Category ' . $data['name'] . ' should appear in the menu!'
);
}
}
/**
* @return array
*/
public function categoriesVisibleInTreeProvider(): array
{
return [
'add_in_tree_visible' => [
'categories' => [
[
'is_new_category' => true,
'parent_name' => 'Category 1.1.1',
Category::KEY_NAME => 'Sub Category 1',
Category::KEY_IS_ACTIVE => true,
],
],
'expectedCategories' => [
[
'name' => 'Sub Category 1',
],
],
],
'child_visible_in_tree' => [
'categories' => [
[
'is_new_category' => true,
'parent_name' => 'Category 1.1',
Category::KEY_NAME => 'Sub Category 1',
Category::KEY_IS_ACTIVE => true,
],
[
'is_new_category' => false,
'category_name' => 'Category 1.1',
Category::KEY_IS_ACTIVE => false,
],
],
'expectedCategories' => [
[
'name' => 'Sub Category 1',
],
[
'name' => 'Category 1.1.1',
],
],
],
];
}
/**
* Check invisibility of a category in the category tree in the menu
*
* @dataProvider categoriesInTreeInvisibleProvider
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoAppIsolation enabled
* @param array $categories
* @param array $expectedCategories
* @return void
*/
public function testCategoriesInTreeInvisible(array $categories, array $expectedCategories): void
{
$this->updateCategories($categories);
$output = $this->block->getHtml('level-top', 'submenu', 0);
foreach ($expectedCategories as $data) {
$this->assertStringNotContainsString(
$data['name'],
$output,
'Category ' . $data['name'] . ' should not appear in the menu!'
);
}
}
/**
* @return array
*/
public function categoriesInTreeInvisibleProvider(): array
{
return [
'add_in_tree_category_disable' => [
'categories' => [
[
'is_new_category' => true,
'parent_name' => 'Category 1.1.1',
Category::KEY_NAME => 'Sub Category 1',
Category::KEY_IS_ACTIVE => false,
Category::KEY_INCLUDE_IN_MENU => true,
],
],
'expectedCategories' => [
[
'name' => 'Sub Category 1',
],
],
],
'add_in_tree_include_in_menu_disable' => [
'categories' => [
[
'is_new_category' => true,
'parent_name' => 'Category 1.1.1',
Category::KEY_NAME => 'Sub Category 1',
Category::KEY_IS_ACTIVE => true,
Category::KEY_INCLUDE_IN_MENU => false,
],
],
'expectedCategories' => [
[
'name' => 'Sub Category 1',
],
],
],
'child_invisible_in_tree' => [
'categories' => [
[
'is_new_category' => true,
'parent_name' => 'Default Category',
Category::KEY_NAME => 'Sub Category 1',
Category::KEY_IS_ACTIVE => true,
],
[
'is_new_category' => false,
'category_name' => 'Category 1',
Category::KEY_IS_ACTIVE => false,
],
],
'expectedCategories' => [
[
'name' => 'Category 1.1',
],
[
'name' => 'Category 1.1.1',
],
],
],
];
}
/**
* Check menu structure after moving category or changing position
*
* @dataProvider menuStructureProvider
* @magentoDataFixture Magento/Catalog/_files/categories_no_products_with_two_tree.php
* @magentoAppIsolation enabled
* @param array $moveCategory
* @param array $expectedMenuTree
* @return void
*/
public function testMenuStructure(array $moveCategory, array $expectedMenuTree): void
{
/** @var Category $category */
$category = $this->categoryRepository->get($this->getCategoryIdByName($moveCategory['name']));
$category->move(
$this->getCategoryIdByName($moveCategory['parent_name']),
$this->getCategoryIdByName($moveCategory['after_category_name'])
);
$this->block->getHtml('level-top', 'submenu', 0);
$menuTree = $this->getMenuTree($this->block->getMenu());
$topLevelKeys = array_flip(array_keys($expectedMenuTree));
$actualMenuTree = array_intersect_key($menuTree, $topLevelKeys);
$this->assertEquals(
$expectedMenuTree,
$actualMenuTree,
'Error in displaying the menu tree after moving a category!'
);
}
/**
* @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function menuStructureProvider(): array
{
return [
'move_to_default' => [
'moveCategory' => [
'name' => 'Category 1.1.1',
'parent_name' => 'Default Category',
'after_category_name' => '',
],
'expectedMenuTree' => [
'Category 1.1.1' => ['position' => '1'],
'Category 1' => [
'position' => '2',
'Category 1.1' => ['position' => '2-1'],
],
],
],
'move_to_not_default' => [
'moveCategory' => [
'name' => 'Movable Position 3',
'parent_name' => 'Movable Position 2',
'after_category_name' => '',
],
'expectedMenuTree' => [
'Movable Position 2' => [
'position' => '5',
'Movable Position 3' => ['position' => '5-1'],
],
'Category 12' => ['position' => '6'],
],
],
'move_tree_to_default' => [
'moveCategory' => [
'name' => 'Category 1.1',
'parent_name' => 'Default Category',
'after_category_name' => '',
],
'expectedMenuTree' => [
'Category 1.1' => [
'position' => '1',
'Category 1.1.1' => ['position' => '1-1'],
],
'Category 1' => ['position' => '2'],
],
],
'move_tree_to_other_tree' => [
'moveCategory' => [
'name' => 'Category 2.2',
'parent_name' => 'Category 1.1',
'after_category_name' => 'Category 1.1.1',
],
'expectedMenuTree' => [
'Category 1' => [
'position' => '1',
'Category 1.1' => [
'position' => '1-1',
'Category 1.1.1' => ['position' => '1-1-1'],
'Category 2.2' => [
'position' => '1-1-2',
'Category 2.2.1' => ['position' => '1-1-2-1'],
],
],
],
'Category 2' => [
'position' => '2',
'Category 2.1' => ['position' => '2-1'],
],
],
],
'position_of_categories_in_default' => [
'moveCategory' => [
'name' => 'Category 12',
'parent_name' => 'Default Category',
'after_category_name' => 'Movable',
],
'expectedMenuTree' => [
'Movable' => ['position' => '3'],
'Category 12' => ['position' => '4'],
'Movable Position 1' => ['position' => '5'],
'Movable Position 2' => ['position' => '6'],
'Movable Position 3' => ['position' => '7'],
],
],
'position_of_categories_in_tree' => [
'moveCategory' => [
'name' => 'Movable',
'parent_name' => 'Category 2',
'after_category_name' => 'Category 2.1',
],
'expectedMenuTree' => [
'Category 2' => [
'position' => '2',
'Category 2.1' => ['position' => '2-1'],
'Movable' => ['position' => '2-2'],
'Category 2.2' => [
'position' => '2-3',
'Category 2.2.1' => ['position' => '2-3-1'],
],
],
'Movable Position 1' => ['position' => '3'],
],
],
];
}
/**
* Test the display of category in menu on different websites
*
* @dataProvider multipleWebsitesCategoryDisplayProvider
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoDataFixture Magento/Catalog/_files/category_in_second_root_category.php
* @param string $storeCode
* @param string $expectedCategory
* @param string $notExpectedCategory
* @return void
*/
public function testMultipleWebsitesCategoryDisplay(
string $storeCode,
string $expectedCategory,
string $notExpectedCategory
): void {
$this->storeManager->setCurrentStore($storeCode);
$output = $this->block->getHtml('level-top', 'submenu', 0);
$this->assertStringContainsString(
$expectedCategory,
$output,
'Category "' . $expectedCategory . '" should appear in the menu!'
);
$this->assertStringNotContainsString(
$notExpectedCategory,
$output,
'Category "' . $notExpectedCategory . '" should not appear in the menu!'
);
}
/**
* Provide test data to verify the display of category in menu on different websites.
*
* @return array
*/
public function multipleWebsitesCategoryDisplayProvider(): array
{
return [
'first_website' => [
'storeCode' => 'default',
'expectedCategory' => '>Category 1<',
'notExpectedCategory' => '>Root2 Category 1<',
],
'second_website' => [
'storeCode' => 'test_store_1',
'expectedCategory' => '>Root2 Category 1<',
'notExpectedCategory' => '>Category 1<',
],
];
}
/**
* Update existing categories or create new ones
*
* @param array $categories
* @return void
*/
private function updateCategories(array $categories): void
{
foreach ($categories as $categoryData) {
if (!$categoryData['is_new_category']) {
$category = $this->categoryRepository->get($this->getCategoryIdByName($categoryData['category_name']));
unset($categoryData['category_name']);
} else {
$categoryData[Category::KEY_PARENT_ID] = $this->getCategoryIdByName($categoryData['parent_name']);
unset($categoryData['parent_name']);
$category = $this->categoryFactory->create();
}
unset($categoryData['is_new_category']);
$category->addData($categoryData);
$this->categoryRepository->save($category);
}
}
/**
* Get an array from the menu tree with category identifiers and their position
*
* @param Node $node
* @return array
*/
private function getMenuTree(Node $node): array
{
$nodes = [];
if (!is_null($node->getId())) {
$nodes['position'] = str_replace('nav-', '', $node->getData('position_class'));
}
$childrenNodes = $node->getChildren()->getNodes();
/** @var Node $childNode */
foreach ($childrenNodes as $childNode) {
$name = $childNode->getName();
$nodes[$name] = $this->getMenuTree($childNode);
}
return $nodes;
}
/**
* @param string $name
* @return string|null
*/
private function getCategoryIdByName(string $name): ?string
{
$categoryCollectionFactory = $this->objectManager->get(CollectionFactory::class);
/** @var Collection $categoryCollection */
$categoryCollection = $categoryCollectionFactory->create();
/** @var $category Category */
$category = $categoryCollection
->addAttributeToFilter(CategoryInterface::KEY_NAME, $name)
->setPageSize(1)
->getFirstItem();
return $category->getId();
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Category;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Catalog\Model\GetCategoryByName;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test for view category block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class ViewTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var GetCategoryByName */
private $getCategoryByName;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var LayoutInterface */
private $layout;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->getCategoryByName = $this->objectManager->get(GetCategoryByName::class);
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_category');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_with_cms_block.php
*
* @return void
*/
public function testCmsBlockDisplayedOnCategory(): void
{
$storeId = (int)$this->storeManager->getStore('default')->getId();
$categoryId = $this->getCategoryByName->execute('Category with cms block')->getId();
$category = $this->categoryRepository->get($categoryId, $storeId);
$this->registerCategory($category);
$block = $this->layout->createBlock(View::class)->setTemplate('Magento_Catalog::category/cms.phtml');
$this->assertStringContainsString('<h1>Fixture Block Title</h1>', $block->toHtml());
}
/**
* Register category in registry
*
* @param CategoryInterface $category
* @return void
*/
private function registerCategory(CategoryInterface $category): void
{
$this->registry->unregister('current_category');
$this->registry->register('current_category', $category);
}
}
@@ -0,0 +1,253 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\DesignInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Magento\Catalog\Block\Product\Abstract.
*
* @magentoDataFixture Magento/Catalog/_files/product_with_image.php
* @magentoAppArea frontend
*/
class AbstractTest extends TestCase
{
/**
* Stub class name for class under test
*/
const STUB_CLASS = 'Magento_Catalog_Block_Product_AbstractProduct_Stub';
/**
* @var AbstractProduct
*/
protected $block;
/**
* @var ProductInterface
*/
protected $product;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* Flag is stub class was created
*
* @var bool
*/
protected static $isStubClass = false;
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var SerializerInterface
*/
private $json;
/**
* @inheritdoc
*/
protected function setUp(): void
{
if (!self::$isStubClass) {
$this->getMockForAbstractClass(
AbstractProduct::class,
[],
self::STUB_CLASS,
false
);
self::$isStubClass = true;
}
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->get(DesignInterface::class)->setDefaultDesignTheme();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(self::STUB_CLASS);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->json = $this->objectManager->get(SerializerInterface::class);
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_simple.php
* @magentoAppIsolation enabled
* @return void
*/
public function testGetAddToCartUrlWithProductRequiredOptions(): void
{
$product = $this->productRepository->get('simple');
$url = $this->block->getAddToCartUrl($product);
$this->assertStringEndsWith('?options=cart', $url);
$this->assertStringMatchesFormat('%ssimple-product.html%s', $url);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @return void
*/
public function testGetAddToCartUrlWithSimpleProduct(): void
{
$product = $this->productRepository->get('simple-1');
$url = $this->block->getAddToCartUrl($product);
$this->assertStringEndsWith(sprintf('product/%s/', $product->getId()), $url);
$this->assertStringContainsString('checkout/cart/add', $url);
}
/**
* @return void
*/
public function testGetSubmitUrl(): void
{
$this->product = $this->productRepository->get('simple');
/* by default same as add to cart */
$this->assertStringEndsWith('?options=cart', $this->block->getSubmitUrl($this->product));
$this->block->setData('submit_route_data', ['route' => 'catalog/product/view']);
$this->assertStringEndsWith('catalog/product/view/', $this->block->getSubmitUrl($this->product));
}
/**
* @return void
*/
public function testGetAddToWishlistParams(): void
{
$this->product = $this->productRepository->get('simple');
$json = $this->block->getAddToWishlistParams($this->product);
$params = (array)$this->json->unserialize($json);
$data = (array)$params['data'];
$this->assertEquals($this->product->getId(), $data['product']);
$this->assertArrayHasKey('uenc', $data);
$this->assertStringEndsWith(
'wishlist/index/add/',
$params['action']
);
}
/**
* @return void
*/
public function testGetAddToCompareUrl(): void
{
$this->assertStringMatchesFormat('%scatalog/product_compare/add/', $this->block->getAddToCompareUrl());
}
/**
* @return void
*/
public function testGetMinimalQty(): void
{
$this->product = $this->productRepository->get('simple');
$this->assertGreaterThan(0, $this->block->getMinimalQty($this->product));
}
/**
* @return void
*/
public function testGetReviewsSummaryHtml(): void
{
$this->product = $this->productRepository->get('simple');
$html = $this->block->getReviewsSummaryHtml($this->product, false, true);
$this->assertNotEmpty($html);
$this->assertStringContainsString('review', $html);
}
/**
* @return void
*/
public function testGetProduct(): void
{
$this->product = $this->productRepository->get('simple');
$this->block->setProduct($this->product);
$this->assertSame($this->product, $this->block->getProduct());
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_simple.php
* @magentoAppIsolation enabled
* @return void
*/
public function testGetProductUrl(): void
{
$product = $this->productRepository->get('simple');
$this->assertStringEndsWith('simple-product.html', $this->block->getProductUrl($product));
}
/**
* @return void
*/
public function testHasProductUrl(): void
{
$this->product = $this->productRepository->get('simple');
$this->assertTrue($this->block->hasProductUrl($this->product));
}
/**
* @return void
*/
public function testLayoutDependColumnCount(): void
{
$this->block->setLayout($this->layout);
$this->assertEquals(3, $this->block->getColumnCount());
/* default column count */
$this->block->addColumnCountLayoutDepend('test', 10);
$this->assertEquals(10, $this->block->getColumnCountLayoutDepend('test'));
$this->block->removeColumnCountLayoutDepend('test');
$this->assertFalse($this->block->getColumnCountLayoutDepend('test'));
}
/**
* @return void
*/
public function testGetCanShowProductPrice(): void
{
$this->product = $this->productRepository->get('simple');
$this->assertTrue($this->block->getCanShowProductPrice($this->product));
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @return void
*/
public function testGetProductPriceHtml(): void
{
$product = $this->productRepository->get('simple-1');
$this->assertEmpty($this->block->getProductPriceHtml($product, FinalPrice::PRICE_CODE));
$this->layout->createBlock(
Render::class,
'product.price.render.default',
[
'data' => [
'price_render_handle' => 'catalog_product_prices',
'use_link_for_as_low_as' => true,
],
]
);
$finalPriceHtml = $this->block->getProductPriceHtml($product, FinalPrice::PRICE_CODE);
$this->assertStringContainsString('price-' . FinalPrice::PRICE_CODE, $finalPriceHtml);
$this->assertStringContainsString('product-price-' . $product->getId(), $finalPriceHtml);
}
}
@@ -0,0 +1,310 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Result\PageFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Check that product price render correctly on category page.
*
* @magentoDbIsolation enabled
* @magentoAppArea frontend
*/
class CheckProductPriceTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var Session
*/
private $customerSession;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->customerSession = $this->objectManager->create(Session::class);
parent::setUp();
}
/**
* Assert that product price without additional price configurations will render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_tax_none.php
*
* @return void
*/
public function testCheckProductPriceWithoutAdditionalPriceConfigurations(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 205.00);
}
/**
* Assert that product special price rendered correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_special_price.php
*
* @return void
*/
public function testCheckSpecialPrice(): void
{
$priceHtml = $this->getProductPriceHtml('simple');
$this->assertFinalPrice($priceHtml, 5.99);
$this->assertRegularPrice($priceHtml, 10.00);
}
/**
* Assert that product with fixed tier price is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price.php
*
* @return void
*/
public function testCheckFixedTierPrice(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 205.00);
$this->assertAsLowAsPrice($priceHtml, 40.00);
}
/**
* Assert that price of product with percent tier price rendered correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_percent_tier_price.php
*
* @return void
*/
public function testCheckPercentTierPrice(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 205.00);
$this->assertAsLowAsPrice($priceHtml, 102.50);
}
/**
* Assert that price of product with fixed tier price for not logged user is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price_for_not_logged_user.php
*
* @return void
*/
public function testCheckFixedTierPriceForNotLoggedUser(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 30.00);
$this->assertRegularPrice($priceHtml, 205.00);
}
/**
* Assert that price of product with fixed tier price for logged user is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price_for_logged_user.php
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
* @magentoAppIsolation enabled
*
* @return void
*/
public function testCheckFixedTierPriceForLoggedUser(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 205.00);
$this->assertDoesNotMatchRegularExpression('/\$10/', $priceHtml);
$this->customerSession->setCustomerId(1);
try {
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 10.00);
$this->assertRegularPrice($priceHtml, 205.00);
} finally {
$this->customerSession->setCustomerId(null);
}
}
/**
* Assert that price of product with catalog rule with action equal to "Apply as percentage of original"
* is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_tax_none.php
* @magentoDataFixture Magento/CatalogRule/_files/rule_apply_as_percentage_of_original_not_logged_user.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*
* @return void
*/
public function testCheckPriceRendersCorrectlyWithApplyAsPercentageOfOriginalRule(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 184.50);
$this->assertRegularPrice($priceHtml, 205.00);
}
/**
* Assert that price of product with catalog rule with action equal to "Apply as fixed amount"
* is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_tax_none.php
* @magentoDataFixture Magento/CatalogRule/_files/rule_apply_as_fixed_amount_not_logged_user.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*
* @return void
*/
public function testCheckPriceRendersCorrectlyWithApplyAsFixedAmountRule(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 195.00);
$this->assertRegularPrice($priceHtml, 205.00);
}
/**
* Assert that price of product with catalog rule with action equal to "Adjust final price to this percentage"
* is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_tax_none.php
* @magentoDataFixture Magento/CatalogRule/_files/rule_adjust_final_price_to_this_percentage_not_logged_user.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*
* @return void
*/
public function testCheckPriceRendersCorrectlyWithAdjustFinalPriceToThisPercentageRule(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 20.50);
$this->assertRegularPrice($priceHtml, 205.00);
}
/**
* Assert that price of product with catalog rule with action equal to "Adjust final price to discount value"
* is renders correctly.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_tax_none.php
* @magentoDataFixture Magento/CatalogRule/_files/rule_adjust_final_price_to_discount_value_not_logged_user.php
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*
* @return void
*/
public function testCheckPriceRendersCorrectlyWithAdjustFinalPriceToDiscountValueRule(): void
{
$priceHtml = $this->getProductPriceHtml('simple-product-tax-none');
$this->assertFinalPrice($priceHtml, 10.00);
$this->assertRegularPrice($priceHtml, 205.00);
}
/**
* Assert that price html contain "As low as" label and expected price amount.
*
* @param string $priceHtml
* @param float $expectedPrice
* @return void
*/
private function assertAsLowAsPrice(string $priceHtml, float $expectedPrice): void
{
$this->assertMatchesRegularExpression(
sprintf(
'/<span class="price-label">As low as<\/span> {1,}<span.*data-price-amount="%s".*>\$%01.2f<\/span>/',
round($expectedPrice, 2),
$expectedPrice
),
$priceHtml
);
}
/**
* Assert that price html contain expected final price amount.
*
* @param string $priceHtml
* @param float $expectedPrice
* @return void
*/
private function assertFinalPrice(string $priceHtml, float $expectedPrice): void
{
$this->assertMatchesRegularExpression(
sprintf(
'/data-price-type="finalPrice".*<span class="price">\$%01.2f<\/span><\/span>/',
$expectedPrice
),
$priceHtml
);
}
/**
* Assert that price html contain "Regular price" label and expected price amount.
*
* @param string $priceHtml
* @param float $expectedPrice
* @return void
*/
private function assertRegularPrice(string $priceHtml, float $expectedPrice): void
{
$regex = '<span class="price-label">Regular Price<\/span> {1,}<span.*data-price-amount="%s".*>\$%01.2f<\/span>';
$this->assertMatchesRegularExpression(
sprintf("/{$regex}/", round($expectedPrice, 2), $expectedPrice),
$priceHtml
);
}
/**
* Return html of product price without new line characters.
*
* @param string $sku
* @return string
*/
private function getProductPriceHtml(string $sku): string
{
$product = $this->productRepository->get($sku, false, null, true);
return preg_replace('/[\n\r]/', '', $this->getListProductBlock()->getProductPrice($product));
}
/**
* Get list product block from layout.
*
* @return ListProduct
*/
private function getListProductBlock(): ListProduct
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'catalog_category_view',
]);
$page->getLayout()->generateXml();
/** @var Template $categoryProductsBlock */
$categoryProductsBlock = $page->getLayout()->getBlock('category.products');
return $categoryProductsBlock->getChildBlock('product_list');
}
}
@@ -0,0 +1,310 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks products displaying on category page
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
class ProductInCategoriesViewTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ListProduct */
private $block;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var StoreManagerInterface */
private $storeManager;
/** @var LayoutInterface */
private $layout;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryRepository = $this->objectManager->create(CategoryRepositoryInterface::class);
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(ListProduct::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_with_two_products.php
* @dataProvider productDataProvider
* @param array $data
* @return void
*/
public function testCategoryProductView(array $data): void
{
$this->updateProduct($data['sku'], $data);
$collection = $this->getCategoryProductCollection(333);
$this->assertEquals(1, $collection->getSize());
$this->assertEquals('simple333', $collection->getFirstItem()->getSku());
}
/**
* @return array
*/
public function productDataProvider(): array
{
return [
'simple_product_enabled_disabled' => [
[
'sku' => 'simple2',
'status' => 0,
],
],
'simple_product_in_stock_out_of_stock' => [
[
'sku' => 'simple2',
'stock_data' => [
'use_config_manage_stock' => 1,
'qty' => 0,
'is_qty_decimal' => 0,
'is_in_stock' => 0,
],
],
],
];
}
/**
* @magentoConfigFixture default_store cataloginventory/options/show_out_of_stock 1
* @magentoDataFixture Magento/Catalog/_files/out_of_stock_product_with_category.php
* @return void
*/
public function testCategoryOutOfStockProductView(): void
{
$collection = $this->getCategoryProductCollection(333);
$this->assertEquals(1, $collection->getSize());
$this->assertEquals('out-of-stock-product', $collection->getFirstItem()->getSku());
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_product.php
* @dataProvider productVisibilityProvider
* @param array $data
* @return void
*/
public function testCategoryProductVisibility(array $data): void
{
$this->updateProduct($data['data']['sku'], $data['data']);
$collection = $this->getCategoryProductCollection(333);
$this->assertEquals($data['expected_count'], $collection->getSize());
}
/**
* @return array
*/
public function productVisibilityProvider(): array
{
return [
'not_visible' => [
[
'data' => [
'sku' => 'simple333',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
],
'expected_count' => 0,
],
],
'catalog_search' => [
[
'data' => [
'sku' => 'simple333',
'visibility' => Visibility::VISIBILITY_BOTH,
],
'expected_count' => 1,
],
],
'search' => [
[
'data' => [
'sku' => 'simple333',
'visibility' => Visibility::VISIBILITY_IN_SEARCH,
],
'expected_count' => 0,
],
],
'catalog' => [
[
'data' => [
'sku' => 'simple333',
'visibility' => Visibility::VISIBILITY_IN_CATALOG,
],
'expected_count' => 1,
],
],
];
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testAnchorCategoryProductVisibility(): void
{
$this->updateCategoryIsAnchor(400, true);
$this->assignProductCategories('simple2', [402]);
$parentCategoryCollection = $this->getCategoryProductCollection(400);
$childCategoryCollection = $this->getCategoryProductCollection(402, true);
$this->assertEquals(1, $parentCategoryCollection->getSize());
$this->assertEquals(
$childCategoryCollection->getAllIds(),
$parentCategoryCollection->getAllIds()
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testNonAnchorCategoryProductVisibility(): void
{
$this->updateCategoryIsAnchor(400, false);
$this->assignProductCategories('simple2', [402]);
$parentCategoryCollectionSize = $this->getCategoryProductCollection(400)->getSize();
$childCategoryCollectionSize = $this->getCategoryProductCollection(402, true)->getSize();
$this->assertEquals(0, $parentCategoryCollectionSize);
$this->assertEquals(1, $childCategoryCollectionSize);
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_with_websites_and_stores.php
* @magentoDataFixture Magento/Catalog/_files/category.php
* @return void
*/
public function testCategoryProductViewOnMultiWebsite(): void
{
$this->assignProductCategories(['simple-1', 'simple-2'], [3, 333]);
$store = $this->storeManager->getStore('fixture_second_store');
$currentStore = $this->storeManager->getStore();
try {
$this->storeManager->setCurrentStore($store->getId());
$collection = $this->block->getLoadedProductCollection();
$collectionSize = $collection->getSize();
} finally {
$this->storeManager->setCurrentStore($currentStore);
}
$this->assertEquals(1, $collectionSize);
$this->assertNull($collection->getItemByColumnValue('sku', 'simple-1'));
$this->assertNotNull($collection->getItemByColumnValue('sku', 'simple-2'));
}
/**
* Set categories to the products
*
* @param string|array $sku
* @param $categoryIds
* @return void
*/
private function assignProductCategories($sku, array $categoryIds): void
{
$skus = !is_array($sku) ? [$sku] : $sku;
foreach ($skus as $sku) {
$product = $this->productRepository->get($sku);
$product->setCategoryIds($categoryIds);
$this->productRepository->save($product);
}
}
/**
* Update product
*
* @param string $sku
* @param array $data
* @return void
*/
private function updateProduct(string $sku, array $data): void
{
$product = $this->productRepository->get($sku);
$product->addData($data);
$this->productRepository->save($product);
}
/**
* Returns category collection by category id
*
* @param int $categoryId
* @param bool $refreshBlock
* @return AbstractCollection
*/
private function getCategoryProductCollection(int $categoryId, bool $refreshBlock = false): AbstractCollection
{
$block = $this->getListingBlock($refreshBlock);
$block->getLayer()->setCurrentCategory($categoryId);
return $block->getLoadedProductCollection();
}
/**
* Update is_anchor attribute of the category
*
* @param int $categoryId
* @param bool $isAnchor
* @return void
*/
private function updateCategoryIsAnchor(int $categoryId, bool $isAnchor): void
{
$category = $this->categoryRepository->get($categoryId);
$category->setIsAnchor($isAnchor);
$this->categoryRepository->save($category);
}
/**
* Get product listing block
*
* @param bool $refresh
* @return ListProduct
*/
private function getListingBlock(bool $refresh): ListProduct
{
if ($refresh) {
$this->block = $this->layout->createBlock(ListProduct::class);
}
return $this->block;
}
}
@@ -0,0 +1,466 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Block\Product\ProductList\Toolbar;
use Magento\Catalog\Model\Config;
use Magento\Catalog\Model\ResourceModel\Category\Collection;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for products sorting on category page.
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SortingTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ListProduct
*/
private $block;
/**
* @var CollectionFactory
*/
private $categoryCollectionFactory;
/**
* @var CategoryRepositoryInterface
*/
private $categoryRepository;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var MutableScopeConfigInterface
*/
private $scopeConfig;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->layout->createBlock(Toolbar::class, 'product_list_toolbar');
$this->block = $this->layout->createBlock(ListProduct::class)->setToolbarBlockName('product_list_toolbar');
$this->categoryCollectionFactory = $this->objectManager->get(CollectionFactory::class);
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->scopeConfig = $this->objectManager->get(MutableScopeConfigInterface::class);
parent::setUp();
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @dataProvider productListSortOrderDataProvider
* @param string $sortBy
* @param string $direction
* @param array $expectation
* @param string|null $incompleteReason
* @return void
*/
public function testProductListSortOrder(
string $sortBy,
string $direction,
array $expectation,
string $incompleteReason = null
): void {
if ($incompleteReason) {
$this->markTestSkipped($incompleteReason);
}
$category = $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, $sortBy);
$this->renderBlock($category, $direction);
$this->assertBlockSorting($sortBy, $expectation);
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @dataProvider productListSortOrderDataProvider
* @param string $sortBy
* @param string $direction
* @param array $expectation
* @param string|null $incompleteReason
* @return void
*/
public function testProductListSortOrderWithConfig(
string $sortBy,
string $direction,
array $expectation,
string $incompleteReason = null
): void {
if ($incompleteReason) {
$this->markTestSkipped($incompleteReason);
}
$this->assertProductListSortOrderWithConfig($sortBy, $direction, $expectation);
}
/**
* @return array
*/
public function productListSortOrderDataProvider(): array
{
return [
'default_order_price_asc' => [
'sort' => 'price',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
],
'default_order_price_desc' => [
'sort' => 'price',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
],
'default_order_position_asc' => [
'sort' => 'position',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
],
'default_order_position_desc' => [
'sort' => 'position',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
],
'default_order_name_asc' => [
'sort' => 'name',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
],
'default_order_name_desc' => [
'sort' => 'name',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
],
'default_order_custom_attribute_asc' => [
'sort' => 'test_configurable',
'direction' => 'asc',
'expectation' => ['simple1', 'simple3', 'simple2'],
'incomplete_reason' => 'MC-33825:'
. 'Stabilize skipped test cases for Integration SortingTest with elasticsearch',
],
'default_order_custom_attribute_desc' => [
'sort' => 'test_configurable',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
'incomplete_reason' => 'MC-33825:'
. 'Stabilize skipped test cases for Integration SortingTest with elasticsearch',
],
];
}
/**
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @dataProvider productListSortOrderDataProviderOnStoreView
* @param string $sortBy
* @param string $direction
* @param array $expectation
* @param string $defaultSortBy
* @param string|null $incompleteReason
* @return void
*/
public function testProductListSortOrderOnStoreView(
string $sortBy,
string $direction,
array $expectation,
string $defaultSortBy,
string $incompleteReason = null
): void {
if ($incompleteReason) {
$this->markTestSkipped($incompleteReason);
}
$secondStoreId = (int)$this->storeManager->getStore('fixture_second_store')->getId();
$this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, $defaultSortBy);
$category = $this->updateCategorySortBy('Category 1', $secondStoreId, $sortBy);
$this->renderBlock($category, $direction);
$this->assertBlockSorting($sortBy, $expectation);
}
/**
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @dataProvider productListSortOrderDataProviderOnStoreView
* @param string $sortBy
* @param string $direction
* @param array $expectation
* @param string $defaultSortBy
* @param string|null $incompleteReason,
* @return void
*/
public function testProductListSortOrderWithConfigOnStoreView(
string $sortBy,
string $direction,
array $expectation,
string $defaultSortBy,
string $incompleteReason = null
): void {
if ($incompleteReason) {
$this->markTestSkipped($incompleteReason);
}
$this->objectManager->removeSharedInstance(Config::class);
$secondStoreId = (int)$this->storeManager->getStore('fixture_second_store')->getId();
$this->scopeConfig->setValue(
Config::XML_PATH_LIST_DEFAULT_SORT_BY,
$defaultSortBy,
ScopeInterface::SCOPE_STORE,
Store::DEFAULT_STORE_ID
);
$this->scopeConfig->setValue(
Config::XML_PATH_LIST_DEFAULT_SORT_BY,
$sortBy,
ScopeInterface::SCOPE_STORE,
'fixture_second_store'
);
$this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, null);
$category = $this->updateCategorySortBy('Category 1', $secondStoreId, null);
$this->renderBlock($category, $direction);
$this->assertBlockSorting($sortBy, $expectation);
}
/**
* @return array
*/
public function productListSortOrderDataProviderOnStoreView(): array
{
return [
'default_order_price_asc' => [
'sort' => 'price',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
'default_sort' => 'position'
],
'default_order_price_desc' => [
'sort' => 'price',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
'default_sort' => 'position'
],
'default_order_position_asc' => [
'sort' => 'position',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
'default_sort' => 'price'
],
'default_order_position_desc' => [
'sort' => 'position',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
'default_sort' => 'price'
],
'default_order_name_asc' => [
'sort' => 'name',
'direction' => 'asc',
'expectation' => ['simple1', 'simple2', 'simple3'],
'default_sort' => 'price'
],
'default_order_name_desc' => [
'sort' => 'name',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
'default_sort' => 'price'
],
'default_order_custom_attribute_asc' => [
'sort' => 'test_configurable',
'direction' => 'asc',
'expectation' => ['simple1', 'simple3', 'simple2'],
'default_sort' => 'price',
'incomplete_reason' => 'MC-33825:'
. 'Stabilize skipped test cases for Integration SortingTest with elasticsearch',
],
'default_order_custom_attribute_desc' => [
'sort' => 'test_configurable',
'direction' => 'desc',
'expectation' => ['simple3', 'simple2', 'simple1'],
'default_sort' => 'price',
'incomplete_reason' => 'MC-33825:'
. 'Stabilize skipped test cases for Integration SortingTest with elasticsearch',
],
];
}
/**
* Renders block to apply sorting.
*
* @param CategoryInterface $category
* @param string $direction
* @return void
*/
private function renderBlock(CategoryInterface $category, string $direction): void
{
$this->block->getLayer()->setCurrentCategory($category);
$this->block->setDefaultDirection($direction);
$this->block->toHtml();
}
/**
* Checks product list block correct sorting.
*
* @param string $sortBy
* @param array $expectation
* @return void
*/
private function assertBlockSorting(string $sortBy, array $expectation): void
{
$this->assertArrayHasKey($sortBy, $this->block->getAvailableOrders());
$this->assertEquals($sortBy, $this->block->getSortBy());
$this->assertEquals($expectation, $this->block->getLoadedProductCollection()->getColumnValues('sku'));
}
/**
* Loads category by name.
*
* @param string $categoryName
* @param int $storeId
* @return CategoryInterface
*/
private function loadCategory(string $categoryName, int $storeId): CategoryInterface
{
/** @var Collection $categoryCollection */
$categoryCollection = $this->categoryCollectionFactory->create();
$categoryId = $categoryCollection->setStoreId($storeId)
->addAttributeToFilter(CategoryInterface::KEY_NAME, $categoryName)
->setPageSize(1)
->getFirstItem()
->getId();
return $this->categoryRepository->get($categoryId, $storeId);
}
/**
* Updates category default sort by field.
*
* @param string $categoryName
* @param int $storeId
* @param string|null $sortBy
* @return CategoryInterface
*/
private function updateCategorySortBy(
string $categoryName,
int $storeId,
?string $sortBy
): CategoryInterface {
$oldStoreId = $this->storeManager->getStore()->getId();
$this->storeManager->setCurrentStore($storeId);
$category = $this->loadCategory($categoryName, $storeId);
$category->addData(['default_sort_by' => $sortBy]);
$category = $this->categoryRepository->save($category);
$this->storeManager->setCurrentStore($oldStoreId);
return $category;
}
/**
* Test product list ordered by price with out-of-stock configurable product options with elasticsearch engine
*
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_out-of-stock_child.php
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
* @dataProvider productListWithOutOfStockSortOrderDataProvider
* @param string $sortBy
* @param string $direction
* @param array $expected
* @return void
*/
public function testProductListOutOfStockSortOrderWithElasticsearch(
string $sortBy,
string $direction,
array $expected
): void {
$this->assertProductListSortOrderWithConfig($sortBy, $direction, $expected);
}
/**
* Test product list ordered by price with out-of-stock configurable product options with mysql search engine
*
* @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php
* @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_out-of-stock_child.php
* @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1
* @dataProvider productListWithOutOfStockSortOrderDataProvider
* @param string $sortBy
* @param string $direction
* @param array $expected
* @return void
*/
public function testProductListOutOfStockSortOrderWithMysql(
string $sortBy,
string $direction,
array $expected
): void {
$this->assertProductListSortOrderWithConfig($sortBy, $direction, $expected);
}
/**
* Product list with out-of-stock sort order data provider
*
* @return array
*/
public function productListWithOutOfStockSortOrderDataProvider(): array
{
return [
'default_order_price_asc' => [
'sort' => 'price',
'direction' => Collection::SORT_ORDER_ASC,
'expectation' => ['simple1', 'simple2', 'simple3', 'configurable'],
],
'default_order_price_desc' => [
'sort' => 'price',
'direction' => Collection::SORT_ORDER_DESC,
'expectation' => ['simple3', 'simple2', 'simple1', 'configurable'],
],
];
}
/**
* Assert product list order
*
* @param string $sortBy
* @param string $direction
* @param array $expected
* @return void
*/
private function assertProductListSortOrderWithConfig(string $sortBy, string $direction, array $expected): void
{
$this->objectManager->removeSharedInstance(Config::class);
$this->scopeConfig->setValue(
Config::XML_PATH_LIST_DEFAULT_SORT_BY,
$sortBy,
ScopeInterface::SCOPE_STORE,
Store::DEFAULT_STORE_ID
);
$category = $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, null);
$this->renderBlock($category, $direction);
$this->assertBlockSorting($sortBy, $expected);
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
/**
* Test class for \Magento\Catalog\Block\Product\List.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoAppArea frontend
* @magentoDbIsolation disabled
*/
class ListTest extends TestCase
{
/**
* @var \Magento\Catalog\Block\Product\ListProduct
*/
protected $_block;
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\Collection|MockObject
*/
private $collectionProductMock;
protected function setUp(): void
{
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class)
->setAreaCode('frontend');
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Product\ListProduct::class
);
$this->collectionProductMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
}
public function testGetLayer()
{
$this->assertInstanceOf(\Magento\Catalog\Model\Layer::class, $this->_block->getLayer());
}
public function testGetLoadedProductCollection()
{
$this->_block->setShowRootCategory(true);
$collection = $this->_block->getLoadedProductCollection();
$this->assertInstanceOf(\Magento\Catalog\Model\ResourceModel\Product\Collection::class, $collection);
/* Check that root category was defined for Layer as current */
$this->assertEquals(2, $this->_block->getLayer()->getCurrentCategory()->getId());
$this->collectionProductMock->expects($this->never())->method('load');
}
/**
* @covers \Magento\Catalog\Block\Product\ListProduct::getToolbarBlock
* @covers \Magento\Catalog\Block\Product\ListProduct::getMode
* @covers \Magento\Catalog\Block\Product\ListProduct::getToolbarHtml
* @covers \Magento\Catalog\Block\Product\ListProduct::toHtml
*/
public function testToolbarCoverage()
{
/** @var $parent \Magento\Catalog\Block\Product\ListProduct */
$parent = $this->_getLayout()->createBlock(\Magento\Catalog\Block\Product\ListProduct::class, 'parent');
/* Prepare toolbar block */
$this->_getLayout()
->createBlock(\Magento\Catalog\Block\Product\ProductList\Toolbar::class, 'product_list_toolbar');
$parent->setToolbarBlockName('product_list_toolbar');
$toolbar = $parent->getToolbarBlock();
$this->assertInstanceOf(\Magento\Catalog\Block\Product\ProductList\Toolbar::class, $toolbar, 'Default Toolbar');
$parent->setChild('toolbar', $toolbar);
/* In order to initialize toolbar collection block toHtml should be called before toolbar toHtml */
$this->assertEmpty($parent->toHtml(), 'Block HTML'); /* Template not specified */
$this->assertEquals('grid', $parent->getMode(), 'Default Mode'); /* default mode */
$this->assertNotEmpty($parent->getToolbarHtml(), 'Toolbar HTML'); /* toolbar for one simple product */
}
public function testGetAdditionalHtmlEmpty()
{
$this->_block->setLayout($this->_getLayout());
$this->assertEmpty($this->_block->getAdditionalHtml());
}
public function testGetAdditionalHtml()
{
$layout = $this->_getLayout();
/** @var $parent \Magento\Catalog\Block\Product\ListProduct */
$parent = $layout->createBlock(\Magento\Catalog\Block\Product\ListProduct::class);
$childBlock = $layout->createBlock(
\Magento\Framework\View\Element\Text::class,
'test',
['data' => ['text' => 'test']]
);
$layout->setChild($parent->getNameInLayout(), $childBlock->getNameInLayout(), 'additional');
$this->assertEquals('test', $parent->getAdditionalHtml());
}
public function testSetCollection()
{
$collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Framework\Data\Collection::class);
$this->_block->setCollection($collection);
$this->assertEquals($collection, $this->_block->getLoadedProductCollection());
}
public function testGetPriceBlockTemplate()
{
$this->assertNull($this->_block->getPriceBlockTemplate());
$this->_block->setData('price_block_template', 'test');
$this->assertEquals('test', $this->_block->getPriceBlockTemplate());
}
public function testPrepareSortableFieldsByCategory()
{
/** @var $category \Magento\Catalog\Model\Category */
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Category::class
);
$category->setDefaultSortBy('name');
$this->_block->prepareSortableFieldsByCategory($category);
$this->assertEquals('name', $this->_block->getSortBy());
}
protected function _getLayout()
{
return \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
}
}
@@ -0,0 +1,140 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Product;
/**
* Test class for \Magento\Catalog\Block\Product\New.
*
* @magentoDataFixture Magento/Catalog/_files/products_new.php
* @magentoDbIsolation disabled
*/
class NewTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Block\Product\NewProduct
*/
protected $_block;
protected function setUp(): void
{
/**
* @var \Magento\Customer\Api\GroupManagementInterface $groupManagement
*/
$groupManagement = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Customer\Api\GroupManagementInterface::class);
$notLoggedInId = $groupManagement->getNotLoggedInGroup()->getId();
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea(\Magento\Framework\App\Area::AREA_FRONTEND);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\Http\Context::class
)->setValue(
\Magento\Customer\Model\Context::CONTEXT_GROUP,
$notLoggedInId,
$notLoggedInId
);
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Product\NewProduct::class
);
}
public function testGetCacheKeyInfo()
{
$info = $this->_block->getCacheKeyInfo();
$keys = array_keys($info);
/** order and values of cache key info elements is important */
$this->assertSame(0, array_shift($keys));
$this->assertEquals('CATALOG_PRODUCT_NEW', $info[0]);
$this->assertSame(1, array_shift($keys));
$this->assertEquals(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->getId(),
$info[1]
);
$this->assertSame(2, array_shift($keys));
$themeModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\DesignInterface::class
)->getDesignTheme();
$this->assertEquals($themeModel->getId() ?: null, $info[2]);
$this->assertSame(3, array_shift($keys));
$this->assertEquals(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Session::class
)->getCustomerGroupId(),
$info[3]
);
$this->assertSame('template', array_shift($keys));
/**
* This block is implemented without template by default (invalid).
* Having the cache key fragment with empty value can potentially lead to caching bugs
*/
$this->assertSame(4, array_shift($keys));
$this->assertNotEquals('', $info[4]);
}
public function testSetGetProductsCount()
{
$this->assertEquals(
\Magento\Catalog\Block\Product\NewProduct::DEFAULT_PRODUCTS_COUNT,
$this->_block->getProductsCount()
);
$this->_block->setProductsCount(100);
$this->assertEquals(100, $this->_block->getProductsCount());
}
public function testToHtml()
{
$this->assertEmpty($this->_block->getProductCollection());
$this->_block->setProductsCount(5);
$this->_block->setTemplate('product/widget/new/content/new_list.phtml');
$this->_block->setLayout(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)
);
$html = $this->_block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringContainsString('New Product', $html);
$this->assertInstanceOf(
\Magento\Catalog\Model\ResourceModel\Product\Collection::class,
$this->_block->getProductCollection()
);
}
/**
* @covers \Magento\Catalog\Block\Product\Widget\NewWidget::getCacheKeyInfo
*/
public function testNewWidgetGetCacheKeyInfo()
{
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Product\Widget\NewWidget::class
);
$requestParams = ['test' => 'data'];
$block->getRequest()->setParams($requestParams);
$info = $block->getCacheKeyInfo();
$this->assertEquals('CATALOG_PRODUCT_NEW', $info[0]);
$this->assertEquals(json_encode($requestParams), $info[8]);
}
}
@@ -0,0 +1,329 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ProductList;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\Data\ProductLinkInterface;
use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductLink\Link;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Class AbstractLinks - abstract class when testing blocks of linked products
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractLinksTest extends TestCase
{
/** @var ObjectManager */
protected $objectManager;
/** @var ProductRepositoryInterface */
protected $productRepository;
/** @var LayoutInterface */
protected $layout;
/** @var ProductInterface|Product */
protected $product;
/** @var ProductLinkInterfaceFactory */
protected $productLinkInterfaceFactory;
/** @var StoreManagerInterface */
protected $storeManager;
/** @var array */
protected $existingProducts = [
'wrong-simple' => [
'position' => 1,
],
'simple-249' => [
'position' => 2,
],
'simple-156' => [
'position' => 3,
],
];
/** @var AbstractProduct */
protected $block;
/** @var string */
protected $linkType;
/** @var string */
protected $titleName;
/** @var string */
protected $titleXpath = "//strong[@id = 'block-%s-heading'][contains(text(), '%s')]";
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->productLinkInterfaceFactory = $this->objectManager->get(ProductLinkInterfaceFactory::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* Provide test data to verify the display of linked products.
*
* @return array
*/
public function displayLinkedProductsProvider(): array
{
return [
'product_all_displayed' => [
'data' => [
'updateProducts' => [],
'expectedProductLinks' => [
'wrong-simple',
'simple-249',
'simple-156',
],
],
],
'product_disabled' => [
'data' => [
'updateProducts' => [
'wrong-simple' => ['status' => Status::STATUS_DISABLED],
],
'expectedProductLinks' => [
'simple-249',
'simple-156',
],
],
],
'product_invisibility' => [
'data' => [
'updateProducts' => [
'simple-249' => ['visibility' => Visibility::VISIBILITY_NOT_VISIBLE],
],
'expectedProductLinks' => [
'wrong-simple',
'simple-156',
],
],
],
'product_invisible_in_catalog' => [
'data' => [
'updateProducts' => [
'simple-249' => ['visibility' => Visibility::VISIBILITY_IN_SEARCH],
],
'expectedProductLinks' => [
'wrong-simple',
'simple-156',
],
],
],
'product_out_of_stock' => [
'data' => [
'updateProducts' => [
'simple-156' => [
'stock_data' => [
'use_config_manage_stock' => 1,
'qty' => 0,
'is_qty_decimal' => 0,
'is_in_stock' => 0,
],
],
],
'expectedProductLinks' => [
'wrong-simple',
'simple-249',
],
],
],
];
}
/**
* Provide test data to verify the display of linked products on different websites.
*
* @return array
*/
public function multipleWebsitesLinkedProductsProvider(): array
{
return [
'first_website' => [
'data' => [
'storeCode' => 'default',
'productLinks' => [
'simple-2' => ['position' => 4],
],
'expectedProductLinks' => [
'wrong-simple',
'simple-2',
],
],
],
'second_website' => [
'data' => [
'storeCode' => 'fixture_second_store',
'productLinks' => [
'simple-2' => ['position' => 4],
],
'expectedProductLinks' => [
'simple-249',
'simple-2',
],
],
],
];
}
/**
* Get test data to check position of related, up-sells and cross-sells products
*
* @return array
*/
protected function getPositionData(): array
{
return [
'productLinks' => array_replace_recursive(
$this->existingProducts,
[
'wrong-simple' => ['position' => 2],
'simple-249' => ['position' => 3],
'simple-156' => ['position' => 1],
]
),
'expectedProductLinks' => [
'simple-156',
'wrong-simple',
'simple-249',
],
];
}
/**
* Prepare a block of linked products
*
* @return void
*/
protected function prepareBlock(): void
{
$this->block->setLayout($this->layout);
$this->block->setTemplate('Magento_Catalog::product/list/items.phtml');
$this->block->setType($this->linkType);
}
/**
* Set linked products by link type for current product received from array
*
* @param ProductInterface $product
* @param array $productData
* @return void
*/
private function setCustomProductLinks(ProductInterface $product, array $productData): void
{
$productLinks = [];
foreach ($productData as $sku => $data) {
/** @var ProductLinkInterface|Link $productLink */
$productLink = $this->productLinkInterfaceFactory->create();
$productLink->setSku($product->getSku());
$productLink->setLinkedProductSku($sku);
if (isset($data['position'])) {
$productLink->setPosition($data['position']);
}
$productLink->setLinkType($this->linkType);
$productLinks[] = $productLink;
}
$product->setProductLinks($productLinks);
}
/**
* Update product attributes
*
* @param array $products
* @return void
*/
protected function updateProducts(array $products): void
{
foreach ($products as $sku => $data) {
/** @var ProductInterface|Product $product */
$product = $this->productRepository->get($sku);
$product->addData($data);
$this->productRepository->save($product);
}
}
/**
* Get an array of received linked products
*
* @param array $items
* @return array
*/
protected function getActualLinks(array $items): array
{
$actualLinks = [];
/** @var ProductInterface $productItem */
foreach ($items as $productItem) {
$actualLinks[] = $productItem->getSku();
}
return $actualLinks;
}
/**
* Link products to an existing product
*
* @param string $sku
* @param array $productLinks
* @return void
*/
protected function linkProducts(string $sku, array $productLinks): void
{
$product = $this->productRepository->get($sku);
$this->setCustomProductLinks($product, $productLinks);
$this->productRepository->save($product);
}
/**
* Prepare the necessary websites for all products
*
* @return array
*/
protected function prepareProductsWebsiteIds(): array
{
$websiteId = $this->storeManager->getWebsite('test')->getId();
$defaultWebsiteId = $this->storeManager->getWebsite('base')->getId();
return [
'simple-1' => [
'website_ids' => [$defaultWebsiteId, $websiteId],
],
'simple-2' => [
'website_ids' => [$defaultWebsiteId, $websiteId],
],
'wrong-simple' => [
'website_ids' => [$defaultWebsiteId],
],
'simple-249' => [
'website_ids' => [$websiteId],
],
'simple-156' => [
'website_ids' => [],
],
];
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Product\ProductList;
/**
* Test class for \Magento\Catalog\Block\Product\List\Crosssell.
*
* @magentoDataFixture Magento/Catalog/_files/products_crosssell.php
*/
class CrosssellTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea(\Magento\Framework\App\Area::AREA_FRONTEND);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$firstProduct = $productRepository->get('simple');
$product = $productRepository->get('simple_with_cross');
$objectManager->get(\Magento\Framework\Registry::class)->register('product', $product);
/** @var $block \Magento\Catalog\Block\Product\ProductList\Crosssell */
$block = $objectManager->get(\Magento\Framework\View\LayoutInterface::class)
->createBlock(\Magento\Catalog\Block\Product\ProductList\Crosssell::class);
$block->setLayout($objectManager->get(\Magento\Framework\View\LayoutInterface::class));
$block->setViewModel($objectManager->get(\Magento\Catalog\ViewModel\Product\Listing\PreparePostData::class));
$block->setTemplate('Magento_Catalog::product/list/items.phtml');
$block->setType('crosssell');
$block->setItemCount(1);
$html = $block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringContainsString('Simple Cross Sell', $html);
/* name */
$this->assertStringContainsString('product/' . $firstProduct->getId() . '/', $html);
/* part of url */
$this->assertInstanceOf(
\Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class,
$block->getItems()
);
}
}
@@ -0,0 +1,152 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ProductList;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection as LinkProductCollection;
/**
* Check the correct behavior of related products on the product view page
*
* @see \Magento\Catalog\Block\Product\ProductList\Related
* @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';
}
/**
* Checks for a related product when block code is generated
*
* @magentoDataFixture Magento/Catalog/_files/products_related.php
* @return void
*/
public function testAll(): void
{
/** @var ProductInterface $relatedProduct */
$relatedProduct = $this->productRepository->get('simple');
$this->product = $this->productRepository->get('simple_with_cross');
$this->block->setProduct($this->product);
$this->prepareBlock();
$html = $this->block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringContainsString($relatedProduct->getName(), $html);
/* name */
$this->assertStringContainsString('id="related-checkbox' . $relatedProduct->getId() . '"', $html);
/* part of url */
$this->assertInstanceOf(
LinkProductCollection::class,
$this->block->getItems()
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_related.php
* @return void
*/
public function testGetIdentities(): void
{
/** @var ProductInterface $relatedProduct */
$relatedProduct = $this->productRepository->get('simple');
$this->product = $this->productRepository->get('simple_with_cross');
$this->block->setProduct($this->product);
$this->prepareBlock();
$expectedTags = ['cat_p_' . $relatedProduct->getId(), 'cat_p'];
$tags = $this->block->getIdentities();
$this->assertEquals($expectedTags, $tags);
}
/**
* Test the display of related products in the block
*
* @dataProvider displayLinkedProductsProvider
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @param array $data
* @return void
*/
public function testDisplayRelatedProducts(array $data): void
{
$this->updateProducts($data['updateProducts']);
$this->linkProducts('simple', $this->existingProducts);
$this->product = $this->productRepository->get('simple');
$this->block->setProduct($this->product);
$items = $this->block->getItems()->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected related products do not match actual related products!'
);
}
/**
* Test the position of related products in the block
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @return void
*/
public function testPositionRelatedProducts(): void
{
$data = $this->getPositionData();
$this->linkProducts('simple', $data['productLinks']);
$this->product = $this->productRepository->get('simple');
$this->block->setProduct($this->product);
$items = $this->block->getItems()->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected related products do not match actual related products!'
);
}
/**
* Test the display of related products in the block on different websites
*
* @dataProvider multipleWebsitesLinkedProductsProvider
* @magentoDataFixture Magento/Catalog/_files/products_with_websites_and_stores.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @magentoAppIsolation enabled
* @param array $data
* @return void
*/
public function testMultipleWebsitesRelatedProducts(array $data): void
{
$this->updateProducts($this->prepareProductsWebsiteIds());
$productLinks = array_replace_recursive($this->existingProducts, $data['productLinks']);
$this->linkProducts('simple-1', $productLinks);
$this->product = $this->productRepository->get(
'simple-1',
false,
$this->storeManager->getStore($data['storeCode'])->getId()
);
$this->block->setProduct($this->product);
$items = $this->block->getItems()->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected related products do not match actual related products!'
);
}
}
@@ -0,0 +1,180 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ProductList;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\TestFramework\Helper\Xpath;
/**
* Checks product list toolbar.
*
* @see \Magento\Catalog\Block\Product\ProductList\Toolbar
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class ToolbarTest extends TestCase
{
/** @var string */
private const XPATH_TEMPLATE_FOR_NOT_VISIBLE_ICON_CASES = '//div[contains(@class, "modes")]/*[@data-value="%s"]';
/** @var string */
private const ACTIVE_MODE_XPATH_TEMPLATE =
'//div[contains(@class, "modes")]/strong[@data-value="%s" and contains(@class, "active")]';
/** @var string */
private const NOT_ACTIVE_MODE_XPATH_TEMPLATE = '//div[contains(@class, "modes")]/a[@data-value="%s"]';
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var Toolbar */
private $toolbarBlock;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->toolbarBlock = $this->layout->createBlock(Toolbar::class);
}
/**
* @return void
*/
public function testGetPagerHtml(): void
{
$this->toolbarBlock->setNameInLayout('block');
/** @var $childBlock Text */
$childBlock = $this->layout->addBlock(
Text::class,
'product_list_toolbar_pager',
'block'
);
$expectedHtml = '<b>Any text there</b>';
$this->assertNotEquals($expectedHtml, $this->toolbarBlock->getPagerHtml());
$childBlock->setText($expectedHtml);
$this->assertEquals($expectedHtml, $this->toolbarBlock->getPagerHtml());
}
/**
* @magentoConfigFixture current_store catalog/frontend/list_mode grid
* @return void
*/
public function testToHtmlGridOnly(): void
{
$htmlOutput = $this->getModeSwitcherHtml();
$this->assertNotEmpty($htmlOutput);
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
sprintf(self::XPATH_TEMPLATE_FOR_NOT_VISIBLE_ICON_CASES, 'grid'),
$htmlOutput
)
);
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
sprintf(self::XPATH_TEMPLATE_FOR_NOT_VISIBLE_ICON_CASES, 'list'),
$htmlOutput
)
);
}
/**
* @magentoConfigFixture current_store catalog/frontend/list_mode list
* @return void
*/
public function testToHtmlListOnly(): void
{
$htmlOutput = $this->getModeSwitcherHtml();
$this->assertNotEmpty($htmlOutput);
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
sprintf(self::XPATH_TEMPLATE_FOR_NOT_VISIBLE_ICON_CASES, 'grid'),
$htmlOutput
)
);
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
sprintf(self::XPATH_TEMPLATE_FOR_NOT_VISIBLE_ICON_CASES, 'list'),
$htmlOutput
)
);
}
/**
* @magentoConfigFixture current_store catalog/frontend/list_mode grid-list
* @return void
*/
public function testToHtmlGridList(): void
{
$htmlOutput = $this->getModeSwitcherHtml();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(self::ACTIVE_MODE_XPATH_TEMPLATE, 'grid'),
$htmlOutput
)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(self::NOT_ACTIVE_MODE_XPATH_TEMPLATE, 'list'),
$htmlOutput
)
);
}
/**
* @magentoConfigFixture current_store catalog/frontend/list_mode list-grid
* @return void
*/
public function testToHtmlListGrid(): void
{
$htmlOutput = $this->getModeSwitcherHtml();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(self::ACTIVE_MODE_XPATH_TEMPLATE, 'list'),
$htmlOutput
)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(self::NOT_ACTIVE_MODE_XPATH_TEMPLATE, 'grid'),
$htmlOutput
)
);
}
/**
* Mode switcher html
*
* @return string
*/
private function getModeSwitcherHtml(): string
{
$this->toolbarBlock->setTemplate('Magento_Catalog::product/list/toolbar/viewmode.phtml');
return $this->toolbarBlock->toHtml();
}
}
@@ -0,0 +1,140 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\ProductList;
/**
* Check the correct behavior of up-sell products on the product view page
*
* @see \Magento\Catalog\Block\Product\ProductList\Upsell
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*/
class UpsellTest extends AbstractLinksTest
{
/** @var Upsell */
protected $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->layout->createBlock(Upsell::class);
$this->linkType = 'upsell';
}
/**
* Checks for a up-sell product when block code is generated
*
* @magentoDataFixture Magento/Catalog/_files/products_upsell.php
* @return void
*/
public function testAll(): void
{
$this->product = $this->productRepository->get('simple_with_upsell');
$this->block->setProduct($this->product);
$this->prepareBlock();
$html = $this->block->toHtml();
$this->assertNotEmpty($html);
$this->assertStringContainsString('Simple Up Sell', $html);
$this->assertCount(1, $this->block->getItems());
}
/**
* @magentoDataFixture Magento/Catalog/_files/products_upsell.php
* @return void
*/
public function testGetIdentities(): void
{
$upsellProduct = $this->productRepository->get('simple');
$this->product = $this->productRepository->get('simple_with_upsell');
$this->block->setProduct($this->product);
$this->prepareBlock();
$expectedTags = ['cat_p_' . $upsellProduct->getId(), 'cat_p'];
$tags = $this->block->getIdentities();
$this->assertEquals($expectedTags, $tags);
}
/**
* Test the display of up-sell products in the block
*
* @dataProvider displayLinkedProductsProvider
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @param array $data
* @return void
*/
public function testDisplayUpsellProducts(array $data): void
{
$this->updateProducts($data['updateProducts']);
$this->linkProducts('simple', $this->existingProducts);
$this->product = $this->productRepository->get('simple');
$this->block->setProduct($this->product);
$items = $this->block->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected up-sell products do not match actual up-sell products!'
);
}
/**
* Test the position of up-sell products in the block
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @return void
*/
public function testPositionUpsellProducts(): void
{
$data = $this->getPositionData();
$this->linkProducts('simple', $data['productLinks']);
$this->product = $this->productRepository->get('simple');
$this->block->setProduct($this->product);
$items = $this->block->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected up-sell products do not match actual up-sell products!'
);
}
/**
* Test the display of up-sell products in the block on different websites
*
* @dataProvider multipleWebsitesLinkedProductsProvider
* @magentoDataFixture Magento/Catalog/_files/products_with_websites_and_stores.php
* @magentoDataFixture Magento/Catalog/_files/products_list.php
* @magentoAppIsolation enabled
* @param array $data
* @return void
*/
public function testMultipleWebsitesUpsellProducts(array $data): void
{
$this->updateProducts($this->prepareProductsWebsiteIds());
$productLinks = array_replace_recursive($this->existingProducts, $data['productLinks']);
$this->linkProducts('simple-1', $productLinks);
$this->product = $this->productRepository->get(
'simple-1',
false,
$this->storeManager->getStore($data['storeCode'])->getId()
);
$this->block->setProduct($this->product);
$items = $this->block->getItems();
$this->assertEquals(
$data['expectedProductLinks'],
$this->getActualLinks($items),
'Expected up-sell products do not match actual up-sell products!'
);
}
}
@@ -0,0 +1,111 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class consist of general logic for currency tests
*/
abstract class AbstractCurrencyTest extends TestCase
{
protected const TIER_PRICE_BLOCK_NAME = 'product.price.tier';
protected const FINAL_PRICE_BLOCK_NAME = 'product.price.final';
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var Registry */
protected $registry;
/** @var PageFactory */
private $pageFactory;
/** @var ProductRepositoryInterface */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->pageFactory = $this->objectManager->get(PageFactory::class);
}
/**
* @inheridoc
*/
protected function tearDown(): void
{
$this->registry->unregister('product');
parent::tearDown();
}
/**
* Process price view on product page
*
* @param string|ProductInterface $product
* @param string $blockName
* @return string
*/
protected function processPriceView($product, string $blockName = self::FINAL_PRICE_BLOCK_NAME): string
{
$product = is_string($product) ? $this->productRepository->get($product) : $product;
$this->registerProduct($product);
return trim(
preg_replace('/(?:\s|&nbsp;)+/', ' ', strip_tags($this->getProductPriceBlockHtml($blockName)))
);
}
/**
* Get product price block content
*
* @param string $blockName
* @return string
*/
private function getProductPriceBlockHtml(string $blockName): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'catalog_product_view',
'catalog_product_view_type_configurable',
]);
$page->getLayout()->generateXml();
$block = $page->getLayout()->getBlock($blockName);
$this->assertNotFalse($block);
return $block->toHtml();
}
/**
* 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,36 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Product\View;
class AdditionalTest extends \PHPUnit\Framework\TestCase
{
public function testGetChildHtmlList()
{
/** @var $layout \Magento\Framework\View\Layout */
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
/** @var $block \Magento\Catalog\Block\Product\View\Additional */
$block = $layout->createBlock(\Magento\Catalog\Block\Product\View\Additional::class, 'block');
/** @var $childFirst \Magento\Framework\View\Element\Text */
$childFirst = $layout->addBlock(\Magento\Framework\View\Element\Text::class, 'child1', 'block');
$htmlFirst = '<b>Any html of child1</b>';
$childFirst->setText($htmlFirst);
/** @var $childSecond \Magento\Framework\View\Element\Text */
$childSecond = $layout->addBlock(\Magento\Framework\View\Element\Text::class, 'child2', 'block');
$htmlSecond = '<b>Any html of child2</b>';
$childSecond->setText($htmlSecond);
$list = $block->getChildHtmlList();
$this->assertIsArray($list);
$this->assertCount(2, $list);
$this->assertContains($htmlFirst, $list);
$this->assertContains($htmlSecond, $list);
}
}
@@ -0,0 +1,270 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\View\Attributes;
use Magento\Catalog\Helper\Output;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class consist of base logic for custom attributes view tests
*/
abstract class AbstractAttributeTest extends TestCase
{
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var ProductAttributeRepositoryInterface */
private $attributeRepository;
/** @var Registry */
private $registry;
/** @var Attributes */
private $block;
/** @var ProductAttributeInterface */
private $attribute;
/** @var Output */
private $outputHelper;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->attributeRepository = $this->objectManager->create(ProductAttributeRepositoryInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->block = $this->layout->createBlock(Attributes::class);
$this->outputHelper = $this->objectManager->create(Output::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* Process custom attribute view
*
* @param string $sku
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
protected function processAttributeView(
string $sku,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->updateAttribute(['is_visible_on_front' => true]);
$product = $this->updateProduct($sku, $attributeValue);
$this->registerProduct($product);
$data = $this->block->getAdditionalData();
$this->assertEquals($this->prepareExpectedData($expectedAttributeValue), $data);
}
/**
* Process custom attribute with default value view when new value set
*
* @param string $sku
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
protected function processNonDefaultAttributeValueView(
string $sku,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->updateAttribute(['is_visible_on_front' => true, 'default_value' => $this->getDefaultAttributeValue()]);
$product = $this->updateProduct($sku, $attributeValue);
$this->registerProduct($product);
$data = $this->block->getAdditionalData();
$this->assertEquals($this->prepareExpectedData($expectedAttributeValue), $data);
}
/**
* Procces custom attribute view with default value
*
* @param string $sku
* @param string $expectedAttributeValue
* @return void
*/
protected function processDefaultValueAttributeView(string $sku, string $expectedAttributeValue): void
{
$this->updateAttribute(['is_visible_on_front' => true, 'default_value' => $this->getDefaultAttributeValue()]);
$product = $this->productRepository->save($this->productRepository->get($sku));
$this->registerProduct($product);
$data = $this->block->getAdditionalData();
$this->assertEquals($this->prepareExpectedData($expectedAttributeValue), $data);
}
/**
* Procces attribute value view with html tags
*
* @param string $sku
* @param bool $allowHtmlTags
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
protected function processAttributeHtmlOutput(
string $sku,
bool $allowHtmlTags,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->updateAttribute(['is_visible_on_front' => true, 'is_html_allowed_on_front' => $allowHtmlTags]);
$product = $this->updateProduct($sku, $attributeValue);
$this->registerProduct($product);
$data = $this->block->getAdditionalData();
$dataItem = $data[$this->getAttributeCode()] ?? null;
$this->assertNotNull($dataItem);
$output = $this->outputHelper->productAttribute($product, $dataItem['value'], $dataItem['code']);
$this->assertEquals($expectedAttributeValue, $output);
}
/**
* Process attribute view per store views
*
* @param string $sku
* @param int $attributeScopeValue
* @param string $attributeValue
* @param string $expectedAttributeValue
* @param string $storeCode
* @return void
*/
protected function processMultiStoreView(
string $sku,
int $attributeScopeValue,
string $attributeValue,
string $storeCode
): void {
$currentStore = $this->storeManager->getStore();
$this->updateAttribute(['is_global' => $attributeScopeValue, 'is_visible_on_front' => true]);
$this->storeManager->setCurrentStore($storeCode);
try {
$product = $this->updateProduct($sku, $attributeValue);
$this->registerProduct($product);
$this->assertEquals($this->prepareExpectedData($attributeValue), $this->block->getAdditionalData());
} finally {
$this->storeManager->setCurrentStore($currentStore);
}
}
/**
* Get attribute
*
* @return ProductAttributeInterface
*/
protected function getAttribute(): ProductAttributeInterface
{
if ($this->attribute === null) {
$this->attribute = $this->attributeRepository->get($this->getAttributeCode());
}
return $this->attribute;
}
/**
* Prepare expected data
*
* @param string $expectedValue
* @return array
*/
private function prepareExpectedData(string $expectedValue): array
{
return [
$this->getAttributeCode() => [
'label' => $this->getAttribute()->getStoreLabel(),
'value' => $expectedValue,
'code' => $this->getAttributeCode(),
],
];
}
/**
* Update product
*
* @param string $productSku
* @param string $attributeValue
* @return ProductInterface
*/
private function updateProduct(string $productSku, string $attributeValue): ProductInterface
{
$value = $this->getAttribute()->usesSource()
? $this->attribute->getSource()->getOptionId($attributeValue)
: $attributeValue;
$product = $this->productRepository->get($productSku);
$product->addData([$this->getAttributeCode() => $value]);
return $this->productRepository->save($product);
}
/**
* Register product
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('product');
$this->registry->register('product', $product);
}
/**
* Update attribute
*
* @param array $data
* @return void
*/
private function updateAttribute(array $data): void
{
$attribute = $this->getAttribute();
$attribute->addData($data);
$this->attributeRepository->save($attribute);
}
/**
* Get attribute code for current test
*
* @return string
*/
abstract protected function getAttributeCode(): string;
/**
* Get default value for current attribute
*
* @return string
*/
abstract protected function getDefaultAttributeValue(): string;
}
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
/**
* Class checks date attribute displaying on frontend
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Catalog/_files/product_date_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class DateAttributeTest extends AbstractAttributeTest
{
/**
* @magentoConfigFixture default_store general/locale/timezone UTC
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = $this->getAttribute()->getBackend()->formatDate('12/20/19');
$this->processAttributeView('simple2', $attributeValue, 'Dec 20, 2019');
}
/**
* @magentoConfigFixture default_store general/locale/timezone UTC
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = $this->getAttribute()->getBackend()->formatDate('12/20/19');
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, 'Dec 20, 2019');
}
/**
* @magentoConfigFixture default_store general/locale/timezone UTC
* @return void
*/
public function testAttributeWithDefaultValueView(): void
{
$this->markTestSkipped('Test is blocked by issue MC-28950');
$this->processDefaultValueAttributeView('simple2', $this->getDefaultAttributeValue());
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'date_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getBackend()->formatDate('11/20/19');
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
/**
* Class checks dropdown attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class DropdownAttributeTest extends AbstractAttributeTest
{
/** @var string */
private $attributeCode;
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processAttributeView('simple2', $attributeValue, 'Option 2');
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, 'Option 2');
}
/**
* @dataProvider attributeWithTagsProvider
* @magentoAppArea frontend
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute_with_html.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @param bool $allowHtmlTags
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
public function testAttributeWithHtmlTags(
bool $allowHtmlTags,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->attributeCode = 'dropdown_attribute_with_html';
$attributeValue = $this->getAttribute()->getSource()->getOptionId($attributeValue);
$this->processAttributeHtmlOutput('simple2', $allowHtmlTags, $attributeValue, $expectedAttributeValue);
}
/**
* @return array
*/
public function attributeWithTagsProvider(): array
{
return [
'allow_html_tags' => [
'allow_html_tags' => true,
'attribute_value' => '<h2>Option 2</h2>',
'expected_attribute_value' => '<h2>Option 2</h2>',
],
'disallow_html_tags' => [
'allow_html_tags' => false,
'attribute_value' => '<h2>Option 2</h2>',
'expected_attribute_value' => '&lt;h2&gt;Option 2&lt;/h2&gt;',
],
];
}
/**
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @return void
*/
public function testAttributePerStoreView(): void
{
$this->processMultiStoreView(
'simple2',
ScopedAttributeInterface::SCOPE_STORE,
'Option 3',
'fixturestore'
);
}
/**
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_two_websites.php
*
* @return void
*/
public function testAttributePerWebsites(): void
{
$this->processMultiStoreView(
'simple-on-two-websites',
ScopedAttributeInterface::SCOPE_WEBSITE,
'Option 3',
'fixture_second_store'
);
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return $this->attributeCode ?? 'dropdown_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('Option 1');
}
}
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
/**
* Class checks multi select attribute displaying on frontend
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Catalog/_files/multiselect_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class MultiSelectAttributeTest extends AbstractAttributeTest
{
/** @var string */
private $attributeCode;
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processAttributeView('simple2', $attributeValue, 'Option 2');
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, 'Option 2');
}
/**
* @return void
*/
public function testAttributeWithDefaultValueView(): void
{
$this->markTestSkipped('Test is blocked by issue MC-29019');
$this->processDefaultValueAttributeView('simple2', 'Option 1');
}
/**
* @dataProvider attributeWithTagsProvider
* @magentoAppArea frontend
* @magentoDataFixture Magento/Catalog/_files/multiselect_attribute_with_html.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @param bool $allowHtmlTags
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
public function testAttributeWithHtmlTags(
bool $allowHtmlTags,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->attributeCode = 'multiselect_attribute_with_html';
$attributeValue = $this->getAttribute()->getSource()->getOptionId($attributeValue);
$this->processAttributeHtmlOutput('simple2', $allowHtmlTags, $attributeValue, $expectedAttributeValue);
}
/**
* @return array
*/
public function attributeWithTagsProvider(): array
{
return [
'allow_html_tags' => [
'allow_html_tags' => true,
'attribute_value' => '<h2>Option 2</h2>',
'expected_attribute_value' => '<h2>Option 2</h2>',
],
'disallow_html_tags' => [
'allow_html_tags' => false,
'attribute_value' => '<h2>Option 2</h2>',
'expected_attribute_value' => '&lt;h2&gt;Option 2&lt;/h2&gt;',
],
];
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return $this->attributeCode ?? 'multiselect_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('Option 1');
}
}
@@ -0,0 +1,74 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
use Magento\Directory\Model\PriceCurrency;
/**
* Class checks price attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_decimal_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class PriceAttributeTest extends AbstractAttributeTest
{
/** @var PriceCurrency */
private $priceCurrency;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->priceCurrency = $this->objectManager->create(PriceCurrency::class);
}
/**
* @dataProvider pricesDataProvider
* @param string $price
* @return void
*/
public function testAttributeView(string $price): void
{
$this->processAttributeView('simple2', $price, $this->priceCurrency->convertAndFormat($price));
}
/**
* @return array
*/
public function pricesDataProvider(): array
{
return [
'zero_price' => [
'price' => '0',
],
'positive_price' => [
'price' => '150',
],
];
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'decimal_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return '';
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
/**
* Class checks textarea attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_text_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class TextAreaAttributeTest extends AbstractAttributeTest
{
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = 'Value for text area attribute';
$this->processAttributeView('simple2', $attributeValue, $attributeValue);
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = 'Text area attribute value';
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, $attributeValue);
}
/**
* @return void
*/
public function testAttributeWithDefaultValueView(): void
{
$this->processDefaultValueAttributeView('simple2', $this->getDefaultAttributeValue());
}
/**
* @inheritdic
*/
protected function getAttributeCode(): string
{
return 'text_attribute';
}
/**
* @inheritdic
*/
protected function getDefaultAttributeValue(): string
{
return 'Default value for text area attribute';
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
/**
* Class checks text attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_varchar_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class TextAttributeTest extends AbstractAttributeTest
{
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = 'Text attribute value';
$this->processAttributeView('simple2', $attributeValue, $attributeValue);
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = 'Non default text attribute value';
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, $attributeValue);
}
/**
* @return void
*/
public function testAttributeWithDefaultValueView(): void
{
$this->processDefaultValueAttributeView('simple2', $this->getDefaultAttributeValue());
}
/**
* @dataProvider attributeWithTagsProvider
* @magentoAppArea frontend
* @param bool $allowHtmlTags
* @param string $attributeValue
* @param string $expectedAttributeValue
* @return void
*/
public function testAttributeWithHtmlTags(
bool $allowHtmlTags,
string $attributeValue,
string $expectedAttributeValue
): void {
$this->processAttributeHtmlOutput('simple2', $allowHtmlTags, $attributeValue, $expectedAttributeValue);
}
/**
* @return array
*/
public function attributeWithTagsProvider(): array
{
return [
'allow_html_tags' => [
'allow_html_tags' => true,
'attribute_value' => '<h2>Text with <p>html inside</p></h2>',
'expected_attribute_value' => '<h2>Text with <p>html inside</p></h2>',
],
'disallow_html_tags' => [
'allow_html_tags' => false,
'attribute_value' => '<h2>Text with <p>html inside</p></h2>',
'expected_attribute_value' => '&lt;h2&gt;Text with &lt;p&gt;html inside&lt;/p&gt;&lt;/h2&gt;',
],
];
}
/**
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/Catalog/_files/product_varchar_attribute.php
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @return void
*/
public function testAttributePerStoreView(): void
{
$this->processMultiStoreView(
'simple2',
ScopedAttributeInterface::SCOPE_STORE,
'second store view value',
'fixturestore'
);
}
/**
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/Catalog/_files/product_two_websites.php
* @magentoDataFixture Magento/Catalog/_files/product_varchar_attribute.php
*
* @return void
*/
public function testAttributePerWebsites(): void
{
$this->processMultiStoreView(
'simple-on-two-websites',
ScopedAttributeInterface::SCOPE_WEBSITE,
'second website value',
'fixture_second_store'
);
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'varchar_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return 'Default value for text attribute';
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Attribute;
/**
* Class checks boolean attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_boolean_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class YesNoAttributeTest extends AbstractAttributeTest
{
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$this->processNonDefaultAttributeValueView('simple2', '0', 'No');
}
/**
* @return void
*/
public function testAttributeWithDefaultValueView(): void
{
$this->processDefaultValueAttributeView('simple2', 'Yes');
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'boolean_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return '1';
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea frontend
*/
class DescriptionTest extends TestCase
{
/**
* @var Description
*/
private $block;
/**
* @var Registry
*/
private $registry;
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->block = $objectManager->create(Description::class, [
'data' => [
'template' => 'Magento_Catalog::product/view/attribute.phtml'
]
]);
$this->registry = $objectManager->get(Registry::class);
$this->registry->unregister('product');
}
public function testGetProductWhenNoProductIsRegistered()
{
$html = $this->block->toHtml();
$this->assertEmpty($html);
}
public function testGetProductWhenInvalidProductIsRegistered()
{
$this->registry->register('product', new \stdClass());
$html = $this->block->toHtml();
$this->assertEmpty($html);
}
}
@@ -0,0 +1,561 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Gallery\UpdateHandler;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/**
* Provide tests for displaying images on product page.
*
* @magentoAppArea frontend
*/
class GalleryTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var StoreRepositoryInterface
*/
private $storeRepository;
/**
* @var Json
*/
private $serializer;
/**
* @var Gallery
*/
private $block;
/**
* @var array
*/
private $imageExpectation = [
'thumb' => '/m/a/magento_image.jpg',
'img' => '/m/a/magento_image.jpg',
'full' => '/m/a/magento_image.jpg',
'caption' => 'Image Alt Text',
'position' => '1',
'isMain' => false,
'type' => 'image',
'videoUrl' => null,
];
/**
* @var array
*/
private $thumbnailExpectation = [
'thumb' => '/m/a/magento_thumbnail.jpg',
'img' => '/m/a/magento_thumbnail.jpg',
'full' => '/m/a/magento_thumbnail.jpg',
'caption' => 'Thumbnail Image',
'position' => '2',
'isMain' => false,
'type' => 'image',
'videoUrl' => null,
];
/**
* @var array
*/
private $placeholderExpectation = [
'thumb' => '/placeholder/thumbnail.jpg',
'img' => '/placeholder/image.jpg',
'full' => '/placeholder/image.jpg',
'caption' => '',
'position' => '0',
'isMain' => true,
'type' => 'image',
'videoUrl' => null,
];
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->storeRepository = $this->objectManager->create(StoreRepositoryInterface::class);
$this->serializer = $this->objectManager->get(Json::class);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Gallery::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation enabled
* @return void
*/
public function testGetGalleryImagesJsonWithoutImages(): void
{
$this->block->setData('product', $this->getProduct());
$result = $this->serializer->unserialize($this->block->getGalleryImagesJson());
$this->assertImages(reset($result), $this->placeholderExpectation);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoConfigFixture default/web/url/catalog_media_url_format image_optimization_parameters
* @magentoDbIsolation enabled
* @return void
*/
public function testGetGalleryImagesJsonWithoutImagesWithImageOptimizationParametersInUrl(): void
{
$this->block->setData('product', $this->getProduct());
$result = $this->serializer->unserialize($this->block->getGalleryImagesJson());
$this->assertImages(reset($result), $this->placeholderExpectation);
}
/**
* @dataProvider galleryDisabledImagesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php
* @magentoConfigFixture default/web/url/catalog_media_url_format hash
* @magentoDbIsolation enabled
* @param array $images
* @param array $expectation
* @return void
*/
public function testGetGalleryImagesJsonWithDisabledImage(array $images, array $expectation): void
{
$product = $this->getProduct();
$this->setGalleryImages($product, $images);
$this->block->setData('product', $this->getProduct());
$firstImage = $this->serializer->unserialize($this->block->getGalleryImagesJson());
$this->assertImages(reset($firstImage), $expectation);
}
/**
* @dataProvider galleryDisabledImagesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoConfigFixture default/web/url/catalog_media_url_format hash
* @magentoDbIsolation disabled
* @param array $images
* @param array $expectation
* @return void
*/
public function testGetGalleryImagesJsonOnStoreWithDisabledImage(array $images, array $expectation): void
{
$secondStoreId = (int)$this->storeRepository->get('fixture_second_store')->getId();
$product = $this->getProduct($secondStoreId);
$this->setGalleryImages($product, $images);
$this->block->setData('product', $this->getProduct($secondStoreId));
$firstImage = $this->serializer->unserialize($this->block->getGalleryImagesJson());
$this->assertImages(reset($firstImage), $expectation);
}
/**
* @return array
*/
public function galleryDisabledImagesDataProvider(): array
{
return [
[
'images' => [
'/m/a/magento_image.jpg' => ['disabled' => true],
'/m/a/magento_thumbnail.jpg' => [],
],
'expectation' => $this->thumbnailExpectation,
],
];
}
/**
* Test default image generation format.
*
* @dataProvider galleryImagesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php
* @magentoDbIsolation enabled
* @param array $images
* @param array $expectation
* @return void
*/
public function testGetGalleryImagesJson(array $images, array $expectation): void
{
$product = $this->getProduct();
$this->setGalleryImages($product, $images);
$this->block->setData('product', $this->getProduct());
[$firstImage, $secondImage] = $this->serializer->unserialize($this->block->getGalleryImagesJson());
[$firstExpectedImage, $secondExpectedImage] = $expectation;
$this->assertImages($firstImage, $firstExpectedImage);
$this->assertImages($secondImage, $secondExpectedImage);
}
/**
* @return array
*/
public function galleryImagesDataProvider(): array
{
return [
'with_main_image' => [
'images' => [
'/m/a/magento_image.jpg' => [],
'/m/a/magento_thumbnail.jpg' => ['main' => true],
],
'expectation' => [
$this->imageExpectation,
array_merge($this->thumbnailExpectation, ['isMain' => true]),
],
],
'without_main_image' => [
'images' => [
'/m/a/magento_image.jpg' => [],
'/m/a/magento_thumbnail.jpg' => [],
],
'expectation' => [
array_merge($this->imageExpectation, ['isMain' => true]),
$this->thumbnailExpectation,
],
],
'with_changed_position' => [
'images' => [
'/m/a/magento_image.jpg' => ['position' => '2'],
'/m/a/magento_thumbnail.jpg' => ['position' => '1'],
],
'expectation' => [
array_merge($this->thumbnailExpectation, ['position' => '1']),
array_merge($this->imageExpectation, ['position' => '2', 'isMain' => true]),
],
],
];
}
/**
* @dataProvider galleryImagesWithImageOptimizationParametersInUrlDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php
* @magentoConfigFixture default/web/url/catalog_media_url_format image_optimization_parameters
* @magentoDbIsolation enabled
* @param array $images
* @param array $expectation
* @return void
*/
public function testGetGalleryImagesJsonWithImageOptimizationParametersInUrl(
array $images,
array $expectation
): void {
$product = $this->getProduct();
$this->setGalleryImages($product, $images);
$this->block->setData('product', $this->getProduct());
[$firstImage, $secondImage] = $this->serializer->unserialize($this->block->getGalleryImagesJson());
[$firstExpectedImage, $secondExpectedImage] = $expectation;
$this->assertImages($firstImage, $firstExpectedImage);
$this->assertImages($secondImage, $secondExpectedImage);
}
/**
* @return array
*/
public function galleryImagesWithImageOptimizationParametersInUrlDataProvider(): array
{
$imageExpectation = [
'thumb' => '/m/a/magento_image.jpg?width=88&height=110&store=default&image-type=thumbnail',
'img' => '/m/a/magento_image.jpg?width=700&height=700&store=default&image-type=image',
'full' => '/m/a/magento_image.jpg?store=default&image-type=image',
'caption' => 'Image Alt Text',
'position' => '1',
'isMain' => false,
'type' => 'image',
'videoUrl' => null,
];
$thumbnailExpectation = [
'thumb' => '/m/a/magento_thumbnail.jpg?width=88&height=110&store=default&image-type=thumbnail',
'img' => '/m/a/magento_thumbnail.jpg?width=700&height=700&store=default&image-type=image',
'full' => '/m/a/magento_thumbnail.jpg?store=default&image-type=image',
'caption' => 'Thumbnail Image',
'position' => '2',
'isMain' => false,
'type' => 'image',
'videoUrl' => null,
];
return [
'with_main_image' => [
'images' => [
'/m/a/magento_image.jpg' => [],
'/m/a/magento_thumbnail.jpg' => ['main' => true],
],
'expectation' => [
$imageExpectation,
array_merge($thumbnailExpectation, ['isMain' => true]),
],
],
'without_main_image' => [
'images' => [
'/m/a/magento_image.jpg' => [],
'/m/a/magento_thumbnail.jpg' => [],
],
'expectation' => [
array_merge($imageExpectation, ['isMain' => true]),
$thumbnailExpectation,
],
],
'with_changed_position' => [
'images' => [
'/m/a/magento_image.jpg' => ['position' => '2'],
'/m/a/magento_thumbnail.jpg' => ['position' => '1'],
],
'expectation' => [
array_merge($thumbnailExpectation, ['position' => '1']),
array_merge($imageExpectation, ['position' => '2', 'isMain' => true]),
],
],
];
}
/**
* @dataProvider galleryImagesOnStoreViewDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoConfigFixture default/web/url/catalog_media_url_format hash
* @magentoDbIsolation disabled
* @param array $images
* @param array $expectation
* @return void
*/
public function testGetGalleryImagesJsonOnStoreView(array $images, array $expectation): void
{
$secondStoreId = (int)$this->storeRepository->get('fixture_second_store')->getId();
$product = $this->getProduct($secondStoreId);
$this->setGalleryImages($product, $images);
$this->block->setData('product', $this->getProduct($secondStoreId));
[$firstImage, $secondImage] = $this->serializer->unserialize($this->block->getGalleryImagesJson());
[$firstExpectedImage, $secondExpectedImage] = $expectation;
$this->assertImages($firstImage, $firstExpectedImage);
$this->assertImages($secondImage, $secondExpectedImage);
}
/**
* @return array
*/
public function galleryImagesOnStoreViewDataProvider(): array
{
return [
'with_store_labels' => [
'images' => [
'/m/a/magento_image.jpg' => ['label' => 'Some store label'],
'/m/a/magento_thumbnail.jpg' => [],
],
'expectation' => [
array_merge($this->imageExpectation, ['isMain' => true, 'caption' => 'Some store label']),
$this->thumbnailExpectation,
],
],
'with_changed_position' => [
'images' => [
'/m/a/magento_image.jpg' => ['position' => '3'],
'/m/a/magento_thumbnail.jpg' => [],
],
'expectation' => [
array_merge($this->thumbnailExpectation, ['position' => '2']),
array_merge($this->imageExpectation, ['position' => '3', 'isMain' => true]),
],
],
'with_main_store_image' => [
'images' => [
'/m/a/magento_image.jpg' => [],
'/m/a/magento_thumbnail.jpg' => ['main' => true],
],
'expectation' => [
$this->imageExpectation,
array_merge($this->thumbnailExpectation, ['isMain' => true]),
],
],
];
}
/**
* Tests images positions in store view
*
* @magentoDataFixture Magento/Catalog/_files/product_with_image.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoConfigFixture default/web/url/catalog_media_url_format image_optimization_parameters
* @dataProvider imagesPositionStoreViewDataProvider
* @param string $addFromStore
* @param array $newImages
* @param string $viewFromStore
* @param array $expectedImages
* @return void
*/
public function testImagesPositionStoreView(
string $addFromStore,
array $newImages,
string $viewFromStore,
array $expectedImages
): void {
$storeId = (int)$this->storeRepository->get($addFromStore)->getId();
$product = $this->getProduct($storeId);
$images = $product->getData('media_gallery')['images'];
$images = array_merge($images, $newImages);
$product->setData('media_gallery', ['images' => $images]);
$updateHandler = Bootstrap::getObjectManager()->create(UpdateHandler::class);
$updateHandler->execute($product);
$storeId = (int)$this->storeRepository->get($viewFromStore)->getId();
$product = $this->getProduct($storeId);
$this->block->setData('product', $product);
$actualImages = array_map(
function ($item) {
return [
'img' => parse_url($item['img'], PHP_URL_PATH),
'caption' => $item['caption'],
'position' => $item['position'],
];
},
$this->serializer->unserialize($this->block->getGalleryImagesJson())
);
$this->assertEquals($expectedImages, array_values($actualImages));
}
/**
* @return array[]
*/
public function imagesPositionStoreViewDataProvider(): array
{
return [
[
'fixture_second_store',
[
[
'file' => '/m/a/magento_small_image.jpg',
'position' => 2,
'label' => 'New Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
]
],
'default',
[
[
'img' => '/media/catalog/product/m/a/magento_image.jpg',
'caption' => 'Image Alt Text',
'position' => 1,
],
[
'img' => '/media/catalog/product/m/a/magento_small_image.jpg',
'caption' => 'Simple Product',
'position' => 2,
],
]
],
[
'fixture_second_store',
[
[
'file' => '/m/a/magento_small_image.jpg',
'position' => 2,
'label' => 'New Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
]
],
'fixture_second_store',
[
[
'img' => '/media/catalog/product/m/a/magento_image.jpg',
'caption' => 'Image Alt Text',
'position' => 1,
],
[
'img' => '/media/catalog/product/m/a/magento_small_image.jpg',
'caption' => 'New Image Alt Text',
'position' => 2,
],
]
]
];
}
/**
* Updates product gallery images and saves product.
*
* @param ProductInterface $product
* @param array $images
* @param int|null $storeId
* @return void
*/
private function setGalleryImages(ProductInterface $product, array $images, int $storeId = null): void
{
$product->setImage(null);
foreach ($images as $file => $data) {
$mediaGalleryData = $product->getData('media_gallery');
foreach ($mediaGalleryData['images'] as &$image) {
if ($image['file'] == $file) {
foreach ($data as $key => $value) {
$image[$key] = $value;
}
}
}
$product->setData('media_gallery', $mediaGalleryData);
if (!empty($data['main'])) {
$product->setImage($file);
}
}
if ($storeId) {
$product->setStoreId($storeId);
}
$this->productResource->save($product);
}
/**
* Returns current product.
*
* @param int|null $storeId
* @return ProductInterface
*/
private function getProduct(?int $storeId = null): ProductInterface
{
return $this->productRepository->get('simple', false, $storeId, true);
}
/**
* Asserts gallery image data.
*
* @param array $image
* @param array $expectedImage
* @return void
*/
private function assertImages(array $image, array $expectedImage): void
{
$this->assertStringEndsWith($expectedImage['thumb'], $image['thumb']);
$this->assertStringEndsWith($expectedImage['img'], $image['img']);
$this->assertStringEndsWith($expectedImage['full'], $image['full']);
$this->assertEquals($expectedImage['caption'], $image['caption']);
$this->assertEquals($expectedImage['position'], $image['position']);
$this->assertEquals($expectedImage['isMain'], $image['isMain']);
$this->assertEquals($expectedImage['type'], $image['type']);
$this->assertEquals($expectedImage['videoUrl'], $image['videoUrl']);
}
}
@@ -0,0 +1,170 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Store\Model\StoreManagerInterface;
/**
* Checks currency displaying and converting on the catalog pages on multi store mode
*
* @magentoAppArea frontend
* @magentoDbIsolation disabled
*/
class MultiStoreCurrencyTest extends AbstractCurrencyTest
{
/** @var StoreManagerInterface */
private $storeManager;
/** @var ResolverInterface */
private $localeResolver;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->localeResolver = $this->objectManager->get(ResolverInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* @magentoConfigFixture default/currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
* @magentoConfigFixture fixturestore_store currency/options/default UAH
* @magentoConfigFixture fixturestore_store currency/options/allow UAH,USD
*
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
* @magentoDataFixture Magento/Directory/_files/usd_uah_rate.php
*
* @return void
*/
public function testMultiStoreRenderPrice(): void
{
$this->localeResolver->setLocale('zh_CN');
$this->assertProductStorePrice('simple2', '¥70.00');
$this->reloadProductPriceInfo();
$this->localeResolver->setLocale('uk_UA');
$this->assertProductStorePrice('simple2', '240,00 ₴', 'fixturestore');
}
/**
* @magentoConfigFixture default/currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
* @magentoConfigFixture fixturestore_store currency/options/default UAH
* @magentoConfigFixture fixturestore_store currency/options/allow UAH,USD
*
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/product_special_price.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
* @magentoDataFixture Magento/Directory/_files/usd_uah_rate.php
*
* @return void
*/
public function testMultiStoreRenderSpecialPrice(): void
{
$this->localeResolver->setLocale('zh_CN');
$this->assertProductStorePrice('simple', 'Special Price ¥41.93 Regular Price ¥70.00');
$this->reloadProductPriceInfo();
$this->localeResolver->setLocale('uk_UA');
$this->assertProductStorePrice('simple', 'Special Price 143,76 ₴ Regular Price 240,00 ₴', 'fixturestore');
}
/**
* @magentoConfigFixture default/currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
* @magentoConfigFixture fixturestore_store currency/options/default UAH
* @magentoConfigFixture fixturestore_store currency/options/allow UAH,USD
*
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
* @magentoDataFixture Magento/Directory/_files/usd_uah_rate.php
*
* @return void
*/
public function testMultiStoreRenderTierPrice(): void
{
$this->localeResolver->setLocale('zh_CN');
$this->assertProductStorePrice(
'simple-product-tax-none',
'Buy 2 for ¥280.00 each and save 80%',
'default',
self::TIER_PRICE_BLOCK_NAME
);
$this->reloadProductPriceInfo();
$this->localeResolver->setLocale('uk_UA');
$this->assertProductStorePrice(
'simple-product-tax-none',
'Buy 2 for 960,00 ₴ each and save 80%',
'fixturestore',
self::TIER_PRICE_BLOCK_NAME
);
}
/**
* Check price per stores
*
* @param string $productSku
* @param string $expectedData
* @param string $storeCode
* @param string $priceBlockName
* @return void
*/
private function assertProductStorePrice(
string $productSku,
string $expectedData,
string $storeCode = 'default',
string $priceBlockName = self::FINAL_PRICE_BLOCK_NAME
): void {
$currentStore = $this->storeManager->getStore();
try {
if ($currentStore->getCode() !== $storeCode) {
$this->storeManager->setCurrentStore($storeCode);
}
$actualData = $this->processPriceView($productSku, $priceBlockName);
self::assertEquals($expectedData, $actualData);
} finally {
if ($currentStore->getCode() !== $storeCode) {
$this->storeManager->setCurrentStore($currentStore);
}
}
}
/**
* Reload product price info
*
* @return void
*/
private function reloadProductPriceInfo(): void
{
$product = $this->registry->registry('product');
self::assertNotNull($product);
$product->reloadPriceInfo();
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
$this->localeResolver->setLocale(\Magento\Setup\Module\I18n\Locale::DEFAULT_SYSTEM_LOCALE);
parent::tearDown();
}
}
@@ -0,0 +1,444 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Options;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory;
use Magento\Catalog\Api\Data\ProductCustomOptionValuesInterface;
use Magento\Catalog\Api\Data\ProductCustomOptionValuesInterfaceFactory;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\View\Options;
use Magento\Catalog\Model\Product\Option;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Base logic for render custom options and check that option renders as expected.
*/
abstract class AbstractRenderCustomOptionsTest extends TestCase
{
/**
* @var ObjectManager
*/
protected $objectManager;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var ProductCustomOptionInterfaceFactory
*/
private $productCustomOptionFactory;
/**
* @var ProductCustomOptionValuesInterfaceFactory
*/
private $productCustomOptionValuesFactory;
/**
* @var Page
*/
private $page;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->productCustomOptionFactory = $this->objectManager->get(ProductCustomOptionInterfaceFactory::class);
$this->productCustomOptionValuesFactory = $this->objectManager->get(
ProductCustomOptionValuesInterfaceFactory::class
);
$this->page = $this->objectManager->get(PageFactory::class)->create();
parent::setUp();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->productRepository->cleanCache();
parent::tearDown();
}
/**
* Add provided options from text group to product, render options block
* and check that options rendered as expected.
*
* @param string $productSku
* @param array $optionData
* @param array $checkArray
* @return void
*/
protected function assertTextOptionRenderingOnProduct(
string $productSku,
array $optionData,
array $checkArray
): void {
$product = $this->productRepository->get($productSku);
$product = $this->addOptionToProduct($product, $optionData);
$option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]);
$optionHtml = $this->getOptionHtml($product);
$this->baseOptionAsserts($option, $optionHtml, $checkArray);
$this->additionalTypeTextAsserts($option, $optionHtml, $checkArray);
}
/**
* Additional asserts for rendering text type options.
*
* @param ProductCustomOptionInterface $option
* @param string $optionHtml
* @param array $checkArray
* @return void
*/
protected function additionalTypeTextAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
if ($option->getMaxCharacters() > 0) {
$this->assertStringContainsString($checkArray['max_characters'], $optionHtml);
} else {
$this->assertStringNotContainsString($this->getMaxCharactersCssClass(), $optionHtml);
}
}
/**
* Add provided options from file group to product, render options block
* and check that options rendered as expected.
*
* @param string $productSku
* @param array $optionData
* @param array $checkArray
* @return void
*/
protected function assertFileOptionRenderingOnProduct(
string $productSku,
array $optionData,
array $checkArray
): void {
$product = $this->productRepository->get($productSku);
$product = $this->addOptionToProduct($product, $optionData);
$option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]);
$optionHtml = $this->getOptionHtml($product);
$this->baseOptionAsserts($option, $optionHtml, $checkArray);
$this->assertStringContainsString($checkArray['file_extension'], $optionHtml);
if (isset($checkArray['file_width'])) {
$checkArray['file_width'] = sprintf($checkArray['file_width'], __('Maximum image width'));
$this->assertMatchesRegularExpression($checkArray['file_width'], $optionHtml);
}
if (isset($checkArray['file_height'])) {
$checkArray['file_height'] = sprintf($checkArray['file_height'], __('Maximum image height'));
$this->assertMatchesRegularExpression($checkArray['file_height'], $optionHtml);
}
}
/**
* Add provided options from select group to product, render options block
* and check that options rendered as expected.
*
* @param string $productSku
* @param array $optionData
* @param array $optionValueData
* @param array $checkArray
* @return void
*/
protected function assertSelectOptionRenderingOnProduct(
string $productSku,
array $optionData,
array $optionValueData,
array $checkArray
): void {
$product = $this->productRepository->get($productSku);
$product = $this->addOptionToProduct($product, $optionData, $optionValueData);
$option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]);
$optionHtml = $this->getOptionHtml($product);
$this->baseOptionAsserts($option, $optionHtml, $checkArray);
$this->additionalTypeSelectAsserts($option, $optionHtml, $checkArray);
}
/**
* Additional asserts for rendering select type options.
*
* @param ProductCustomOptionInterface $option
* @param string $optionHtml
* @param array $checkArray
* @return void
*/
protected function additionalTypeSelectAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
$optionValues = $option->getValues();
$optionValue = reset($optionValues);
if (isset($checkArray['not_contain_arr'])) {
foreach ($checkArray['not_contain_arr'] as $notContainPattern) {
$this->assertDoesNotMatchRegularExpression($notContainPattern, $optionHtml);
}
}
if (isset($checkArray['option_value_item'])) {
$checkArray['option_value_item'] = sprintf(
$checkArray['option_value_item'],
$optionValue->getOptionTypeId(),
$optionValue->getTitle()
);
$this->assertMatchesRegularExpression($checkArray['option_value_item'], $optionHtml);
}
}
/**
* Add provided options from date group to product, render options block
* and check that options rendered as expected.
*
* @param string $productSku
* @param array $optionData
* @param array $checkArray
* @return void
*/
protected function assertDateOptionRenderingOnProduct(
string $productSku,
array $optionData,
array $checkArray
): void {
$product = $this->productRepository->get($productSku);
$product = $this->addOptionToProduct($product, $optionData);
$option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]);
$optionHtml = $this->getOptionHtml($product);
$this->baseOptionAsserts($option, $optionHtml, $checkArray);
switch ($optionData[Option::KEY_TYPE]) {
case ProductCustomOptionInterface::OPTION_TYPE_DATE:
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][month]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][day]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][year]\"",
$optionHtml
);
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][hour]\"",
$optionHtml
);
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][minute]\"",
$optionHtml
);
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][day_part]\"",
$optionHtml
);
break;
case ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME:
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][month]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][day]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][year]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][hour]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][minute]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][day_part]\"",
$optionHtml
);
break;
case ProductCustomOptionInterface::OPTION_TYPE_TIME:
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][month]\"",
$optionHtml
);
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][day]\"",
$optionHtml
);
$this->assertStringNotContainsString(
"<select name=\"options[{$option->getOptionId()}][year]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][hour]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][minute]\"",
$optionHtml
);
$this->assertStringContainsString(
"<select name=\"options[{$option->getOptionId()}][day_part]\"",
$optionHtml
);
break;
}
}
/**
* Base asserts for rendered options.
*
* @param ProductCustomOptionInterface $option
* @param string $optionHtml
* @param array $checkArray
* @return void
*/
protected function baseOptionAsserts(
ProductCustomOptionInterface $option,
string $optionHtml,
array $checkArray
): void {
$this->assertStringContainsString($checkArray['block_with_required_class'], $optionHtml);
$this->assertStringContainsString($checkArray['title'], $optionHtml);
if (isset($checkArray['label_for_created_option'])) {
$checkArray['label_for_created_option'] = sprintf(
$checkArray['label_for_created_option'],
$option->getOptionId()
);
$this->assertStringContainsString($checkArray['label_for_created_option'], $optionHtml);
}
if (isset($checkArray['price'])) {
$this->assertStringContainsString($checkArray['price'], $optionHtml);
}
if (isset($checkArray['required_element'])) {
$this->assertMatchesRegularExpression($checkArray['required_element'], $optionHtml);
}
}
/**
* Add custom option to product with data.
*
* @param ProductInterface $product
* @param array $optionData
* @param array $optionValueData
* @return ProductInterface
*/
protected function addOptionToProduct(
ProductInterface $product,
array $optionData,
array $optionValueData = []
): ProductInterface {
$optionData[Option::KEY_PRODUCT_SKU] = $product->getSku();
if (!empty($optionValueData)) {
$optionValueData = $this->productCustomOptionValuesFactory->create(['data' => $optionValueData]);
$optionData['values'] = [$optionValueData];
}
$option = $this->productCustomOptionFactory->create(['data' => $optionData]);
$product->setOptions([$option]);
return $this->productRepository->save($product);
}
/**
* Render custom options block.
*
* @param ProductInterface $product
* @return string
*/
protected function getOptionHtml(ProductInterface $product): string
{
$this->page->addHandle($this->getHandlesList());
$this->page->getLayout()->generateXml();
/** @var Options $optionsBlock */
$optionsBlock = $this->page->getLayout()->getBlock($this->getOptionsBlockName());
$this->assertNotFalse($optionsBlock);
$optionsBlock->setProduct($product);
return $optionsBlock->toHtml();
}
/**
* Find and return custom option.
*
* @param ProductInterface $product
* @param string $optionTitle
* @return null|Option
*/
protected function findOptionByTitle(ProductInterface $product, string $optionTitle): ?Option
{
$option = null;
foreach ($product->getOptions() as $customOption) {
if ($customOption->getTitle() === $optionTitle) {
$option = $customOption;
break;
}
}
return $option;
}
/**
* Find and return custom option value.
*
* @param ProductCustomOptionInterface $option
* @param string $optionValueTitle
* @return null|ProductCustomOptionValuesInterface
*/
protected function findOptionValueByTitle(
ProductCustomOptionInterface $option,
string $optionValueTitle
): ?ProductCustomOptionValuesInterface {
$optionValue = null;
foreach ($option->getValues() as $customOptionValue) {
if ($customOptionValue->getTitle() === $optionValueTitle) {
$optionValue = $customOptionValue;
break;
}
}
return $optionValue;
}
/**
* Return all need handles for load.
*
* @return array
*/
abstract protected function getHandlesList(): array;
/**
* @return string
*/
abstract protected function getMaxCharactersCssClass(): string;
/**
* @return string
*/
abstract protected function getOptionsBlockName(): string;
}
@@ -0,0 +1,107 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Options;
/**
* Test cases related to check that simple product custom option renders as expected.
*
* @magentoAppArea frontend
*/
class RenderOptionsTest extends AbstractRenderCustomOptionsTest
{
/**
* Check that options from text group(field, area) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider \Magento\TestFramework\Catalog\Block\Product\View\Options\TextGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromTextGroup(array $optionData, array $checkArray): void
{
$this->assertTextOptionRenderingOnProduct('simple', $optionData, $checkArray);
}
/**
* Check that options from file group(file) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider \Magento\TestFramework\Catalog\Block\Product\View\Options\FileGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromFileGroup(array $optionData, array $checkArray): void
{
$this->assertFileOptionRenderingOnProduct('simple', $optionData, $checkArray);
}
/**
* Check that options from select group(drop-down, radio buttons, checkbox, multiple select) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider \Magento\TestFramework\Catalog\Block\Product\View\Options\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('simple', $optionData, $optionValueData, $checkArray);
}
/**
* Check that options from date group(date, date & time, time) render as expected.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options_with_stock_data.php
* @dataProvider \Magento\TestFramework\Catalog\Block\Product\View\Options\DateGroupDataProvider::getData
*
* @param array $optionData
* @param array $checkArray
* @return void
*/
public function testRenderCustomOptionsFromDateGroup(array $optionData, array $checkArray): void
{
$this->assertDateOptionRenderingOnProduct('simple', $optionData, $checkArray);
}
/**
* @inheritdoc
*/
protected function getHandlesList(): array
{
return [
'default',
'catalog_product_view',
];
}
/**
* @inheritdoc
*/
protected function getMaxCharactersCssClass(): string
{
return 'class="character-counter';
}
/**
* @inheritdoc
*/
protected function getOptionsBlockName(): string
{
return 'product.info.options';
}
}
@@ -0,0 +1,327 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View\Options\Type;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\Product as ProductHelper;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Option;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Pricing\Render;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DateTest extends TestCase
{
/**
* @var Date
*/
private $block;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var DataObjectFactory
*/
private $dataObjectFactory;
/**
* @var ProductHelper
*/
private $productHelper;
/**
* @var ResolverInterface
*/
private $localeResolver;
/**
* @var string
*/
private $defaultLocale;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
$this->productHelper = $objectManager->get(ProductHelper::class);
$this->dataObjectFactory = $objectManager->get(DataObjectFactory::class);
$layout = $objectManager->get(LayoutInterface::class);
$this->localeResolver = $objectManager->get(ResolverInterface::class);
$this->defaultLocale = $this->localeResolver->getLocale();
$this->block = $layout->createBlock(
Date::class,
'product.info.options.date',
[
'data' => [
'template' => 'Magento_Catalog::product/view/options/type/date.phtml'
]
]
);
$layout->createBlock(
Render::class,
'product.price.render.default',
[
'data' => [
'price_render_handle' => 'catalog_product_prices',
'use_link_for_as_low_as' => true,
],
]
);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
$this->localeResolver->setLocale($this->defaultLocale);
parent::tearDown();
}
/**
* @param array $data
* @param array $expected
* @magentoAppArea frontend
* @magentoConfigFixture current_store catalog/custom_options/year_range 2020,2030
* @dataProvider toHtmlWithDropDownDataProvider
*/
public function testToHtmlWithDropDown(array $data, array $expected): void
{
$this->prepareBlock($data);
$this->assertXPaths($expected);
}
/**
* @param array $data
* @param array $expected
* @param string|null $locale
* @magentoAppArea frontend
* @magentoConfigFixture current_store catalog/custom_options/use_calendar 1
* @magentoConfigFixture current_store catalog/custom_options/year_range 2020,2030
* @dataProvider toHtmlWithCalendarDataProvider
*/
public function testToHtmlWithCalendar(array $data, array $expected, ?string $locale = null): void
{
if ($locale) {
$this->localeResolver->setLocale($locale);
}
$this->prepareBlock($data);
$this->assertXPaths($expected);
}
/**
* @param array $expected
*/
private function assertXPaths(array $expected): void
{
$html = $this->block->toHtml();
$domXpath = new \DOMXPath($this->getHtmlDocument($html));
foreach ($expected as $xpath => $value) {
$xpath = strtr($xpath, ['{id}' => $this->block->getOption()->getId()]);
$nodes = $domXpath->query(strtr($xpath, ['{id}' => $this->block->getOption()->getId()]));
$this->assertEquals(1, $nodes->count(), 'Cannot find element \'' . $xpath . '"\' in the HTML');
$this->assertEquals($value, $nodes->item(0)->getAttribute('value'));
}
}
/**
* @param array $data
*/
private function prepareBlock(array $data): void
{
/** @var Product $product */
$product = $this->productRepository->get('simple');
$this->block->setProduct($product);
$option = $this->getDateTimeOption($product);
$this->block->setOption($option);
$buyRequest = $this->dataObjectFactory->create();
$buyRequest->setData(
[
'qty' => 1,
'options' => [
$option->getId() => $data
],
]
);
$this->productHelper->prepareProductOptions($product, $buyRequest);
}
/**
* @param Product $product
* @return Option|null
*/
private function getDateTimeOption(Product $product): ?Option
{
$option = null;
foreach ($product->getOptions() as $customOption) {
if ($customOption->getType() === Option::OPTION_TYPE_DATE_TIME) {
$option = $customOption;
break;
}
}
return $option;
}
/**
* @param string $source
* @return \DOMDocument
*/
private function getHtmlDocument(string $source): \DOMDocument
{
$page =<<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
$source
</body>
</html>
HTML;
$domDocument = new \DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$domDocument->loadHTML($page);
libxml_use_internal_errors(false);
return $domDocument;
}
/**
* @return array
*/
public function toHtmlWithDropDownDataProvider(): array
{
return [
[
[
'month' => '3',
'day' => '5',
'year' => '2020',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//select[@id="options_{id}_year"]/option[@selected]' => '2020',
'//select[@id="options_{id}_month"]/option[@selected]' => '3',
'//select[@id="options_{id}_day"]/option[@selected]' => '5',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
]
],
[
[
'date' => '09/30/2022',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//select[@id="options_{id}_year"]/option[@selected]' => '2020',
'//select[@id="options_{id}_month"]/option[@selected]' => '9',
'//select[@id="options_{id}_day"]/option[@selected]' => '30',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
]
]
];
}
/**
* @return array
*/
public function toHtmlWithCalendarDataProvider(): array
{
return [
[
[
'month' => '3',
'day' => '5',
'year' => '2020',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//input[@id="options_{id}_date"]' => '3/5/2020',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
]
],
[
[
'date' => '09/30/2022',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//input[@id="options_{id}_date"]' => '9/30/2020',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
]
],
[
[
'month' => '3',
'day' => '5',
'year' => '2020',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//input[@id="options_{id}_date"]' => '05/03/2020',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
],
'fr_FR'
],
[
[
'date' => '09/30/2022',
'hour' => '2',
'minute' => '15',
'day_part' => 'am',
'date_internal' => '2020-09-30 02:15:00'
],
[
'//input[@id="options_{id}_date"]' => '30/09/2020',
'//select[@id="options_{id}_hour"]/option[@selected]' => '2',
'//select[@id="options_{id}_minute"]/option[@selected]' => '15',
'//select[@id="options_{id}_day_part"]/option[@selected]' => 'am',
],
'fr_FR'
]
];
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Product\View;
/**
* Test class for \Magento\Catalog\Block\Product\View\Options.
*/
class OptionsTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Block\Product\View\Options
*/
protected $block;
/**
* @var \Magento\Catalog\Model\Product
*/
protected $product;
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $objectManager;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
try {
$this->product = $this->productRepository->get('simple');
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
$this->product = $this->productRepository->get('simple_dropdown_option');
}
$this->objectManager->get(\Magento\Framework\Registry::class)->unregister('current_product');
$this->objectManager->get(\Magento\Framework\Registry::class)->register('current_product', $this->product);
$this->block = $this->objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Catalog\Block\Product\View\Options::class
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSetGetProduct()
{
$this->assertSame($this->product, $this->block->getProduct());
$product = $this->objectManager->create(
\Magento\Catalog\Model\Product::class
);
$this->block->setProduct($product);
$this->assertSame($product, $this->block->getProduct());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGetGroupOfOption()
{
$this->assertEquals('default', $this->block->getGroupOfOption('test'));
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testGetOptions()
{
$options = $this->block->getOptions();
$this->assertNotEmpty($options);
foreach ($options as $option) {
$this->assertInstanceOf(\Magento\Catalog\Model\Product\Option::class, $option);
}
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testHasOptions()
{
$this->assertTrue($this->block->hasOptions());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_with_dropdown_option.php
*/
public function testGetJsonConfig()
{
$config = json_decode($this->block->getJsonConfig(), true);
$configValues = array_values($config);
$this->assertEquals($this->getExpectedJsonConfig(), array_values($configValues[0]));
}
/**
* Expected data for testGetJsonConfig
*
* @return array
*/
private function getExpectedJsonConfig()
{
return [
0 => [
'prices' =>
['oldPrice' =>
['amount' => 10, 'adjustments' => []],
'basePrice' => ['amount' => 10],
'finalPrice' => ['amount' => 10]
],
'type' => 'fixed',
'name' => 'drop_down option 1',
],
1 => [
'prices' =>
['oldPrice' =>
['amount' => 40, 'adjustments' => []],
'basePrice' => ['amount' => 40],
'finalPrice' => ['amount' => 40],
],
'type' => 'percent',
'name' => 'drop_down option 2',
],
];
}
}
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product\View;
/**
* Checks currency displaying and converting on the catalog pages
*
* @magentoAppArea frontend
*/
class SingleStoreCurrencyTest extends AbstractCurrencyTest
{
/**
* @magentoConfigFixture current_store currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
*
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
*
* @return void
*/
public function testRenderPrice(): void
{
$priceHtml = $this->processPriceView('simple2');
$this->assertEquals('CN¥70.00', $priceHtml);
}
/**
* @magentoConfigFixture current_store currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow EUR,CNY
*
* @magentoDataFixture Magento/Catalog/_files/product_special_price.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
*
* @return void
*/
public function testRenderSpecialPrice(): void
{
$priceHtml = $this->processPriceView('simple');
$this->assertEquals('Special Price CN¥41.93 Regular Price CN¥70.00', $priceHtml);
}
/**
* @magentoConfigFixture current_store currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price.php
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
*
* @return void
*/
public function testRenderTierPrice(): void
{
$priceHtml = $this->processPriceView('simple-product-tax-none', self::TIER_PRICE_BLOCK_NAME);
$this->assertEquals('Buy 2 for CN¥280.00 each and save 80%', $priceHtml);
}
}
@@ -0,0 +1,294 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Block\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\View\Description;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks product view block.
*
* @see \Magento\Catalog\Block\Product\View
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation enabled
*/
class ViewTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var View */
private $block;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var Json */
private $json;
/** @var StoreManagerInterface */
private $storeManager;
/** @var Description */
private $descriptionBlock;
/** @var array */
private const SHORT_DESCRIPTION_BLOCK_DATA = [
'at_call' => 'getShortDescription',
'at_code' => 'short_description',
'overview' => 'overview',
'at_label' => 'none',
'title' => 'Overview',
'add_attribute' => 'description',
];
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(View::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->json = $this->objectManager->get(Json::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->descriptionBlock = $this->layout->createBlock(Description::class);
}
/**
* @return void
*/
public function testSetLayout(): void
{
$productView = $this->layout->createBlock(View::class);
$this->assertInstanceOf(LayoutInterface::class, $productView->getLayout());
}
/**
* @return void
*/
public function testGetProduct(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$this->assertNotEmpty($this->block->getProduct()->getId());
$this->assertEquals($product->getId(), $this->block->getProduct()->getId());
$this->registry->unregister('product');
$this->block->setProductId($product->getId());
$this->assertEquals($product->getId(), $this->block->getProduct()->getId());
}
/**
* @return void
*/
public function testCanEmailToFriend(): void
{
$this->assertFalse($this->block->canEmailToFriend());
}
/**
* @return void
*/
public function testGetAddToCartUrl(): void
{
$product = $this->productRepository->get('simple');
$url = $this->block->getAddToCartUrl($product);
$this->assertStringMatchesFormat(
'%scheckout/cart/add/%sproduct/' . $product->getId() . '/',
$url
);
}
/**
* @return void
*/
public function testGetJsonConfig(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$config = $this->json->unserialize($this->block->getJsonConfig());
$this->assertNotEmpty($config);
$this->assertArrayHasKey('productId', $config);
$this->assertEquals($product->getId(), $config['productId']);
}
/**
* Verifies that product tier prices config contains price and basePrice.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_fixed_tier_price.php
*
* @return void
*/
public function testTierPriceGetJsonConfig(): void
{
$product = $this->productRepository->get('simple-product-tax-none');
$this->registerProduct($product);
$config = $this->json->unserialize($this->block->getJsonConfig());
$this->assertNotEmpty($config);
$this->assertArrayHasKey('tierPrices', $config);
$this->assertArrayHasKey('basePrice', $config['tierPrices'][0]);
$this->assertArrayHasKey('price', $config['tierPrices'][0]);
}
/**
* @return void
*/
public function testHasOptions(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$this->assertTrue($this->block->hasOptions());
}
/**
* @return void
*/
public function testHasRequiredOptions(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$this->assertTrue($this->block->hasRequiredOptions());
}
/**
* @return void
*/
public function testStartBundleCustomization(): void
{
$this->markTestSkipped("Functionality not implemented in Magento 1.x. Implemented in Magento 2");
$this->assertFalse($this->block->startBundleCustomization());
}
/**
* @magentoAppArea frontend
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_out_of_stock.php
*/
public function testAddToCartBlockInvisibility(): void
{
$outOfStockProduct = $this->productRepository->get('simple-out-of-stock');
$this->registerProduct($outOfStockProduct);
$this->block->setTemplate('Magento_Catalog::product/view/addtocart.phtml');
$output = $this->block->toHtml();
$this->assertStringNotContainsString((string)__('Add to Cart'), $output);
}
/**
* @magentoAppArea frontend
*/
public function testAddToCartBlockVisibility(): void
{
$product = $this->productRepository->get('simple');
$this->registerProduct($product);
$this->block->setTemplate('Magento_Catalog::product/view/addtocart.phtml');
$output = $this->block->toHtml();
$this->assertStringContainsString((string)__('Add to Cart'), $output);
}
/**
* @magentoDbIsolation disabled
* @magentoAppArea frontend
* @magentoDataFixture Magento/Catalog/_files/product_multistore_different_short_description.php
* @return void
*/
public function testProductShortDescription(): void
{
$product = $this->productRepository->get('simple-different-short-description');
$currentStoreId = $this->storeManager->getStore()->getId();
$output = $this->renderDescriptionBlock($product);
$this->assertStringContainsString('First store view short description', $output);
$secondStore = $this->storeManager->getStore('fixturestore');
$this->storeManager->setCurrentStore($secondStore->getId());
try {
$product = $this->productRepository->get(
'simple-different-short-description',
false,
$secondStore->getId(),
true
);
$newBlockOutput = $this->renderDescriptionBlock($product, true);
$this->assertStringContainsString('Second store view short description', $newBlockOutput);
} finally {
$this->storeManager->setCurrentStore($currentStoreId);
}
}
/**
* @param ProductInterface $product
* @param bool $refreshBlock
* @return string
*/
private function renderDescriptionBlock(ProductInterface $product, bool $refreshBlock = false): string
{
$this->registerProduct($product);
$descriptionBlock = $this->getDescriptionBlock($refreshBlock);
$descriptionBlock->addData(self::SHORT_DESCRIPTION_BLOCK_DATA);
$descriptionBlock->setTemplate('Magento_Catalog::product/view/attribute.phtml');
return $this->descriptionBlock->toHtml();
}
/**
* Get description block
*
* @param bool $refreshBlock
* @return Description
*/
private function getDescriptionBlock(bool $refreshBlock): Description
{
if ($refreshBlock) {
$this->descriptionBlock = $this->layout->createBlock(Description::class);
}
return $this->descriptionBlock;
}
/**
* Register the product
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('product');
$this->registry->register('product', $product);
}
}