This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Block\Advanced;
class ResultTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\View\LayoutInterface
*/
protected $_layout;
/**
* @var \Magento\CatalogSearch\Block\Advanced\Result
*/
protected $_block;
protected function setUp(): void
{
$this->_layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\LayoutInterface::class
);
$this->_block = $this->_layout->createBlock(\Magento\CatalogSearch\Block\Advanced\Result::class, 'block');
}
/**
* @magentoAppIsolation enabled
*/
public function testSetListOrders()
{
$sortOptions = [
'option1' => 'Label Option 1',
'position' => 'Label Position',
'option3' => 'Label Option 2',
];
/** @var \Magento\Catalog\Model\Category $category */
$category = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['getAvailableSortByOptions']);
$category->expects($this->atLeastOnce())
->method('getAvailableSortByOptions')
->willReturn($sortOptions);
$category->setId(100500); // Any id - just for layer navigation
/** @var \Magento\Catalog\Model\Layer\Resolver $resolver */
$resolver = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Model\Layer\Resolver::class);
$resolver->get()->setCurrentCategory($category);
$childBlock = $this->_layout->addBlock(
\Magento\Framework\View\Element\Text::class,
'search_result_list',
'block'
);
$expectedOptions = ['option1' => 'Label Option 1', 'option3' => 'Label Option 2'];
$this->assertNotEquals($expectedOptions, $childBlock->getAvailableOrders());
$this->_block->setListOrders();
$this->assertEquals($expectedOptions, $childBlock->getAvailableOrders());
}
/**
* @magentoAppIsolation enabled
*/
public function testSetListModes()
{
/** @var $childBlock \Magento\Framework\View\Element\Text */
$childBlock = $this->_layout->addBlock(
\Magento\Framework\View\Element\Text::class,
'search_result_list',
'block'
);
$this->assertEmpty($childBlock->getModes());
$this->_block->setListModes();
$this->assertNotEmpty($childBlock->getModes());
}
public function testSetListCollection()
{
/** @var $childBlock \Magento\Framework\View\Element\Text */
$childBlock = $this->_layout->addBlock(
\Magento\Framework\View\Element\Text::class,
'search_result_list',
'block'
);
$this->assertEmpty($childBlock->getCollection());
$this->_block->setListCollection();
$this->assertInstanceOf(
\Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection::class,
$childBlock->getCollection()
);
}
}
@@ -0,0 +1,120 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Block;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\Search\Model\QueryFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Search\ViewModel\ConfigProvider;
class ResultTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->configProvider = $this->objectManager->get(ConfigProvider::class);
}
/**
* Set list orders test
*
* @return void
*/
public function testSetListOrders(): void
{
$this->layout->addBlock(Text::class, 'head');
// The tested block is using head block
/** @var $block Result */
$block = $this->layout->addBlock(Result::class, 'block');
$childBlock = $this->layout->addBlock(Text::class, 'search_result_list', 'block');
$this->assertSame($childBlock, $block->getListBlock());
}
/**
* Verify search value escaping process
*
* @dataProvider toEscapeSearchTextDataProvider
* @magentoAppArea frontend
* @param string $searchValue
* @param string $expectedOutput
* @param string $unexpectedOutput
* @return void
*/
public function testEscapeSearchText(string $searchValue, string $expectedOutput, string $unexpectedOutput): void
{
/** @var Result $searchResultBlock */
$searchResultBlock = $this->layout->createBlock(Result::class);
/** @var Template $searchBlock */
$searchQueryParams = $this->getMockBuilder(\Magento\Search\ViewModel\AdditionalSearchFormData::class)
->disableOriginalConstructor()
->setMethods(['getFormData'])
->getMock();
$searchQueryParams->expects($this->any())
->method('getFormData')
->willReturn([]);
$searchBlock = $this->layout->createBlock(Template::class);
$searchBlock->setData([
'configProvider' => $this->configProvider,
'additionalSearchFormData' => $searchQueryParams,
]);
$searchBlock->setTemplate('Magento_Search::form.mini.phtml');
/** @var RequestInterface $request */
$request = $this->objectManager->get(RequestInterface::class);
$request->setParam(QueryFactory::QUERY_VAR_NAME, $searchValue);
$searchHtml = $searchBlock->toHtml();
$this->assertStringContainsString('value=' . '"' . $expectedOutput . '"', $searchHtml);
$this->assertStringNotContainsString($unexpectedOutput, $searchHtml);
$resultTitle = $searchResultBlock->getSearchQueryText()->render();
$this->assertStringContainsString("Search results for: '{$expectedOutput}'", $resultTitle);
$this->assertStringNotContainsString($unexpectedOutput, $resultTitle);
}
/**
* DataProvider for testEscapeSearchText()
*
* @return array
*/
public function toEscapeSearchTextDataProvider(): array
{
return [
'less_than_sign_escaped' => ['<', '&lt;', '&amp;lt&#x3B;'],
'greater_than_sign_escaped' => ['>', '&gt;', '&amp;gt&#x3B;'],
'ampersand_sign_escaped' => ['&', '&amp;', '&amp;amp&#x3B;'],
'double_quote_sign_escaped' => ['"', '&quot;', '&amp;quot&#x3B;'],
'single_quote_sign_escaped' => ["'", '&#039;', '&amp;&#x23;039&#x3B;'],
'plus_sign_not_escaped' => ['+', '+', '&amp;+&#x3B;'],
'characters_not_escaped' => ['abc', 'abc', '&amp;abc&#x3B;'],
'numbers_not_escaped' => ['123', '123', '&amp;123&#x3B;'],
];
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Block;
class TermTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Search\Block\Term
*/
protected $_block;
protected function setUp(): void
{
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Search\Block\Term::class
);
}
public function testGetSearchUrl()
{
$query = uniqid();
$obj = new \Magento\Framework\DataObject(['query_text' => $query]);
$this->assertStringEndsWith("/catalogsearch/result/?q={$query}", $this->_block->getSearchUrl($obj));
}
}
@@ -0,0 +1,115 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Controller\Advanced;
use Magento\TestFramework\TestCase\AbstractController;
use Laminas\Stdlib\Parameters;
/**
* Test cases for catalog advanced index using params.
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
class IndexTest extends AbstractController
{
/**
* Advanced index test by params with the array in params.
*
* @magentoAppArea frontend
* @dataProvider fromParamsInArrayDataProvider
*
* @param array $searchParams
* @return void
*/
public function testExecuteWithArrayInParams(array $searchParams): void
{
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => $searchParams
]
)
);
$this->dispatch('catalogsearch/advanced/index');
$this->assertEquals(200, $this->getResponse()->getStatusCode());
$this->getResponse()->getBody();
}
/**
* Data provider with array in param values.
*
* @return array
*/
public function fromParamsInArrayDataProvider(): array
{
return [
'from_data_with_from_param_is_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => [],
'to' => 1,
]
]
],
'from_data_with_to_param_is_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 0,
'to' => [],
]
]
],
'from_data_with_params_in_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => ['0' => 1],
'to' => [1],
]
]
],
'from_data_with_params_in_array_in_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => ['0' => ['0' => 1]],
'to' => 1,
]
]
],
'from_data_with_name_param_is_array' => [
[
'name' => [],
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 0,
'to' => 20,
]
]
]
];
}
}
@@ -0,0 +1,445 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Controller\Advanced;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\TestFramework\TestCase\AbstractController;
use Laminas\Stdlib\Parameters;
/**
* Test cases for catalog advanced search using search engine.
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
class ResultTest extends AbstractController
{
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productAttributeRepository = $this->_objectManager->create(ProductAttributeRepositoryInterface::class);
}
/**
* Advanced search test by difference product attributes.
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @dataProvider searchStringDataProvider
*
* @param array $searchParams
* @return void
*/
public function testExecute(array $searchParams): void
{
if ('' !== $searchParams['test_searchable_attribute']) {
$searchParams['test_searchable_attribute'] = $this->getAttributeOptionValueByOptionLabel(
'test_searchable_attribute',
$searchParams['test_searchable_attribute']
);
}
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => $searchParams
]
)
);
$this->dispatch('catalogsearch/advanced/result');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Simple product name', $responseBody);
$this->assertStringNotContainsString('Not visible simple product', $responseBody);
}
/**
* Advanced search test by difference product attributes.
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search_with_hyphen_in_sku.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*
* @return void
*/
public function testExecuteSkuWithHyphen(): void
{
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => [
'name' => '',
'sku' => '24-mb01',
'description' => '',
'short_description' => '',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => '',
]
]
)
);
$this->dispatch('catalogsearch/advanced/result');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Simple product name', $responseBody);
}
/**
* Advanced search with an underscore in product attributes.
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search_with_underscore.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*
* @return void
*/
public function testExecuteWithUnderscore(): void
{
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => [
'name' => 'name',
'sku' => 'sku',
'description' => 'description',
'short_description' => 'short',
'price' => [
'from' => '',
'to' => '',
],
],
]
)
);
$this->dispatch('catalogsearch/advanced/result');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('name_simple_product', $responseBody);
}
/**
* Advanced search with array in price parameters
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @dataProvider searchParamsInArrayDataProvider
*
* @param array $searchParams
* @return void
*/
public function testExecuteWithArrayInParam(array $searchParams): void
{
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => $searchParams
]
)
);
$this->dispatch('catalogsearch/advanced/result');
$this->assertEquals(200, $this->getResponse()->getStatusCode());
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString(
'We can&#039;t find any items matching these search criteria.',
$responseBody
);
}
/**
* Advanced search test by difference product attributes.
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @dataProvider testDataForAttributesCombination
*
* @param array $searchParams
* @param bool $isProductShown
* @return void
*/
public function testExecuteForAttributesCombination(array $searchParams, bool $isProductShown): void
{
$this->getRequest()->setQuery(
$this->_objectManager->create(
Parameters::class,
[
'values' => $searchParams
]
)
);
$this->dispatch('catalogsearch/advanced/result');
$responseBody = $this->getResponse()->getBody();
if ($isProductShown) {
$this->assertStringContainsString('Simple product name', $responseBody);
} else {
$this->assertStringContainsString(
'We can&#039;t find any items matching these search criteria.',
$responseBody
);
}
$this->assertStringNotContainsString('Not visible simple product', $responseBody);
}
/**
* Data provider with array in params values
*
* @return array
*/
public function searchParamsInArrayDataProvider(): array
{
return [
'search_with_from_param_is_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => [],
'to' => 1,
]
]
],
'search_with_to_param_is_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 0,
'to' => [],
]
]
],
'search_with_params_in_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => ['0' => 1],
'to' => [1],
]
]
],
'search_with_params_in_array_in_array' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => ['0' => ['0' => 1]],
'to' => 1,
]
]
],
'search_with_name_param_is_array' => [
[
'name' => [],
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 0,
'to' => 20,
]
]
]
];
}
/**
* Data provider with strings for quick search.
*
* @return array
*/
public function searchStringDataProvider(): array
{
return [
'search_product_by_name' => [
[
'name' => 'Simple product name',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => '',
],
],
'search_product_by_sku' => [
[
'name' => '',
'sku' => 'simple_for_search',
'description' => '',
'short_description' => '',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => '',
],
],
'search_product_by_description' => [
[
'name' => '',
'sku' => '',
'description' => 'Product description',
'short_description' => '',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => '',
],
],
'search_product_by_short_description' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => 'Product short description',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => '',
],
],
'search_product_by_price_range' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 50,
'to' => 150,
],
'test_searchable_attribute' => '',
],
],
'search_product_by_custom_attribute' => [
[
'name' => '',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => '',
'to' => '',
],
'test_searchable_attribute' => 'Option 1',
],
],
];
}
/**
* Return attribute option value by option label.
*
* @param string $attributeCode
* @param string $optionLabel
* @return null|string
*/
private function getAttributeOptionValueByOptionLabel(string $attributeCode, string $optionLabel): ?string
{
/** @var Attribute $attribute */
$attribute = $this->productAttributeRepository->get($attributeCode);
return $attribute->getSource()->getOptionId($optionLabel);
}
/**
* Data provider with strings for quick search.
*
* @return array
*/
public function testDataForAttributesCombination(): array
{
return [
'search_product_by_name_and_price' => [
[
'name' => 'Simple product name',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 99,
'to' => 101,
],
'test_searchable_attribute' => '',
],
true
],
'search_product_by_name_and_price_not_shown' => [
[
'name' => 'Simple product name',
'sku' => '',
'description' => '',
'short_description' => '',
'price' => [
'from' => 101,
'to' => 102,
],
'test_searchable_attribute' => '',
],
false
],
'search_product_by_sku' => [
[
'name' => '',
'sku' => 'simple_for_search',
'description' => '',
'short_description' => '',
'price' => [
'from' => 99,
'to' => 101,
],
'test_searchable_attribute' => '',
],
true
],
'search_product_by_sku_not_shown' => [
[
'name' => '',
'sku' => 'simple_for_search',
'description' => '',
'short_description' => '',
'price' => [
'from' => 990,
'to' => 1010,
],
'test_searchable_attribute' => '',
],
false
],
];
}
}
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Controller;
class AjaxTest extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testSuggestAction()
{
$this->getRequest()->setParam('q', 'query_text');
$this->dispatch('catalogsearch/ajax/suggest');
$this->assertStringContainsString('query_text', $this->getResponse()->getBody());
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogSearch\Controller\Result;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test cases for catalog quick search using search engine.
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
class IndexTest extends AbstractController
{
/**
* Quick search test by difference product attributes.
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @dataProvider searchStringDataProvider
*
* @param string $searchString
* @return void
*/
public function testExecute(string $searchString): void
{
$this->getRequest()->setParam('q', $searchString);
$this->dispatch('catalogsearch/result');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Simple product name', $responseBody);
}
/**
* Data provider with strings for quick search.
*
* @return array
*/
public function searchStringDataProvider(): array
{
return [
'search_product_by_name' => ['Simple product name'],
'search_product_by_sku' => ['simple_for_search'],
'search_product_by_description' => ['Product description'],
'search_product_by_short_description' => ['Product short description'],
'search_product_by_custom_attribute' => ['Option 1'],
];
}
}
@@ -0,0 +1,186 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Controller;
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*/
class ResultTest extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testIndexActionTranslation()
{
$this->markTestSkipped('MAGETWO-44910');
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\Locale\ResolverInterface::class)->setLocale('de_DE');
$this->getRequest()->setParam('q', 'query_text');
$this->dispatch('catalogsearch/result');
$responseBody = $this->getResponse()->getBody();
$this->assertStringNotContainsString('for="search">Search', $responseBody);
$this->assertStringMatchesFormat('%aSuche%S%a', $responseBody);
$this->assertStringNotContainsString('Search entire store here...', $responseBody);
$this->assertStringContainsString('Den gesamten Shop durchsuchen...', $responseBody);
}
/**
* @magentoDbIsolation disabled
*/
public function testIndexActionXSSQueryVerification()
{
$escaper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Escaper::class);
$this->getRequest()->setParam('q', '<script>alert(1)</script>');
$this->dispatch('catalogsearch/result');
$responseBody = $this->getResponse()->getBody();
$data = '<script>alert(1)</script>';
$this->assertStringNotContainsString($data, $responseBody);
$this->assertStringContainsString($escaper->escapeHtml($data), $responseBody);
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/query_redirect.php
*/
public function testRedirect()
{
$this->dispatch('/catalogsearch/result/?q=query_text');
$responseBody = $this->getResponse();
$this->assertTrue($responseBody->isRedirect());
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/query_redirect.php
*/
public function testNoRedirectIfCurrentUrlAndRedirectTermAreSame()
{
$this->dispatch('/catalogsearch/result/?q=query_text&cat=41');
$responseBody = $this->getResponse();
$this->assertFalse($responseBody->isRedirect());
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testPopularity()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->loadByQueryText('query_text');
$this->assertEquals(1, $query->getPopularity());
$this->dispatch('catalogsearch/searchTermsLog/save?q=query_text');
$responseBody = $this->getResponse()->getBody();
$data = '"success":true';
$this->assertStringContainsString($data, $responseBody);
$query->loadByQueryText('query_text');
$this->assertEquals(2, $query->getPopularity());
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/popular_query.php
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testPopularSearch()
{
$this->cacheAndPopularitySetup();
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->loadByQueryText('popular_query_text');
$this->assertEquals(100, $query->getPopularity());
$this->dispatch('/catalogsearch/result/?q=popular_query_text');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Search results for: &#039;popular_query_text&#039;', $responseBody);
$this->assertStringContainsString('/catalogsearch/searchTermsLog/save/', $responseBody);
$query->loadByQueryText('popular_query_text');
$this->assertEquals(100, $query->getPopularity());
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/popular_query.php
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testPopularSearchWithAdditionalRequestParameters()
{
$this->cacheAndPopularitySetup();
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->loadByQueryText('popular_query_text');
$this->assertEquals(100, $query->getPopularity());
$this->dispatch('/catalogsearch/result/?q=popular_query_text&additional_parameters=some');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Search results for: &#039;popular_query_text&#039;', $responseBody);
$this->assertStringNotContainsString('/catalogsearch/searchTermsLog/save/', $responseBody);
$query->loadByQueryText('popular_query_text');
$this->assertEquals(101, $query->getPopularity());
}
/**
* @magentoDataFixture Magento/CatalogSearch/_files/popular_query.php
* @magentoDataFixture Magento/CatalogSearch/_files/query.php
*/
public function testNotPopularSearch()
{
$this->cacheAndPopularitySetup();
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->loadByQueryText('query_text');
$this->assertEquals(1, $query->getPopularity());
$this->dispatch('/catalogsearch/result/?q=query_text');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Search results for: &#039;query_text&#039;', $responseBody);
$this->assertStringNotContainsString('/catalogsearch/searchTermsLog/save/', $responseBody);
$query->loadByQueryText('query_text');
$this->assertEquals(2, $query->getPopularity());
}
private function cacheAndPopularitySetup()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $scopeConfig \Magento\Framework\App\MutableScopeConfig */
$scopeConfig = $objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
\Magento\Search\Model\PopularSearchTerms::XML_PATH_MAX_COUNT_CACHEABLE_SEARCH_TERMS,
1,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
/** @var $cacheState \Magento\Framework\App\Cache\StateInterface */
$cacheState = $objectManager->get(\Magento\Framework\App\Cache\StateInterface::class);
$cacheState->setEnabled(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER, true);
/** @var $fpc \Magento\PageCache\Model\Cache\Type */
$fpc = $objectManager->get(\Magento\PageCache\Model\Cache\Type::class);
$fpc->clean();
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Helper;
class DataTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\CatalogSearch\Helper\Data
*/
protected $_helper;
protected function setUp(): void
{
/** @var \Magento\TestFramework\ObjectManager $objectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\App\Request\Http $request */
$request = $objectManager->get(\Magento\Framework\App\RequestInterface::class);
$request->setParam('q', 'five <words> here <being> tested');
$this->_helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\CatalogSearch\Helper\Data::class
);
}
public function testGetResultUrl()
{
$this->assertStringEndsWith('/catalogsearch/result/', $this->_helper->getResultUrl());
$query = uniqid();
$this->assertStringEndsWith("/catalogsearch/result/?q={$query}", $this->_helper->getResultUrl($query));
}
public function testGetAdvancedSearchUrl()
{
$this->assertStringEndsWith('/catalogsearch/advanced/', $this->_helper->getAdvancedSearchUrl());
}
public function testCheckNotesResult()
{
$this->assertInstanceOf(\Magento\CatalogSearch\Helper\Data::class, $this->_helper->checkNotes());
}
}
@@ -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);
}
}
@@ -0,0 +1,10 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Indexer\Model\Indexer::class
);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $category \Magento\Catalog\Model\Category */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $productFirst \Magento\Catalog\Model\Product */
$productFirst = $objectManager->create(\Magento\Catalog\Model\Product::class);
$productFirst->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Apple')
->setSku('fulltext-1')
->setUrlKey('fulltext-1')
->setPrice(10)
->setMetaTitle('first meta title')
->setMetaKeyword('first meta keyword')
->setMetaDescription('first meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
/** @var $productFirst \Magento\Catalog\Model\Product */
$productSecond = $objectManager->create(\Magento\Catalog\Model\Product::class);
$productSecond->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Banana')
->setSku('fulltext-2')
->setUrlKey('fulltext-2')
->setPrice(20)
->setMetaTitle('second meta title')
->setMetaKeyword('second meta keyword')
->setMetaDescription('second meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
/** @var $productFirst \Magento\Catalog\Model\Product */
$productThird = $objectManager->create(\Magento\Catalog\Model\Product::class);
$productThird->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Orange')
->setSku('fulltext-3')
->setUrlKey('fulltext-3')
->setPrice(20)
->setMetaTitle('third meta title')
->setMetaKeyword('third meta keyword')
->setMetaDescription('third meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
/** @var $productFirst \Magento\Catalog\Model\Product */
$productFourth = $objectManager->create(\Magento\Catalog\Model\Product::class);
$productFourth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Papaya')
->setSku('fulltext-4')
->setUrlKey('fulltext-4')
->setPrice(20)
->setMetaTitle('fourth meta title')
->setMetaKeyword('fourth meta keyword')
->setMetaDescription('fourth meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
/** @var $productFirst \Magento\Catalog\Model\Product */
$productFifth = $objectManager->create(\Magento\Catalog\Model\Product::class);
$productFifth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Cherry')
->setSku('fulltext-5')
->setUrlKey('fulltext-5')
->setPrice(20)
->setMetaTitle('fifth meta title')
->setMetaKeyword('fifth meta keyword')
->setMetaDescription('fifth meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Framework\Registry $registry */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$collection->addAttributeToSelect('id')->load()->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->setStoreId(1);
$query->setQueryText(
'popular_query_text'
)->setNumResults(
1
)->setPopularity(
100
)->setDisplayInTerms(
1
)->setIsActive(
1
)->setIsProcessed(
1
)->save();
@@ -0,0 +1,110 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Setup\CategorySetup;
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Eav\Model\Config;
Bootstrap::getInstance()->reinitialize();
Resolver::getInstance()->requireDataFixture(
'Magento/Framework/Search/_files/configurable_attribute.php'
);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()
->create(ProductRepositoryInterface::class);
/** @var $installer CategorySetup */
$installer = Bootstrap::getObjectManager()->create(CategorySetup::class);
$eavConfig = Bootstrap::getObjectManager()->get(Config::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable');
/* Create simple products per each option value*/
/** @var AttributeOptionInterface[] $options */
$options = $attribute->getOptions();
$attributeValues = [];
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
$associatedProductIds = [];
$productsSku = [1110, 1120];
array_shift($options); //remove the first option which is empty
$isFirstOption = true;
foreach ($options as $option) {
/** @var $product Product */
$product = Bootstrap::getObjectManager()->create(Product::class);
$productSku = array_shift($productsSku);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($attributeSetId)
->setName('Configurable Option' . $option->getLabel())
->setSku('simple_not_avalilable_' . $productSku)
->setPrice(11)
->setTestConfigurable($option->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_DISABLED);
$product = $productRepository->save($product);
/** @var StockItemInterface $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem->setUseConfigManageStock(1)->setIsInStock(true)->setQty(100)->setIsQtyDecimal(0);
$product = $productRepository->save($product);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
$associatedProductIds[] = $product->getId();
$isFirstOption = false;
}
/** @var $product Product */
$product = Bootstrap::getObjectManager()->create(Product::class);
/** @var Factory $optionsFactory */
$optionsFactory = Bootstrap::getObjectManager()->create(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$extensionConfigurableAttributes = $product->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($attributeSetId)
->setName('Configurable Product Disable Child Products')
->setSku('configurable_not_available')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED);
$product = $productRepository->save($product);
/** @var StockItemInterface $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem->setUseConfigManageStock(1)->setIsInStock(1);
$productRepository->save($product);
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSkus = ['simple_not_avalilable_1110', 'simple_not_avalilable_1120', 'configurable_not_available'];
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()->get(SearchCriteriaBuilder::class);
$searchCriteriaBuilder->addFilter(ProductInterface::SKU, $productSkus, 'in');
$result = $productRepository->getList($searchCriteriaBuilder->create());
foreach ($result->getItems() as $product) {
$productRepository->delete($product);
}
Resolver::getInstance()->requireDataFixture('Magento/Framework/Search/_files/configurable_attribute_rollback.php');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,168 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Setup\CategorySetup;
use Magento\CatalogInventory\Model\Stock\Item;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Framework\Search\Request\Config;
use Magento\Framework\Search\Request\Config\Converter;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute.php');
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute_2.php');
$objectManager = Bootstrap::getObjectManager();
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = $objectManager->create(AttributeRepositoryInterface::class);
/** @var \Magento\Eav\Model\Config $eavConfig */
$eavConfig = $objectManager->get(\Magento\Eav\Model\Config::class);
$attributes = ['test_configurable', 'test_configurable_2'];
foreach ($attributes as $attributeName) {
$attributeModel = $eavConfig->getAttribute(Product::ENTITY, $attributeName);
$attributeModel->addData([
'is_searchable' => 1,
'is_filterable' => 1,
'is_filterable_in_search' => 1,
'is_visible_in_advanced_search' => 1,
]);
$attributeRepository->save($attributeModel);
}
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var $installer CategorySetup */
$installer = $objectManager->create(CategorySetup::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable');
$attribute2 = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable_2');
/** @var AttributeOptionInterface[] $options */
$options = $attribute->getOptions();
$attribute1Values = [];
$attribute2Values = [];
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
$associatedProductIds = [];
array_shift($options);
$index1 = 1;
foreach ($options as $option1) {
/** @var AttributeOptionInterface[] $options */
$options2 = $attribute2->getOptions();
array_shift($options2);
$index2 = 1;
foreach ($options2 as $option2) {
/** @var $product Product */
$product = $objectManager->create(Product::class);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('Configurable2 Option' . $index1 . $index2)
->setSku('configurable2_option_' . $index1 . $index2)
->setPrice(random_int(10, 100))
->setTestConfigurable($option1->getValue())
->setTestConfigurable2($option2->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$product = $productRepository->save($product);
/** @var Item $stockItem */
$stockItem = $objectManager->create(Item::class);
$stockItem->load($product->getId(), 'product_id');
if (!$stockItem->getProductId()) {
$stockItem->setProductId($product->getId());
}
$stockItem->setUseConfigManageStock(1);
$stockItem->setQty(1000);
$stockItem->setIsQtyDecimal(0);
$stockItem->setIsInStock(1);
$stockItem->save();
$attribute1Values[] = [
'label' => 'test1',
'attribute_id' => $attribute->getId(),
'value_index' => $option1->getValue(),
];
$attribute2Values[] = [
'label' => 'test2',
'attribute_id' => $attribute2->getId(),
'value_index' => $option2->getValue(),
];
$associatedProductIds[] = $product->getId();
$index2++;
}
$index1++;
}
/** @var $product Product */
$product = $objectManager->create(Product::class);
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->create(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attribute1Values,
],
[
'attribute_id' => $attribute2->getId(),
'code' => $attribute2->getAttributeCode(),
'label' => $attribute2->getStoreLabel(),
'position' => '1',
'values' => $attribute2Values,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$extensionConfigurableAttributes = $product->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('configurable with 2 opts')
->setSku('configurable_with_2_opts')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($product);
/** @var CategoryLinkManagementInterface $categoryLinkManagement */
$categoryLinkManagement = $objectManager->create(CategoryLinkManagementInterface::class);
$categoryLinkManagement->assignProductToCategories(
$product->getSku(),
[2]
);
/** @var Converter $converter */
$converter = $objectManager->create(Converter::class);
$document = new DOMDocument();
$document->load(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'requests.xml');
$requestConfig = $converter->convert($document);
/** @var Config $config */
$config = $objectManager->get(Config::class);
$config->merge($requestConfig);
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogInventory\Model\Stock\Status;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$list = [
'configurable2_option_11',
'configurable2_option_12',
'configurable2_option_21',
'configurable2_option_22',
'configurable_with_2_opts'
];
foreach ($list as $sku) {
try {
$product = $productRepository->get($sku, true);
$stockStatus = $objectManager->create(Status::class);
$stockStatus->load($product->getEntityId(), 'product_id');
$stockStatus->delete();
$productRepository->delete($product);
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute_2_rollback.php');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Setup\CategorySetup;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Eav\Model\Config;
Bootstrap::getInstance()->reinitialize();
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute.php');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
/** @var $installer CategorySetup */
$installer = Bootstrap::getObjectManager()->create(CategorySetup::class);
$eavConfig = Bootstrap::getObjectManager()->get(Config::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable');
/* Create simple products per each option value*/
/** @var AttributeOptionInterface[] $options */
$options = $attribute->getOptions();
$attributeValues = [];
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
array_shift($options); //remove the first option which is empty
$option = reset($options);
/** @var $childProduct Product */
$childProduct = Bootstrap::getObjectManager()->create(Product::class);
$childProduct->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($attributeSetId)
->setName('Configurable Product Option' . $option->getLabel())
->setSku('configurable_option_single_child')
->setPrice(11)
->setTestConfigurable($option->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$childProduct = $productRepository->save($childProduct);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
/** @var $product Product */
$configurableProduct = Bootstrap::getObjectManager()->create(Product::class);
/** @var Factory $optionsFactory */
$optionsFactory = Bootstrap::getObjectManager()->create(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$extensionConfigurableAttributes = $configurableProduct->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks([$childProduct->getId()]);
$configurableProduct->setExtensionAttributes($extensionConfigurableAttributes);
$configurableProduct->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($attributeSetId)
->setName('Configurable Product with single child')
->setSku('configurable_with_single_child')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'is_in_stock' => 1,
]
);
$configurableProduct = $productRepository->save($configurableProduct);
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSkus = ['configurable_option_single_child', 'configurable_with_single_child'];
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()->get(SearchCriteriaBuilder::class);
$searchCriteriaBuilder->addFilter(ProductInterface::SKU, $productSkus, 'in');
$result = $productRepository->getList($searchCriteriaBuilder->create());
foreach ($result->getItems() as $product) {
$productRepository->delete($product);
}
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute_rollback.php');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,85 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Eav\Model\Config;
use Magento\Catalog\Model\Product;
Resolver::getInstance()->requireDataFixture('Magento/CatalogSearch/_files/searchable_attribute.php');
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
$eavConfig = $objectManager->get(Config::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_searchable_attribute');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
$product = $productFactory->create();
$product->isObjectNew(true);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Simple product name')
->setSku('simple_for_search')
->setPrice(100)
->setWeight(1)
->setShortDescription('Product short description')
->setTaxClassId(0)
->setDescription('Product description')
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setTestSearchableAttribute($attribute->getSource()->getOptionId('Option 1'))
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
$product = $productFactory->create();
$product->isObjectNew(true);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Not visible simple product')
->setSku('not_visible_simple')
->setPrice(100)
->setWeight(1)
->setShortDescription('Product short description')
->setTaxClassId(0)
->setDescription('Product description')
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setTestSearchableAttribute($attribute->getSource()->getOptionId('Option 1'))
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var EavSetupFactory $eavSetupFactory */
$eavSetupFactory = $objectManager->create(EavSetupFactory::class);
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
try {
$productRepository->deleteById('simple_for_search');
} catch (NoSuchEntityException $e) {
//Product already deleted.
}
/** @var EavSetup $eavSetup */
$eavSetup = $eavSetupFactory->create();
$eavSetup->removeAttribute(Product::ENTITY, 'test_searchable_attribute');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/CatalogSearch/_files/searchable_attribute.php');
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('test_searchable_attribute');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
$product = $productFactory->create();
$product->isObjectNew(true);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Simple product name')
->setSku('24-mb01')
->setPrice(100)
->setWeight(1)
->setShortDescription('Product short description')
->setTaxClassId(0)
->setDescription('Product description')
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setTestSearchableAttribute($attribute->getSource()->getOptionId('Option 1'))
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var EavSetupFactory $eavSetupFactory */
$eavSetupFactory = $objectManager->create(EavSetupFactory::class);
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
try {
$productRepository->deleteById('24-mb01');
} catch (NoSuchEntityException $e) {
//Product already deleted.
}
/** @var EavSetup $eavSetup */
$eavSetup = $eavSetupFactory->create();
$eavSetup->removeAttribute(Product::ENTITY, 'test_searchable_attribute');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$baseWebsite = $websiteRepository->get('base');
/** @var ProductInterfaceFactory $productFactory */
$productFactory = $objectManager->get(ProductInterfaceFactory::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productFactory->create();
$product->isObjectNew(true);
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('name_simple_product')
->setSku('sku_simple_product')
->setShortDescription('short_description_simple_product')
->setDescription('description_simple_product')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setPrice(100)
->setWeight(1)
->setTaxClassId(0)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
try {
$product = $productRepository->get('sku_simple_product', false, null, true);
$productRepository->delete($product);
} catch (NoSuchEntityException $e) {
//product already deleted.
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,77 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\Data\ProductInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\TestFramework\Helper\Bootstrap;
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$products = [
[
'name' => 'index enabled',
'sku' => 'index_enabled',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
],
[
'name' => 'index disabled',
'sku' => 'index_disabled',
'status' => Status::STATUS_DISABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
],
[
'name' => 'index visible search',
'sku' => 'index_visible_search',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_IN_SEARCH,
],
[
'name' => 'index visible category',
'sku' => 'index_visible_category',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_IN_CATALOG,
],
[
'name' => 'index visible both',
'sku' => 'index_visible_both',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
],
[
'name' => 'index not visible',
'sku' => 'index_not_visible',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
]
];
/** @var $productFactory ProductInterfaceFactory */
$productFactory = Bootstrap::getObjectManager()->create(ProductInterfaceFactory::class);
foreach ($products as $data) {
/** @var ProductInterface $product */
$product = $productFactory->create();
$product
->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId(4)
->setName($data['name'])
->setSku($data['sku'])
->setPrice(10)
->setVisibility($data['visibility'])
->setStatus($data['status']);
$product = $productRepository->save($product);
/** @var StockItemInterface $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem->setUseConfigManageStock(0);
$productRepository->save($product);
}
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
Bootstrap::getInstance()->getInstance()->reinitialize();
/** @var Registry $registry */
$registry = Bootstrap::getObjectManager()->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$productSkus = [
'index_enabled',
'index_disabled',
'index_visible_search',
'index_visible_category',
'index_visible_both',
'index_not_visible'
];
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()->get(SearchCriteriaBuilder::class);
$searchCriteriaBuilder->addFilter(ProductInterface::SKU, $productSkus, 'in');
$result = $productRepository->getList($searchCriteriaBuilder->create());
foreach ($result->getItems() as $product) {
$productRepository->delete($product);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,112 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\Eav\Model\Config;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/CatalogSearch/_files/searchable_attribute.php');
$objectManager = Bootstrap::getObjectManager();
/** @var Config $eavConfig */
$eavConfig = $objectManager->get(Config::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_searchable_attribute');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Xbox')
->setSku('nintendo-wii')
->setUrlKey('not-related')
->setPrice(10)
->setTaxClassId(0)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Nintendo Wii')
->setSku('xbox')
->setUrlKey('something-random')
->setPrice(10)
->setTaxClassId(0)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Console description')
->setSku('console_description')
->setUrlKey('console-description')
->setDescription('xbox')
->setPrice(10)
->setTaxClassId(0)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName('Gamecube attribute')
->setSku('gamecube_attribute')
->setUrlKey('gamecube-attribute')
->setPrice(10)
->setTaxClassId(0)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setTestSearchableAttribute($attribute->getSource()->getOptionId('xbox'))
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
);
$productRepository->save($product);
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$productSkus = [
'1234-1234-1234-1234',
'Simple',
'product_with_description',
'product_with_attribute',
'nintendo-wii',
'xbox',
'console_description',
'gamecube_attribute',
];
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
foreach ($productSkus as $productSku) {
try {
$productRepository->deleteById($productSku);
} catch (NoSuchEntityException $e) {
//Product already deleted.
}
}
try {
$productAttributeRepository->deleteById('test_searchable_attribute');
} catch (NoSuchEntityException $e) {
//attribute already deleted.
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $query \Magento\Search\Model\Query */
$query = $objectManager->create(\Magento\Search\Model\Query::class);
$query->setStoreId(1);
$query->setQueryText(
'query_text'
)->setNumResults(
1
)->setPopularity(
1
)->setDisplayInTerms(
1
)->setIsActive(
1
)->setIsProcessed(
1
)->save();
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Framework\UrlInterface;
use Magento\Search\Model\Query;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/CatalogSearch/_files/query.php');
$objectManager = Bootstrap::getObjectManager();
/** @var UrlInterface $url */
$url = $objectManager->get(UrlInterface::class);
/** @var $query Query */
$query = $objectManager->create(Query::class);
$query->loadByQueryText('query_text');
$query->setRedirect($url->getCurrentUrl() . 'catalogsearch/result/?q=query_text&cat=41')
->save();
@@ -0,0 +1,38 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<requests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Search/etc/search_request_merged.xsd">
<request query="filter_by_configurable_product_options" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="filter_by_configurable_product_options" boost="1">
<queryReference clause="must" ref="category"/>
<queryReference clause="must" ref="test_configurable"/>
<queryReference clause="must" ref="test_configurable_2"/>
</query>
<query xsi:type="filteredQuery" name="category">
<filterReference clause="must" ref="category_filter"/>
</query>
<query xsi:type="filteredQuery" name="test_configurable">
<filterReference clause="must" ref="test_configurable_filter"/>
</query>
<query xsi:type="filteredQuery" name="test_configurable_2">
<filterReference clause="must" ref="test_configurable_2_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="termFilter" name="category_filter" field="category_ids" value="$category_ids$"/>
<filter xsi:type="termFilter" name="test_configurable_filter" field="test_configurable" value="$test_configurable$"/>
<filter xsi:type="termFilter" name="test_configurable_2_filter" field="test_configurable_2" value="$test_configurable_2$"/>
</filters>
<aggregations/>
<from>0</from>
<size>10</size>
</request>
</requests>
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* Create attribute */
/** @var $installer \Magento\Catalog\Setup\CategorySetup */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Setup\CategorySetup::class
);
$attributesData = [
[
'attribute_code' => 'test_quick_search',
'is_filterable_in_search' => 1,
],
[
'attribute_code' => 'test_catalog_view',
'is_filterable' => 1,
]
];
foreach ($attributesData as $data) {
/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
);
$attributeData = array_merge(
[
'attribute_code' => '',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 1,
'is_searchable' => 0,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Test Configurable'],
'backend_type' => 'int',
'option' => [
'value' => ['option_0' => ['Option 1'], 'option_1' => ['Option 2']],
'order' => ['option_0' => 1, 'option_1' => 2],
],
],
$data
);
$attribute->setData($attributeData);
$attribute->save();
/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
}
/** @var \Magento\Eav\Model\Config $eavConfig */
$eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class);
$eavConfig->clear();
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class);
$attributesCode = ['test_advanced_search', 'test_quick_search', 'test_catalog_view'];
foreach (['test_quick_search', 'test_catalog_view'] as $code) {
$attribute = $eavConfig->getAttribute('catalog_product', $code);
if ($attribute instanceof \Magento\Eav\Model\Entity\Attribute\AbstractAttribute
&& $attribute->getId()
) {
$attribute->delete();
}
}
$eavConfig->clear();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
use Magento\Eav\Setup\EavSetup;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var AttributeFactory $attributeFactory */
$attributeFactory = $objectManager->get(AttributeFactory::class);
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
$attribute = $attributeFactory->create()->loadByCode(Product::ENTITY, 'test_searchable_attribute');
if (!$attribute->getId()) {
/** @var EavSetup $installer */
$installer = $objectManager->create(EavSetup::class);
$attribute->setData(
[
'attribute_code' => 'test_searchable_attribute',
'is_global' => 0,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 1,
'is_comparable' => 0,
'is_filterable' => 1,
'is_filterable_in_search' => 1,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Test Drop-Down Attribute'],
'backend_type' => 'int',
'option' => [
'value' => [
'option_1' => ['Option 1'],
'option_2' => ['Option 2'],
'option_3' => ['Option 3'],
'option_4' => ['xbox']
],
'order' => [
'option_1' => 1,
'option_2' => 2,
'option_3' => 3,
'option_4' => 4,
],
],
]
);
$productAttributeRepository->save($attribute);
$attribute = $productAttributeRepository->get('test_searchable_attribute');
/* Assign attribute to attribute set */
$installer->addAttributeToGroup(Product::ENTITY, 'Default', 'Attributes', $attribute->getId());
}