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,89 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Action;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\Search\Document as SearchDocument;
use Magento\Framework\Search\Request\Builder as SearchRequestBuilder;
use Magento\Framework\Search\Request\Config as SearchRequestConfig;
use Magento\Search\Model\AdapterFactory as AdapterFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Search products by attribute value search engine.
*/
class DataProviderTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var SearchRequestConfig
*/
private $searchRequestConfig;
/**
* @var SearchRequestBuilder
*/
private $requestBuilder;
/**
* @var AdapterFactory
*/
private $adapterFactory;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->searchRequestConfig = $this->objectManager->create(SearchRequestConfig::class);
$this->requestBuilder = $this->objectManager->create(
SearchRequestBuilder::class,
['config' => $this->searchRequestConfig]
);
$this->adapterFactory = $this->objectManager->get(AdapterFactory::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
parent::setUp();
}
/**
* Search product by custom attribute value.
*
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testSearchProductByAttribute(): void
{
$this->requestBuilder->bind('search_term', 'Option 1');
$this->requestBuilder->setRequestName('quick_search_container');
$queryRequest = $this->requestBuilder->create();
$adapter = $this->adapterFactory->create();
$queryResponse = $adapter->query($queryRequest);
$actualIds = [];
/** @var SearchDocument $document */
foreach ($queryResponse as $document) {
$actualIds[] = $document->getId();
}
$product = $this->productRepository->get('simple_for_search');
$this->assertContains($product->getId(), $actualIds, 'Product not found by searchable attribute.');
}
}
@@ -0,0 +1,167 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Action;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\CatalogSearch\Model\ResourceModel\EngineInterface as Engine;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Store\Model\Store;
use Magento\Catalog\Model\Product;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class for testing fulltext index rebuild
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class FullTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
$this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed");
}
/**
* Testing fulltext index rebuild
*
* @magentoDataFixture Magento/CatalogSearch/_files/products_for_index.php
* @magentoDataFixture Magento/CatalogSearch/_files/product_configurable_not_available.php
* @magentoDataFixture Magento/Framework/Search/_files/product_configurable.php
*/
public function testGetIndexData()
{
$engineProvider = Bootstrap::getObjectManager()->create(
\Magento\CatalogSearch\Model\ResourceModel\EngineProvider::class
);
$dataProvider = Bootstrap::getObjectManager()->create(
\Magento\CatalogSearch\Model\Indexer\Fulltext\Action\DataProvider::class,
['engineProvider' => $engineProvider]
);
$actionFull = Bootstrap::getObjectManager()->create(
\Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full::class,
['dataProvider' => $dataProvider]
);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$allowedStatuses = Bootstrap::getObjectManager()->get(Status::class)->getVisibleStatusIds();
$allowedVisibility = Bootstrap::getObjectManager()->get(Engine::class)->getAllowedVisibility();
$result = iterator_to_array($actionFull->rebuildStoreIndex(Store::DISTRO_STORE_ID));
$this->assertNotEmpty($result);
$productsIds = array_keys($result);
foreach ($productsIds as $productId) {
$product = $productRepository->getById($productId);
$this->assertContainsEquals($product->getVisibility(), $allowedVisibility);
$this->assertContainsEquals($product->getStatus(), $allowedStatuses);
}
$expectedData = $this->getExpectedIndexData();
foreach ($expectedData as $sku => $expectedIndexData) {
$product = $productRepository->get($sku);
$this->assertEquals($expectedIndexData, $result[$product->getId()]);
}
}
/**
* Prepare and return expected index data
*
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getExpectedIndexData()
{
/** @var ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->get(ProductAttributeRepositoryInterface::class);
$skuId = $attributeRepository->get(ProductInterface::SKU)->getAttributeId();
$nameId = $attributeRepository->get(ProductInterface::NAME)->getAttributeId();
/** @see dev/tests/integration/testsuite/Magento/Framework/Search/_files/configurable_attribute.php */
$configurableId = $attributeRepository->get('test_configurable')->getAttributeId();
$statusId = $attributeRepository->get(ProductInterface::STATUS)->getAttributeId();
$taxClassId = $attributeRepository
->get(\Magento\Customer\Api\Data\GroupInterface::TAX_CLASS_ID)
->getAttributeId();
$urlKeyId = $attributeRepository
->get(\Magento\Catalog\Api\Data\ProductAttributeInterface::CODE_SEO_FIELD_URL_KEY)
->getAttributeId();
return [
'configurable' => [
$skuId => 'configurable',
$configurableId => 'Option 2',
$nameId => 'Configurable Product | Configurable OptionOption 2',
$taxClassId => 'Taxable Goods | Taxable Goods',
$statusId => 'Enabled | Enabled',
$urlKeyId => 'configurable-product | configurable-optionoption-2'
],
'index_enabled' => [
$skuId => 'index_enabled',
$nameId => 'index enabled',
$taxClassId => 'Taxable Goods',
$statusId => 'Enabled',
$urlKeyId => 'index-enabled'
],
'index_visible_search' => [
$skuId => 'index_visible_search',
$nameId => 'index visible search',
$taxClassId => 'Taxable Goods',
$statusId => 'Enabled',
$urlKeyId => 'index-visible-search'
],
'index_visible_category' => [
$skuId => 'index_visible_category',
$nameId => 'index visible category',
$taxClassId => 'Taxable Goods',
$statusId => 'Enabled',
$urlKeyId => 'index-visible-category'
],
'index_visible_both' => [
$skuId => 'index_visible_both',
$nameId => 'index visible both',
$taxClassId => 'Taxable Goods',
$statusId => 'Enabled',
$urlKeyId => 'index-visible-both'
]
];
}
/**
* Testing fulltext index rebuild with configurations
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testRebuildStoreIndexConfigurable()
{
$actionFull = Bootstrap::getObjectManager()->create(
\Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full::class
);
$storeId = 1;
$simpleProductId = $this->getIdBySku('simple_10');
$configProductId = $this->getIdBySku('configurable');
$expected = [
$simpleProductId,
$configProductId
];
$storeIndexDataSimple = $actionFull->rebuildStoreIndex($storeId, [$simpleProductId]);
$storeIndexDataExpected = $actionFull->rebuildStoreIndex($storeId, $expected);
$this->assertEquals($storeIndexDataSimple, $storeIndexDataExpected);
}
/**
* Get product Id by its SKU
*
* @param string $sku
* @return int
*/
private function getIdBySku($sku)
{
/** @var Product $product */
$product = Bootstrap::getObjectManager()->get(Product::class);
return $product->getIdBySku($sku);
}
}
@@ -0,0 +1,84 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Model\Plugin;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\CatalogSearch\Model\Indexer\Fulltext\Processor;
use Magento\Framework\Indexer\StateInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test for category repository plugin
*/
class CategoryTest extends TestCase
{
/**
* @var Processor
*/
private $indexerProcessor;
/**
* @var CategoryRepositoryInterface
*/
private $categoryRepository;
/**
* @var CategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->indexerProcessor = Bootstrap::getObjectManager()->create(Processor::class);
$this->categoryRepository = Bootstrap::getObjectManager()->create(CategoryRepositoryInterface::class);
$this->categoryCollectionFactory = Bootstrap::getObjectManager()->create(CategoryCollectionFactory::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/indexer_catalog_category.php
* @magentoAppArea adminhtml
*/
public function testIndexerInvalidatedAfterCategoryDelete()
{
$this->indexerProcessor->reindexAll();
$isIndexerValid = (bool)$this->indexerProcessor->getIndexer()->isValid();
$category = $this->getCategories(1);
$this->categoryRepository->delete(array_pop($category));
$state = $this->indexerProcessor->getIndexer()->getState();
$state->loadByIndexer($this->indexerProcessor->getIndexerId());
$status = $state->getStatus();
$this->assertTrue($isIndexerValid);
$this->assertEquals(StateInterface::STATUS_INVALID, $status);
}
/**
* Returns categories
*
* @param int $count
* @return Category[]
*/
private function getCategories(int $count): array
{
$collection = $this->categoryCollectionFactory->create()
->addAttributeToSelect('name')
->addAttributeToSelect('is_active')
->getItems();
$result = array_slice($collection, 2);
return array_slice($result, 0, $count);
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\CatalogSearch\Model\Indexer\Fulltext\Processor;
use Magento\Catalog\Api\Data\EavAttributeInterface;
/**
* Check catalogsearch_fulltext index status after create product attribute.
*/
class AttributeTest extends TestCase
{
/**
* @var Processor
*/
private $indexerProcessor;
/**
* @var Attribute
*/
private $attribute;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->indexerProcessor = Bootstrap::getObjectManager()->create(Processor::class);
$this->attribute = Bootstrap::getObjectManager()->create(Attribute::class);
}
/**
* Check index status on clean database.
*
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*/
public function testCheckIndexStatusOnCleanDatabase(): void
{
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
}
/**
* Check index status after create non searchable attribute.
*
* @return void
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDbIsolation enabled
* @depends testCheckIndexStatusOnCleanDatabase
*/
public function testCheckIndexStatusAfterCreateNonSearchableAttribute(): void
{
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
}
/**
* Check index status after non searchable attribute update.
*
* @return void
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDbIsolation enabled
* @depends testCheckIndexStatusOnCleanDatabase
*/
public function testCheckIndexStatusAfterNonSearchableAttributeUpdate(): void
{
$this->attribute->load('dropdown_attribute', 'attribute_code');
$this->assertFalse($this->attribute->isObjectNew());
$this->attribute->setIsGlobal(1)->save();
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
}
/**
* Check index status after create searchable attribute.
*
* @return void
* @magentoDataFixture Magento/CatalogSearch/_files/search_attributes.php
* @magentoDbIsolation enabled
* @depends testCheckIndexStatusOnCleanDatabase
*/
public function testCheckIndexStatusAfterCreateSearchableAttribute(): void
{
$this->assertTrue($this->indexerProcessor->getIndexer()->isInvalid());
}
/**
* Check index status after update non searchable attribute to searchable.
*
* @param string $field
* @return void
* @dataProvider searchableAttributesDataProvider
* @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php
* @magentoDbIsolation enabled
*/
public function testCheckIndexStatusAfterUpdateNonSearchableAttributeToSearchable(string $field): void
{
$this->indexerProcessor->reindexAll();
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
$this->attribute->loadByCode(Product::ENTITY, 'dropdown_attribute');
$this->assertFalse($this->attribute->isObjectNew());
$this->attribute->setData($field, true)->save();
$this->assertFalse($this->indexerProcessor->getIndexer()->isValid());
}
/**
* @return array
*/
public function searchableAttributesDataProvider(): array
{
return [
[EavAttributeInterface::IS_SEARCHABLE],
[EavAttributeInterface::IS_FILTERABLE],
[EavAttributeInterface::IS_VISIBLE_IN_ADVANCED_SEARCH]
];
}
/**
* Check index status after update searchable attribute to non searchable.
*
* @return void
* @magentoDataFixture Magento/CatalogSearch/_files/search_attributes.php
* @magentoDbIsolation enabled
* @depends testCheckIndexStatusOnCleanDatabase
*/
public function testCheckIndexStatusAfterUpdateSearchableAttributeToNonSearchable(): void
{
$this->indexerProcessor->reindexAll();
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
$this->attribute->loadByCode(Product::ENTITY, 'test_catalog_view');
$this->assertFalse($this->attribute->isObjectNew());
$this->attribute->setIsFilterable(false)->save();
$this->assertFalse($this->indexerProcessor->getIndexer()->isValid());
}
}
@@ -0,0 +1,239 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Indexer;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/CatalogSearch/_files/indexer_fulltext.php
*/
class FulltextTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Indexer\IndexerInterface
*/
protected $indexer;
/**
* @var \Magento\Search\Model\QueryFactory
*/
protected $queryFactory;
/**
* @var Product
*/
protected $productApple;
/**
* @var Product
*/
protected $productBanana;
/**
* @var Product
*/
protected $productOrange;
/**
* @var Product
*/
protected $productPapaya;
/**
* @var Product
*/
protected $productCherry;
/**
* @var \Magento\Framework\Search\Request\Dimension
*/
protected $dimension;
protected function setUp(): void
{
/** @var \Magento\Framework\Indexer\IndexerInterface indexer */
$this->indexer = Bootstrap::getObjectManager()->create(
\Magento\Indexer\Model\Indexer::class
);
$this->indexer->load('catalogsearch_fulltext');
$this->queryFactory = Bootstrap::getObjectManager()->get(
\Magento\Search\Model\QueryFactory::class
);
$this->dimension = Bootstrap::getObjectManager()->create(
\Magento\Framework\Search\Request\Dimension::class,
['name' => 'scope', 'value' => '1']
);
$this->productApple = $this->getProductBySku('fulltext-1');
$this->productBanana = $this->getProductBySku('fulltext-2');
$this->productOrange = $this->getProductBySku('fulltext-3');
$this->productPapaya = $this->getProductBySku('fulltext-4');
$this->productCherry = $this->getProductBySku('fulltext-5');
}
public function testReindexAll()
{
$this->indexer->reindexAll();
$products = $this->search('Apple');
$this->assertCount(1, $products);
$this->assertEquals($this->productApple->getId(), $products[0]->getId());
$products = $this->search('Simple Product');
$this->assertCount(5, $products);
}
/**
*
*/
public function testReindexRowAfterEdit()
{
$this->indexer->reindexAll();
$this->productApple->setData('name', 'Simple Product Cucumber');
$this->productApple->save();
$products = $this->search('Apple');
$this->assertCount(0, $products);
$products = $this->search('Cucumber');
$this->assertCount(1, $products);
$this->assertEquals($this->productApple->getId(), $products[0]->getId());
$products = $this->search('Simple Product');
$this->assertCount(5, $products);
}
/**
*
*/
public function testReindexRowAfterMassAction()
{
$this->indexer->reindexAll();
$productIds = [
$this->productApple->getId(),
$this->productBanana->getId(),
];
$attrData = [
'name' => 'Simple Product Common',
];
/** @var \Magento\Catalog\Model\Product\Action $action */
$action = Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\Product\Action::class
);
$action->updateAttributes($productIds, $attrData, 1);
$products = $this->search('Apple');
$this->assertCount(0, $products);
$products = $this->search('Banana');
$this->assertCount(0, $products);
$products = $this->search('Unknown');
$this->assertCount(0, $products);
$products = $this->search('Common');
$this->assertCount(2, $products);
$products = $this->search('Simple Product');
$this->assertCount(5, $products);
}
/**
* @magentoAppArea adminhtml
*/
public function testReindexRowAfterDelete()
{
$this->indexer->reindexAll();
$this->productBanana->delete();
$products = $this->search('Simple Product');
$this->assertCount(4, $products);
}
/**
* Test the case when the last child product of the configurable becomes disabled/out of stock.
*
* Such behavior should enforce parent product to be deleted from the index as its latest child become unavailable
* and the configurable cannot be sold anymore.
*
* @return void
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/CatalogSearch/_files/product_configurable_with_single_child.php
*/
public function testReindexParentProductWhenChildBeingDisabled()
{
$this->indexer->reindexAll();
$visibilityFilter = [
Visibility::VISIBILITY_IN_SEARCH,
Visibility::VISIBILITY_IN_CATALOG,
Visibility::VISIBILITY_BOTH
];
$products = $this->search('Configurable', $visibilityFilter);
$this->assertCount(1, $products);
$childProduct = $this->getProductBySku('configurable_option_single_child');
$childProduct->setStatus(Product\Attribute\Source\Status::STATUS_DISABLED)->save();
$products = $this->search('Configurable', $visibilityFilter);
$this->assertCount(0, $products);
}
/**
* Search the text and return result collection
*
* @param string $text
* @param array|null $visibilityFilter
* @return Product[]
*/
protected function search(string $text, $visibilityFilter = null): array
{
$query = $this->queryFactory->get();
$query->unsetData();
$query->setQueryText($text);
$query->saveIncrementalPopularity();
$products = [];
$searchLayer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Layer\Search::class);
$collection = $searchLayer->getProductCollection();
$collection->addSearchFilter($text);
if (null !== $visibilityFilter) {
$collection->setVisibility($visibilityFilter);
}
foreach ($collection as $product) {
$products[] = $product;
}
return $products;
}
/**
* Return product by SKU
*
* @param string $sku
* @return Product|bool
*/
protected function getProductBySku(string $sku)
{
/** @var Product $product */
$product = Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\Product::class
);
return $product->loadByAttribute('sku', $sku);
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\Layer\Filter;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Model\Layer\Category as LayerCategory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Request;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Magento\CatalogSearch\Model\Layer\Filter\Attribute.
*
* @magentoDataFixture Magento/Catalog/Model/Layer/Filter/_files/attribute_with_option.php
*/
class AttributeTest extends TestCase
{
/**
* @var Attribute
*/
protected $_model;
/**
* @var int
*/
protected $_attributeOptionId;
/**
* @var mixed
*/
private $request;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeInterface $attribute */
$attribute = $objectManager->get(ProductAttributeInterface::class);
$attribute->loadByCode('catalog_product', 'attribute_with_option');
foreach ($attribute->getSource()->getAllOptions() as $optionInfo) {
if ($optionInfo['label'] == 'Option Label') {
$this->_attributeOptionId = $optionInfo['value'];
break;
}
}
/** @var LayerCategory $layer */
$layer = $objectManager->get(LayerCategory::class);
$this->request = $objectManager->get(Request::class);
$this->_model = $objectManager->create(Attribute::class, ['layer' => $layer]);
$this->_model->setAttributeModel($attribute);
$this->_model->setRequestVar('attribute');
}
/**
* @return void
*/
public function testOptionIdNotEmpty()
{
$this->assertNotEmpty($this->_attributeOptionId, 'Fixture attribute option id.'); // just in case
}
/**
* @return void
*/
public function testApplyInvalid()
{
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
$this->request->setParam('attribute', []);
$this->_model->apply($this->request);
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
}
/**
* @return void
*/
public function testApply()
{
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
$this->request->setParam('attribute', $this->_attributeOptionId);
$this->_model->apply($this->request);
$this->assertNotEmpty($this->_model->getLayer()->getState()->getFilters());
}
/**
* @return void
*/
public function testGetItemsWithApply()
{
$this->request->setParam('attribute', $this->_attributeOptionId);
$this->_model->apply($this->request);
$items = $this->_model->getItems();
$this->assertIsArray($items);
$this->assertEmpty($items);
}
}
@@ -0,0 +1,168 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\Layer\Filter;
/**
* Test class for \Magento\CatalogSearch\Model\Layer\Filter\Category.
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/categories.php
*/
class CategoryTest extends \PHPUnit\Framework\TestCase
{
const CURRENT_CATEGORY_FILTER = 'current_category_filter';
/**
* @var \Magento\CatalogSearch\Model\Layer\Filter\Category
*/
protected $_model;
/**
* @var \Magento\Catalog\Model\Category
*/
protected $_category;
protected function setUp(): void
{
$this->_category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Category::class
);
$this->_category->load(5);
$layer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(
\Magento\Catalog\Model\Layer\Category::class,
['data' => ['current_category' => $this->_category]]
);
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\CatalogSearch\Model\Layer\Filter\Category::class, ['layer' => $layer]);
$this->_model->setRequestVar('cat');
}
protected function tearDown(): void
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\Registry::class)->unregister(self::CURRENT_CATEGORY_FILTER);
}
public function testGetResetValue()
{
$this->assertNull($this->_model->getResetValue());
}
public function testApplyNothing()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model->apply(
$objectManager->get(\Magento\TestFramework\Request::class),
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Framework\View\Element\Text::class
)
);
/** @var $category \Magento\Catalog\Model\Category */
$category = $objectManager->get(\Magento\Framework\Registry::class)->registry(self::CURRENT_CATEGORY_FILTER);
$this->assertInstanceOf(\Magento\Catalog\Model\Category::class, $category);
$this->assertEquals($this->_category->getId(), $category->getId());
}
public function testApply()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$request = $objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('cat', 3);
$this->_model->apply($request);
/** @var $category \Magento\Catalog\Model\Category */
$category = $objectManager->get(\Magento\Framework\Registry::class)->registry(self::CURRENT_CATEGORY_FILTER);
$this->assertInstanceOf(\Magento\Catalog\Model\Category::class, $category);
$this->assertEquals(3, $category->getId());
return $this->_model;
}
/**
* @depends testApply
*/
public function testGetResetValueApplied(\Magento\CatalogSearch\Model\Layer\Filter\Category $modelApplied)
{
$this->assertEquals(2, $modelApplied->getResetValue());
}
public function testGetName()
{
$this->assertEquals('Category', $this->_model->getName());
}
/**
* @magentoDbIsolation disabled
*/
public function testGetItems()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$request = $objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('cat', 3);
$this->_model->apply($request);
/** @var $category \Magento\Catalog\Model\Category */
$category = $objectManager->get(\Magento\Framework\Registry::class)->registry(self::CURRENT_CATEGORY_FILTER);
$this->assertInstanceOf(\Magento\Catalog\Model\Category::class, $category);
$this->assertEquals(3, $category->getId());
$items = $this->_model->getItems();
$this->assertIsArray($items);
$this->assertCount(2, $items);
/** @var $item \Magento\Catalog\Model\Layer\Filter\Item */
$item = $items[0];
$this->assertInstanceOf(\Magento\Catalog\Model\Layer\Filter\Item::class, $item);
$this->assertSame($this->_model, $item->getFilter());
$this->assertEquals('Category 1.1', $item->getLabel());
$this->assertEquals(4, $item->getValue());
$this->assertEquals(2, $item->getCount());
$item = $items[1];
$this->assertInstanceOf(\Magento\Catalog\Model\Layer\Filter\Item::class, $item);
$this->assertEquals('Category 1.2', $item->getLabel());
$this->assertEquals(13, $item->getValue());
$this->assertEquals(2, $item->getCount());
}
/**
* Check that only children category of current category are aggregated
*
* @magentoDbIsolation disabled
*/
public function testCategoryAggregation(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$request = $objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('cat', 3);
$this->_model->apply($request);
/** @var $category \Magento\Catalog\Model\Category */
$category = $objectManager->get(\Magento\Framework\Registry::class)->registry(self::CURRENT_CATEGORY_FILTER);
$this->assertInstanceOf(\Magento\Catalog\Model\Category::class, $category);
$this->assertEquals(3, $category->getId());
$metrics = $this->_model->getLayer()->getProductCollection()->getFacetedData('category');
$this->assertIsArray($metrics);
$actual = [];
foreach ($metrics as $categoryId => $metric) {
$actual[$categoryId] = $metric['count'];
}
$this->assertEquals(
[
4 => 2,
13 => 2
],
$actual
);
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\Layer\Filter;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Model\Layer\Category as LayerCategory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Request;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Magento\CatalogSearch\Model\Layer\Filter\Decimal.
*
* @magentoDataFixture Magento/Catalog/Model/Layer/Filter/_files/attribute_weight_filterable.php
* @magentoDataFixture Magento/Catalog/_files/categories.php
* @magentoDataFixture Magento/Catalog/Model/Layer/Filter/Price/_files/products_base.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class DecimalTest extends TestCase
{
/**
* @var Decimal
*/
protected $_model;
/**
* @var mixed
*/
private $request;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
$category = $categoryRepository->get(4);
/** @var LayerCategory $layer */
$layer = $objectManager->create(
LayerCategory::class,
['data' => ['current_category' => $category]]
);
/** @var ProductAttributeInterface $attribute */
$attribute = $objectManager->get(ProductAttributeInterface::class);
$attribute->loadByCode('catalog_product', 'weight');
$this->request = $objectManager->get(Request::class);
$this->_model = $objectManager->create(Decimal::class, ['layer' => $layer]);
$this->_model->setAttributeModel($attribute);
$this->_model->setRequestVar('decimal');
}
/**
* @return void
*/
public function testApplyNothing()
{
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
$this->_model->apply($this->request);
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
}
/**
* @return void
*/
public function testApplyInvalid()
{
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
$this->request->setParam('decimal', 'non-decimal');
$this->_model->apply($this->request);
$filters = $this->_model->getLayer()->getState()->getFilters();
$this->assertArrayHasKey(0, $filters);
$this->assertEquals(
'<span class="price">$0.00</span> - <span class="price">$0.00</span>',
(string)$filters[0]->getLabel()
);
}
/**
* @return void
*/
public function testApply()
{
$this->assertEmpty($this->_model->getLayer()->getState()->getFilters());
$this->request->setParam('decimal', '1-100');
$this->_model->apply($this->request);
$filters = $this->_model->getLayer()->getState()->getFilters();
$this->assertArrayHasKey(0, $filters);
$this->assertEquals(
'<span class="price">$1.00</span> - <span class="price">$99.99</span>',
(string)$filters[0]->getLabel()
);
}
}
@@ -0,0 +1,169 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Layer\Filter;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\Layer\Category as CategoryLayer;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\CatalogSearch\Model\Layer\Filter\Price as PriceFilter;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DbIsolation;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for \Magento\CatalogSearch\Model\Layer\Filter\Price.
*
* @magentoDataFixture Magento/Catalog/_files/categories.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class PriceTest extends \PHPUnit\Framework\TestCase
{
/**
* @var PriceFilter
*/
private $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->initializePriceFilter();
}
public function testApplyNothing()
{
$this->assertEmpty($this->model->getData('price_range'));
/** @var $request \Magento\TestFramework\Request */
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
$this->model->apply($request);
$this->assertEmpty($this->model->getData('price_range'));
}
public function testApplyInvalid()
{
$this->assertEmpty($this->model->getData('price_range'));
/** @var $request \Magento\TestFramework\Request */
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('price', 'non-numeric');
$this->model->apply($request);
$this->assertEmpty($this->model->getData('price_range'));
}
/**
* @magentoConfigFixture current_store catalog/layered_navigation/price_range_calculation manual
*/
public function testApplyManual()
{
/** @var $request \Magento\TestFramework\Request */
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('price', '10-20');
$this->model->apply($request);
}
/**
* Make sure that currency rate is used to calculate label for applied price filter
*/
public function testApplyWithCustomCurrencyRate()
{
/** @var $request \Magento\TestFramework\Request */
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
$request->setParam('price', '10-20');
$this->model->setCurrencyRate(10);
$this->model->apply($request);
$filters = $this->model->getLayer()->getState()->getFilters();
$this->assertArrayHasKey(0, $filters);
$this->assertEquals(
'<span class="price">$100.00</span> - <span class="price">$199.99</span>',
(string)$filters[0]->getLabel()
);
}
public function testGetSetCustomerGroupId()
{
$this->assertEquals(
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID,
$this->model->getCustomerGroupId()
);
$customerGroupId = 123;
$this->model->setCustomerGroupId($customerGroupId);
$this->assertEquals($customerGroupId, $this->model->getCustomerGroupId());
}
public function testGetSetCurrencyRate()
{
$this->assertEquals(1, $this->model->getCurrencyRate());
$currencyRate = 42;
$this->model->setCurrencyRate($currencyRate);
$this->assertEquals($currencyRate, $this->model->getCurrencyRate());
}
/**
* @magentoDataFixture Magento/Catalog/_files/categories_no_products.php
*/
#[
DbIsolation(false),
Config('catalog/layered_navigation/price_range_calculation', 'manual', 'store'),
Config('catalog/layered_navigation/price_range_step', '10', 'store'),
Config('catalog/layered_navigation/price_range_max_intervals', '2', 'store'),
DataFixture(ProductFixture::class, ['category_ids' => [4], 'price' => 11]),
DataFixture(ProductFixture::class, ['category_ids' => [4], 'price' => 13]),
DataFixture(ProductFixture::class, ['category_ids' => [4], 'price' => 22]),
DataFixture(ProductFixture::class, ['category_ids' => [4], 'price' => 22]),
DataFixture(ProductFixture::class, ['category_ids' => [4], 'price' => 110]),
]
public function testGetItemsWithManualAlgorithm(): void
{
$attributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$priceAttribute = $attributeRepository->get('price');
$this->model->setAttributeModel($priceAttribute);
/** @var \Magento\Catalog\Model\Layer\Filter\Item[] $ranges */
$ranges = $this->model->getItems();
self::assertCount(2, $ranges);
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
foreach ($ranges as $range) {
$request->setParam('price', $range->getValueString());
$this->initializePriceFilter();
$this->model->apply($request);
$products = $this->model->getLayer()->getProductCollection()->getItems();
self::assertCount($range->getCount(), $products);
}
}
/**
* @return void
*/
private function initializePriceFilter(): void
{
$categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$category = $categoryRepository->get(4);
$layer = $this->objectManager->create(CategoryLayer::class);
$layer->setCurrentCategory($category);
$this->model = $this->objectManager->create(
PriceFilter::class,
['layer' => $layer]
);
}
}
@@ -0,0 +1,55 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\ResourceModel\Advanced;
use Magento\CatalogSearch\Model\Indexer\Fulltext;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection.
* @magentoDbIsolation disabled
*/
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection
*/
private $advancedCollection;
protected function setUp(): void
{
$advanced = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\CatalogSearch\Model\Search\ItemCollectionProvider::class);
$this->advancedCollection = $advanced->getCollection();
$indexerRegistry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(IndexerRegistry::class);
$indexerRegistry->get(Fulltext::INDEXER_ID)->reindexAll();
}
/**
* @dataProvider filtersDataProvider
* @magentoDataFixture Magento/Framework/Search/_files/products.php
*/
public function testLoadWithFilterNoFilters($filters, $expectedCount)
{
// addFieldsToFilter will load filters,
// then loadWithFilter will trigger _renderFiltersBefore code in Advanced/Collection
$this->advancedCollection->addFieldsToFilter([$filters])->loadWithFilter();
$items = $this->advancedCollection->getItems();
$this->assertCount($expectedCount, $items);
}
public function filtersDataProvider()
{
return [
[['name' => ['like' => 'shorts'], 'description' => ['like' => 'green']], 1],
[['name' => 'white', 'description' => ' '], 1],
[['name' => ' ', 'description' => 'green'], 2],
[['name' => ' ', 'description' => ' '], 0],
];
}
}
@@ -0,0 +1,304 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\ResourceModel\Fulltext;
/**
* Test class for \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection.
* @magentoDbIsolation disabled
*/
class CollectionTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
$this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed");
}
/**
* @dataProvider filtersDataProviderSearch
* @magentoDataFixture Magento/Framework/Search/_files/products.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoAppIsolation enabled
*/
public function testLoadWithFilterSearch($request, $filters, $expectedCount)
{
$objManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $fulltextCollection */
$fulltextCollection = $objManager->create(
\Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class,
['searchRequestName' => $request]
);
foreach ($filters as $field => $value) {
$fulltextCollection->addFieldToFilter($field, $value);
}
if ($request == 'quick_search_container' && isset($filters['search_term'])) {
$fulltextCollection->addSearchFilter($filters['search_term']);
}
$fulltextCollection->loadWithFilter();
$items = $fulltextCollection->getItems();
$this->assertCount($expectedCount, $items);
}
/**
* @dataProvider filtersDataProviderQuickSearch
* @magentoDataFixture Magento/Framework/Search/_files/products.php
* @magentoAppIsolation enabled
*/
public function testLoadWithFilterQuickSearch($filters, $expectedCount)
{
$objManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$searchLayer = $objManager->create(\Magento\Catalog\Model\Layer\Search::class);
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $fulltextCollection */
$fulltextCollection = $searchLayer->getProductCollection();
foreach ($filters as $field => $value) {
$fulltextCollection->addFieldToFilter($field, $value);
}
if (isset($filters['search_term'])) {
$fulltextCollection->addSearchFilter($filters['search_term']);
}
$fulltextCollection->loadWithFilter();
$items = $fulltextCollection->getItems();
$this->assertCount($expectedCount, $items);
}
/**
* @dataProvider filtersDataProviderCatalogView
* @magentoDataFixture Magento/Framework/Search/_files/products.php
* @magentoAppIsolation enabled
*/
public function testLoadWithFilterCatalogView($filters, $expectedCount)
{
$objManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$searchLayer = $objManager->create(\Magento\Catalog\Model\Layer\Category::class);
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $fulltextCollection */
$fulltextCollection = $searchLayer->getProductCollection();
foreach ($filters as $field => $value) {
$fulltextCollection->addFieldToFilter($field, $value);
}
$fulltextCollection->loadWithFilter();
$items = $fulltextCollection->getItems();
$this->assertCount($expectedCount, $items);
}
/**
* @magentoDataFixture Magento/Framework/Search/_files/products_with_the_same_search_score.php
* @magentoAppIsolation enabled
*/
public function testSearchResultsAreTheSameForSameRequests()
{
$howManySearchRequests = 3;
$previousResult = null;
$objManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
foreach (range(1, $howManySearchRequests) as $i) {
$searchLayer = $objManager->create(\Magento\Catalog\Model\Layer\Search::class);
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $fulltextCollection */
$fulltextCollection = $searchLayer->getProductCollection();
$fulltextCollection->addSearchFilter('shorts');
$fulltextCollection->setOrder('relevance');
$fulltextCollection->load();
$items = $fulltextCollection->getItems();
$this->assertGreaterThan(
0,
count($items),
sprintf("Search #%s result must not be empty", $i)
);
if ($previousResult) {
$this->assertEquals(
$previousResult,
array_keys($items),
"Search result must be the same for the same requests"
);
}
$previousResult = array_keys($items);
}
}
public function filtersDataProviderSearch()
{
return [
['quick_search_container', ['search_term' => ' shorts'], 2],
['quick_search_container', ['search_term' => ' '], 0],
['catalog_view_container', ['category_ids' => 2], 5],
['catalog_view_container', ['category_ids' => 100001], 0],
['catalog_view_container', ['category_ids' => []], 0],
['catalog_view_container', [], 0],
];
}
public function filtersDataProviderQuickSearch()
{
return [
[['search_term' => ' shorts'], 2],
[['search_term' => 'nonexistent'], 0],
];
}
public function filtersDataProviderCatalogView()
{
return [
[['category_ids' => 2], 5],
[['category_ids' => 100001], 0],
[['category_ids' => []], 5],
[[], 5],
];
}
/**
* Test configurable product with multiple options
*
* @magentoDataFixture Magento/CatalogSearch/_files/product_configurable_two_options.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoAppIsolation enabled
* @dataProvider configurableProductWithMultipleOptionsDataProvider
* @param array $filters
* @param bool $found
* @param array $outOfStock
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function testConfigurableProductWithMultipleOptions(array $filters, bool $found, array $outOfStock = [])
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/**@var $stockRegistry \Magento\CatalogInventory\Model\StockRegistry */
$stockRegistry = $objectManager->get(\Magento\CatalogInventory\Model\StockRegistry::class);
/**@var $stockItemRepository \Magento\CatalogInventory\Api\StockItemRepositoryInterface */
$stockItemRepository = $objectManager->get(\Magento\CatalogInventory\Api\StockItemRepositoryInterface::class);
$collection = $objectManager->create(
\Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class,
['searchRequestName' => 'filter_by_configurable_product_options']
);
foreach ($outOfStock as $sku) {
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty(0);
$stockItem->setIsInStock(0);
$stockItemRepository->save($stockItem);
}
$options = ['test_configurable', 'test_configurable_2'];
foreach ($options as $option) {
if (isset($filters[$option])) {
$filters[$option] = $this->getOptionValue($option, $filters[$option]);
}
}
$filters['category_ids'] = 2;
foreach ($filters as $field => $value) {
$collection->addFieldToFilter($field, $value);
}
$collection->load();
$items = $collection->getItems();
if ($found) {
$this->assertCount(1, $items);
$item = array_shift($items);
$this->assertEquals('configurable_with_2_opts', $item['sku']);
}
$this->assertCount(0, $items);
}
/**
* Provide filters to test configurable product with multiple options
*
* @return array
*/
public function configurableProductWithMultipleOptionsDataProvider(): array
{
return [
[
[],
true
],
[
['test_configurable' => 'Option 1'],
true
],
[
['test_configurable' => 'Option 2'],
true
],
[
['test_configurable_2' => 'Option 1'],
true
],
[
['test_configurable_2' => 'Option 2'],
true
],
[
['test_configurable' => 'Option 1', 'test_configurable_2' => 'Option 1'],
true
],
[
['test_configurable' => 'Option 1', 'test_configurable_2' => 'Option 2'],
true
],
[
['test_configurable' => 'Option 2', 'test_configurable_2' => 'Option 1'],
true
],
[
['test_configurable' => 'Option 2', 'test_configurable_2' => 'Option 2'],
true
],
[
['test_configurable' => 'Option 2', 'test_configurable_2' => 'Option 2'],
false,
[
'configurable2_option_12',
'configurable2_option_22',
]
],
[
['test_configurable' => 'Option 2', 'test_configurable_2' => 'Option 2'],
false,
[
'configurable2_option_21',
'configurable2_option_22',
]
],
[
['test_configurable' => 'Option 2'],
false,
[
'configurable2_option_21',
'configurable2_option_22',
]
],
[
[],
false,
[
'configurable2_option_11',
'configurable2_option_12',
'configurable2_option_21',
'configurable2_option_22',
]
],
];
}
/**
* Get attribute option value by label
*
* @param string $attributeName
* @param string $optionLabel
* @return string|null
*/
private function getOptionValue(string $attributeName, string $optionLabel): ?string
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$eavConfig = $objectManager->get(\Magento\Eav\Model\Config::class);
$attribute = $eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeName);
$option = null;
foreach ($attribute->getOptions() as $option) {
if ($option->getLabel() === $optionLabel) {
return $option->getValue();
}
}
return null;
}
}
@@ -0,0 +1,186 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Model\Search;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\TestFramework\Catalog\Model\Layer\QuickSearchByQuery;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Test founded products order after quick search with changed attribute search weight using mysql search engine.
*
* @magentoAppIsolation enabled
*/
class AttributeSearchWeightTest extends TestCase
{
/**
* @var $objectManager ObjectManager
*/
private $objectManager;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var array
*/
private $collectedAttributesWeight = [];
/**
* @var QuickSearchByQuery
*/
private $quickSearchByQuery;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->quickSearchByQuery = $this->objectManager->get(QuickSearchByQuery::class);
$this->collectCurrentProductAttributesWeights();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->updateAttributesWeight($this->collectedAttributesWeight);
}
/**
* Perform search by word and check founded product order in different cases.
*
* @magentoDataFixture Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @dataProvider attributeSearchWeightDataProvider
* @magentoDbIsolation disabled
*
* @param string $searchQuery
* @param array $attributeWeights
* @param array $expectedProductNames
* @return void
*/
public function testAttributeSearchWeight(
string $searchQuery,
array $attributeWeights,
array $expectedProductNames
): void {
$this->markTestSkipped(
'MC-33824: Stabilize skipped test cases for Integration AttributeSearchWeightTest with Elasticsearch'
);
$this->updateAttributesWeight($attributeWeights);
$actualProductNames = $this->quickSearchByQuery->execute($searchQuery)->getColumnValues('name');
$this->assertEquals($expectedProductNames, $actualProductNames, 'Products order is not as expected.');
}
/**
* Data provider with word for quick search, attributes weight and expected products name order.
*
* @return array
*/
public function attributeSearchWeightDataProvider(): array
{
return [
'name_order_more_than_sku' => [
'Nintendo Wii',
[
'sku' => 5,
'name' => 6,
],
[
'Nintendo Wii',
'Xbox',
],
],
'search_by_word_from_description' => [
'Xbox',
[
'name' => 10,
'test_searchable_attribute' => 9,
'sku' => 2,
'description' => 1,
],
[
'Nintendo Wii',
'Xbox',
'Console description',
'Gamecube attribute',
],
],
'search_by_attribute_option' => [
'Xbox',
[
'name' => 10,
'description' => 9,
'test_searchable_attribute' => 7,
'sku' => 2,
],
[
'Nintendo Wii',
'Xbox',
'Console description',
'Gamecube attribute',
],
],
'sku_order_more_than_name' => [
'Nintendo Wii',
[
'sku' => 6,
'name' => 5,
],
[
'Xbox',
'Nintendo Wii',
]
],
];
}
/**
* Update attributes weight.
*
* @param array $attributeWeights
* @return void
*/
protected function updateAttributesWeight(array $attributeWeights): void
{
foreach ($attributeWeights as $attributeCode => $weight) {
$attribute = $this->productAttributeRepository->get($attributeCode);
$attribute->setSearchWeight($weight);
$this->productAttributeRepository->save($attribute);
}
}
/**
* Collect weight of attributes which use in test.
*
* @return void
*/
private function collectCurrentProductAttributesWeights(): void
{
if (empty($this->collectedAttributesWeight)) {
$attributeCodes = [
'sku',
'name',
'description',
'test_searchable_attribute'
];
foreach ($attributeCodes as $attributeCode) {
$attribute = $this->productAttributeRepository->get($attributeCode);
$this->collectedAttributesWeight[$attribute->getAttributeCode()] = $attribute->getSearchWeight();
}
}
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Model\Search;
/**
* Test class for \Magento\CatalogSearch\Model\Search\RequestGenerator.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/CatalogSearch/_files/search_attributes.php
*/
class RequestGeneratorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\CatalogSearch\Model\Search\RequestGenerator
*/
protected $model;
protected function setUp(): void
{
$this->model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\CatalogSearch\Model\Search\RequestGenerator::class);
}
public function testGenerate()
{
$requests = $this->model->generate();
//Quick Search
$this->assertArrayHasKey('quick_search_container', $requests);
$quickSearch = $requests['quick_search_container'];
$message = 'Unexpected attribute';
$this->assertArrayHasKey('test_quick_search_bucket', $quickSearch['aggregations'], $message);
$this->assertArrayNotHasKey('test_catalog_view_bucket', $quickSearch['aggregations'], $message);
//Catalog View
$this->assertArrayHasKey('catalog_view_container', $requests);
$catalogView = $requests['catalog_view_container'];
$this->assertArrayNotHasKey('test_quick_search_bucket', $catalogView['aggregations'], $message);
$this->assertArrayHasKey('test_catalog_view_bucket', $catalogView['aggregations'], $message);
}
}