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,171 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\CatalogGraphQl;
use Magento\Catalog\Api\Data\CategoryAttributeInterface;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Test\Fixture\Attribute;
use Magento\Catalog\Test\Fixture\CategoryAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
#[
DataFixture(
CategoryAttribute::class,
[
'frontend_input' => 'multiselect',
'is_filterable_in_search' => true,
'position' => 4,
'apply_to' => 'category'
],
'category_attribute'
),
DataFixture(
Attribute::class,
[
'frontend_input' => 'multiselect',
'is_filterable_in_search' => true,
'position' => 5,
],
'product_attribute'
),
]
class AttributesMetadataTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
...on CatalogAttributeMetadata {
is_filterable_in_search
is_searchable
is_filterable
is_comparable
is_html_allowed_on_front
is_used_for_price_rules
is_wysiwyg_enabled
is_used_for_promo_rules
used_in_product_listing
apply_to
}
}
errors {
type
message
}
}
}
QRY;
/**
* @return void
* @throws \Exception
*/
public function testMetadataProduct(): void
{
/** @var ProductAttributeInterface $productAttribute */
$productAttribute = DataFixtureStorageManager::getStorage()->get('product_attribute');
$result = $this->graphQlQuery(
sprintf(
self::QUERY,
$productAttribute->getAttributeCode(),
ProductAttributeInterface::ENTITY_TYPE_CODE
)
);
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $productAttribute->getAttributeCode(),
'label' => $productAttribute->getDefaultFrontendLabel(),
'entity_type' => strtoupper(ProductAttributeInterface::ENTITY_TYPE_CODE),
'frontend_input' => 'MULTISELECT',
'is_required' => false,
'default_value' => $productAttribute->getDefaultValue(),
'is_unique' => false,
'is_filterable_in_search' => true,
'is_searchable' => false,
'is_filterable' => false,
'is_comparable' => false,
'is_html_allowed_on_front' => true,
'is_used_for_price_rules' => false,
'is_wysiwyg_enabled' => false,
'is_used_for_promo_rules' => false,
'used_in_product_listing' => false,
'apply_to' => null,
]
],
'errors' => []
]
],
$result
);
}
/**
* @return void
* @throws \Exception
*/
public function testMetadataCategory(): void
{
/** @var CategoryAttributeInterface $categoryAttribute */
$categoryAttribute = DataFixtureStorageManager::getStorage()->get('category_attribute');
$result = $this->graphQlQuery(
sprintf(
self::QUERY,
$categoryAttribute->getAttributeCode(),
CategoryAttributeInterface::ENTITY_TYPE_CODE
)
);
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $categoryAttribute->getAttributeCode(),
'label' => $categoryAttribute->getDefaultFrontendLabel(),
'entity_type' => strtoupper(CategoryAttributeInterface::ENTITY_TYPE_CODE),
'frontend_input' => 'MULTISELECT',
'is_required' => false,
'default_value' => $categoryAttribute->getDefaultValue(),
'is_unique' => false,
'is_filterable_in_search' => true,
'is_searchable' => false,
'is_filterable' => false,
'is_comparable' => false,
'is_html_allowed_on_front' => true,
'is_used_for_price_rules' => false,
'is_wysiwyg_enabled' => false,
'is_used_for_promo_rules' => false,
'used_in_product_listing' => false,
'apply_to' => ['CATEGORY'],
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\CatalogGraphQl;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test class to verify category uid, available as product aggregation type
*/
class CategoryTest extends GraphQlAbstract
{
/**
* Test for checking if graphQL query for category uid is available as product aggregation type
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testCheckCategoryUidAsAggregation(): void
{
$query = $this->getSearchQueryWithSCategoryUID();
$response = $this->graphQlQuery($query);
$this->assertNotEmpty($response['products']);
$this->assertEquals(1, count($response['products']['aggregations']));
$this->assertNotEmpty($response['products']['aggregations']);
$this->assertEquals('price', $response['products']['aggregations'][0]['attribute_code']);
}
/**
* Prepare search query with suggestions
*
* @return string
*/
private function getSearchQueryWithSCategoryUID() : string
{
return <<<QUERY
{
products(filter: {category_uid: {eq: "Mg=="}}) {
aggregations {
__typename
attribute_code
}
__typename
}
}
QUERY;
}
}
@@ -0,0 +1,206 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\CatalogGraphQl;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Directory\Helper\Data as LocaleConfig;
use Magento\Eav\Model\Entity\Attribute\FrontendLabel;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Translation\Test\Fixture\Translation as TranslationFixture;
/**
* Test class to verify the translated price attribute option label based on the store view.
*/
class PriceAttributeOptionsLabelTranslateTest extends GraphQlAbstract
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixture;
/**
* Setup
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->fixture = DataFixtureStorageManager::getStorage();
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
#[
DataFixture(
StoreFixture::class,
[
'code' => 'view2',
'name' => 'view2'
],
as: 'view2'
),
DataFixture(
ProductFixture::class,
[
'sku' => 'simple'
],
as: 'product'
),
]
public function testValidatePriceAttributeOptionsLabelTranslationForSecondStoreView(): void
{
$attributeCode = 'price';
$secondStoreViewFixtureName = 'view2';
$attributeStoreFrontLabelForSecondStoreView = 'Price View2';
//Updating price attribute storefront option label for the second store view.
$attributeRepository = $this->objectManager->create(ProductAttributeRepositoryInterface::class);
$priceAttribute = $attributeRepository->get($attributeCode);
$frontendLabelAttribute = $this->objectManager->get(FrontendLabel::class);
$frontendLabelAttribute->setStoreId(
$this->fixture->get($secondStoreViewFixtureName)->getId()
);
$frontendLabelAttribute->setLabel($attributeStoreFrontLabelForSecondStoreView);
$frontendLabels = $priceAttribute->getFrontendLabels();
$frontendLabels[] = $frontendLabelAttribute;
$priceAttribute->setFrontendLabels($frontendLabels);
$attributeRepository->save($priceAttribute);
$query = $this->getProductsQueryWithAggregations();
$headers = ['Store' => $secondStoreViewFixtureName];
$response = $this->graphQlQuery($query, [], '', $headers);
$this->assertNotEmpty($response['products']['aggregations']);
$aggregationAttributes = $response['products']['aggregations'];
$priceAttributeOptionLabel = '';
foreach ($aggregationAttributes as $attribute) {
if ($attribute['attribute_code'] === $attributeCode) {
$priceAttributeOptionLabel = $attribute['label'];
}
}
$this->assertEquals('Price View2', $priceAttributeOptionLabel);
}
/**
* Prepare products query with aggregations
*
* @return string
*/
private function getProductsQueryWithAggregations() : string
{
return <<<QUERY
{
products(
currentPage: 1,
pageSize:12,
filter: {
sku: {
eq: "simple"
}
}, sort: {
price: ASC
}) {
aggregations {
options {
count,
label,
value
}, attribute_code, count, label
}
}
}
QUERY;
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
#[
DataFixture(
TranslationFixture::class,
[
'string' => 'Price View2',
'translate' => 'Preisansicht',
'locale' => 'de_DE',
]
),
DataFixture(
StoreFixture::class,
[
'code' => 'view2',
'name' => 'view2'
],
as: 'view2'
),
DataFixture(
ProductFixture::class,
[
'sku' => 'simple'
],
as: 'product'
),
Config(LocaleConfig::XML_PATH_DEFAULT_LOCALE, 'de_DE', 'store', 'view2'),
]
public function testValidateAggregateAttributeOptionsInLabelLocaleTranslationForSecondStoreView(): void
{
$attributeCode = 'price';
$secondStoreViewFixtureName = 'view2';
$attributeStoreFrontLabelForSecondStoreView = 'Price View2';
//Updating price attribute storefront option label for the second store view.
$attributeRepository = $this->objectManager->create(ProductAttributeRepositoryInterface::class);
$priceAttribute = $attributeRepository->get($attributeCode);
$frontendLabelAttribute = $this->objectManager->get(FrontendLabel::class);
$frontendLabelAttribute->setStoreId(
$this->fixture->get($secondStoreViewFixtureName)->getId()
);
$frontendLabelAttribute->setLabel($attributeStoreFrontLabelForSecondStoreView);
$frontendLabels = $priceAttribute->getFrontendLabels();
$frontendLabels[] = $frontendLabelAttribute;
$priceAttribute->setFrontendLabels($frontendLabels);
$attributeRepository->save($priceAttribute);
$query = $this->getProductsQueryWithAggregations();
$headers = ['Store' => $secondStoreViewFixtureName];
$response = $this->graphQlQuery($query, [], '', $headers);
$this->assertNotEmpty($response['products']['aggregations']);
$aggregationAttributes = $response['products']['aggregations'];
$priceAttributeOptionLabel = '';
foreach ($aggregationAttributes as $attribute) {
if ($attribute['attribute_code'] === $attributeCode) {
$priceAttributeOptionLabel = $attribute['label'];
}
}
$this->assertEquals('Preisansicht', $priceAttributeOptionLabel);
}
}
@@ -0,0 +1,368 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\CatalogGraphQl;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test class to verify catalog price rule is applied for
* tier prices for different customer groups.
*/
class PriceRangeTest extends GraphQlAbstract
{
/**
* @var ObjectManager|null
*/
private $objectManager;
/**
* @var GetCustomerAuthenticationHeader
*/
private $getCustomerAuthenticationHeader;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->getCustomerAuthenticationHeader = $this->objectManager->get(GetCustomerAuthenticationHeader::class);
}
/**
* @magentoApiDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_in_multiple_websites.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_in_multiple_websites_with_special_price.php
*/
public function testMinimalPriceForConfigurableProductWithSpecialPrice() : void
{
$headerMapFirstStore['Store'] = 'default';
$headerMapSecondStore['Store'] = 'fixture_second_store';
$query = $this->getProductsBySkuQuery();
$responseForFirstWebsite = $this->graphQlQuery($query, [], '', $headerMapFirstStore);
$responseForSecondWebsite = $this->graphQlQuery($query, [], '', $headerMapSecondStore);
$this->assertNotEmpty($responseForFirstWebsite['products']);
$priceRange = $responseForFirstWebsite['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['final_price']['value']);
$this->assertNotEmpty($responseForSecondWebsite['products']);
$priceRange = $responseForSecondWebsite['products']['items'][0]['price_range'];
$this->assertEquals(20, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(4, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(20, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(4, $priceRange['maximum_price']['final_price']['value']);
}
/**
* Test for checking if catalog rule price has been applied for all customer group
*
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_25_customer_group_all.php
*/
public function testCheckIfCatalogRuleIsAppliedForTierPriceForAllGroups(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery($query);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(7.5, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(2.5, $priceRange['minimum_price']['discount']['amount_off']);
$this->assertEquals(25, $priceRange['minimum_price']['discount']['percent_off']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(7.5, $priceRange['maximum_price']['final_price']['value']);
$this->assertEquals(2.5, $priceRange['maximum_price']['discount']['amount_off']);
$this->assertEquals(25, $priceRange['maximum_price']['discount']['percent_off']);
}
/**
* Test for checking if catalog rule price has been applied for registered customer
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/simple_product_with_tier_prices_for_logged_in_group.php
* @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_50_registered_customer_group.php
*/
public function testCheckIfCatalogRuleIsAppliedForTierPriceForRegisteredCustomer(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthenticationHeader->execute('customer@example.com', 'password')
);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(5, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(5, $priceRange['minimum_price']['discount']['amount_off']);
$this->assertEquals(50, $priceRange['minimum_price']['discount']['percent_off']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(5, $priceRange['maximum_price']['final_price']['value']);
$this->assertEquals(5, $priceRange['maximum_price']['discount']['amount_off']);
$this->assertEquals(50, $priceRange['maximum_price']['discount']['percent_off']);
}
/**
* Test for checking if catalog rule price has been applied for guest
*
* @magentoApiDataFixture Magento/Catalog/_files/simple_product_with_tier_prices_for_not_logged_in_group.php
* @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_10_off_not_logged.php
*/
public function testCheckIfCatalogRuleIsAppliedForTierPriceForGuest(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery($query);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(9, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(1, $priceRange['minimum_price']['discount']['amount_off']);
$this->assertEquals(10, $priceRange['minimum_price']['discount']['percent_off']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(9, $priceRange['maximum_price']['final_price']['value']);
$this->assertEquals(1, $priceRange['maximum_price']['discount']['amount_off']);
$this->assertEquals(10, $priceRange['maximum_price']['discount']['percent_off']);
}
/**
* Test to make sure tax amount is displayed correctly for a logged-in user
*
* @magentoConfigFixture default_store tax/display/type 2
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_shipping_address_36104.php
* @magentoApiDataFixture Magento/Tax/_files/tax_rule_postal_36104.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testTaxDisplayAppliesToCustomer(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthenticationHeader->execute('customer@example.com', 'password')
);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10.75, round($priceRange['minimum_price']['regular_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['minimum_price']['final_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['maximum_price']['regular_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['maximum_price']['final_price']['value'], 2));
}
/**
* Test to make sure tax rule is not applied in display for guest
*
* @magentoConfigFixture default_store tax/display/type 2
*
* @magentoApiDataFixture Magento/Tax/_files/tax_rule_postal_36104.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testTaxDisplayDoesNotApplyToGuest(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery($query);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['final_price']['value']);
}
/**
* Test to make sure tax rule is applied for customer group
*
* @magentoConfigFixture default_store tax/display/type 2
*
* @magentoApiDataFixture Magento/Customer/_files/customer_with_group_and_address.php
* @magentoApiDataFixture Magento/Tax/_files/tax_class_customer_group.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testTaxDisplayAppliesToCustomerGroup()
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthenticationHeader->execute('customer@example.com', 'password')
);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10.75, round($priceRange['minimum_price']['regular_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['minimum_price']['final_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['maximum_price']['regular_price']['value'], 2));
$this->assertEquals(10.75, round($priceRange['maximum_price']['final_price']['value'], 2));
}
/**
* Test to make sure tax rule is not applied for a customer in the wrong group
*
* @magentoConfigFixture default_store tax/display/type 2
*
* @magentoApiDataFixture Magento/Customer/_files/customer_with_group_and_address.php
* @magentoApiDataFixture Magento/Customer/_files/second_customer_with_group_and_address.php
* @magentoApiDataFixture Magento/Tax/_files/tax_class_customer_group.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testTaxDisplayDoesNotApplyToWrongCustomerGroup(): void
{
$productSku = 'simple';
$query = $this->getProductSearchQuery($productSku);
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthenticationHeader->execute('secondcustomer@example.com', 'password')
);
$this->assertNotEmpty($response['products']);
$priceRange = $response['products']['items'][0]['price_range'];
$this->assertEquals(10, $priceRange['minimum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['minimum_price']['final_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['regular_price']['value']);
$this->assertEquals(10, $priceRange['maximum_price']['final_price']['value']);
}
/**
* Get a query which user filter for product sku and returns price_tiers
*
* @param string $productSku
* @return string
*/
private function getProductSearchQuery(string $productSku): string
{
return <<<QUERY
{
products(filter: {sku: {eq: "{$productSku}"}}) {
items {
name
sku
price_range {
minimum_price {
regular_price {
value
currency
}
final_price {
value
currency
}
discount {
amount_off
percent_off
}
}
maximum_price {
regular_price {
value
currency
}
final_price {
value
currency
}
discount {
amount_off
percent_off
}
}
}
price_tiers{
discount{
amount_off
percent_off
}
final_price{
value
}
quantity
}
}
}
}
QUERY;
}
/**
* Get a query which user filter for product sku and returns price_range
*
* @param string $productSku
* @return string
*/
private function getProductsBySkuQuery() : string
{
return <<<QUERY
query getProductsBySku {
products(filter: { sku: { eq: "configurable" } }) {
items {
sku
name
price_range {
minimum_price {
regular_price {
value
currency
}
discount {
amount_off
percent_off
}
final_price {
value
currency
}
}
maximum_price {
regular_price {
value
currency
}
discount {
amount_off
percent_off
}
final_price {
value
currency
}
}
}
... on ConfigurableProduct {
variants {
product {
sku
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,374 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\CatalogGraphQl;
use Magento\Catalog\Test\Fixture\Category as CategoryFixture;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Indexer\Model\IndexerFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\Catalog\Test\Fixture\Product;
use Magento\Indexer\Test\Fixture\Indexer;
/**
* Test class to verify product search, used for GraphQL resolver
* for configurable product returns only visible products.
*/
class ProductSearchTest extends GraphQlAbstract
{
#[
DataFixture(CategoryFixture::class, as: 'cat1'),
DataFixture(
ProductFixture::class,
[
'category_ids' => ['$cat1.id$'],
],
'product'
)
]
public function testSearchProductsWithCategoriesAliasPresentInQuery(): void
{
$this->reindexCatalogCategory();
/** @var \Magento\Catalog\Model\Product $product */
$product = DataFixtureStorageManager::getStorage()->get('product');
/** @var \Magento\Catalog\Model\Category $category */
$category = DataFixtureStorageManager::getStorage()->get('cat1');
$response = $this->graphQlQuery($this->getProductSearchQueryWithCategoriesAlias($product->getSku()));
$this->assertNotEmpty($response['products']);
$this->assertNotEmpty($response['products']['items']);
$this->assertEquals(
$category->getUrlKey(),
$response['products']['items'][0]['custom_categories'][0]['url_key']
);
}
/**
* Make catalog_category reindex.
*
* @return void
* @throws \Throwable
*/
private function reindexCatalogCategory(): void
{
$indexerFactory = Bootstrap::getObjectManager()->create(IndexerFactory::class);
$indexer = $indexerFactory->create();
$indexer->load('catalog_category_product')->reindexAll();
}
#[
DataFixture(Product::class, as: 'product')
]
public function testSearchProductsWithSkuEqFilterQuery(): void
{
/** @var \Magento\Catalog\Model\Product $product */
$product = DataFixtureStorageManager::getStorage()->get('product');
$response = $this->graphQlQuery($this->getProductSearchQuery($product->getName(), $product->getSku()));
$this->assertNotEmpty($response['products']);
$this->assertEquals(1, $response['products']['total_count']);
$this->assertNotEmpty($response['products']['items']);
$this->assertEquals($product->getName(), $response['products']['items'][0]['name']);
$this->assertEquals($product->getSku(), $response['products']['items'][0]['sku']);
}
#[
DataFixture(Product::class, as: 'product1'),
DataFixture(Product::class, as: 'product2'),
DataFixture(Product::class, as: 'product3')
]
public function testSearchProductsWithMultipleSkuInFilterQuery(): void
{
/** @var \Magento\Catalog\Model\Product $product */
$response = $this->graphQlQuery(
$this->getProductSearchQueryWithMultipleSkusFilter([
DataFixtureStorageManager::getStorage()->get('product1'),
DataFixtureStorageManager::getStorage()->get('product2'),
DataFixtureStorageManager::getStorage()->get('product3')
], "simple")
);
$this->assertNotEmpty($response['products']);
$this->assertEquals(3, $response['products']['total_count']);
$this->assertNotEmpty($response['products']['items']);
}
#[
DataFixture(Product::class, as: 'product1'),
DataFixture(Product::class, as: 'product2'),
DataFixture(Indexer::class, as: 'indexer')
]
public function testSearchSuggestions(): void
{
$response = $this->graphQlQuery($this->getSearchQueryWithSuggestions());
$this->assertNotEmpty($response['products']);
$this->assertEmpty($response['products']['items']);
$this->assertNotEmpty($response['products']['suggestions']);
}
/**
* Get a query which contains alias for product categories data.
*
* @param string $productSku
* @return string
*/
private function getProductSearchQueryWithCategoriesAlias(string $productSku): string
{
return <<<QUERY
{
products(filter: {
sku: {
eq: "{$productSku}"
}})
{
items {
name
sku
categories {
uid
name
}
custom_categories: categories {
url_key
}
}
}
}
QUERY;
}
/**
* Get a query which user filter for product sku and search by product name
*
* @param string $productName
* @param string $productSku
* @return string
*/
private function getProductSearchQuery(string $productName, string $productSku): string
{
return <<<QUERY
{
products(filter: {
sku: {
eq: "{$productSku}"
}},
search: "$productName",
sort: {},
pageSize: 200,
currentPage: 1)
{
total_count
page_info {
total_pages
current_page
page_size
}
items {
name
sku
}
}
}
QUERY;
}
/**
* Get a query which filters list of found products by array of SKUs
*
* @param array $products
* @param string $product
* @return string
*/
private function getProductSearchQueryWithMultipleSkusFilter(array $products, string $product): string
{
return <<<QUERY
{
products(filter: {
sku: {
in: [
"{$products[0]->getSku()}",
"{$products[1]->getSku()}",
"{$products[2]->getSku()}"
]
}},
search: "$product",
sort: {},
pageSize: 200,
currentPage: 1)
{
total_count
page_info {
total_pages
current_page
page_size
}
items {
name
sku
}
}
}
QUERY;
}
/**
* Prepare search query with suggestions
*
* @return string
*/
private function getSearchQueryWithSuggestions(): string
{
return <<<QUERY
{
products(
search: "smiple"
) {
items {
name
sku
}
suggestions {
search
}
}
}
QUERY;
}
#[
DataFixture(CategoryFixture::class, as: 'category'),
DataFixture(
ProductFixture::class,
[
'name' => 'Lifelong 1',
'sku' => 'lifelong1',
'description' => 'Life product 1',
'category_ids' => ['$category.id$'],
],
'product1'
),
DataFixture(
ProductFixture::class,
[
'name' => 'Life 2',
'sku' => 'life2',
'description' => 'Lifelong product 2',
'category_ids' => ['$category.id$'],
],
'product2'
),
DataFixture(
ProductFixture::class,
[
'name' => 'Life 3',
'sku' => 'life3',
'description' => 'Life product 3',
'category_ids' => ['$category.id$'],
],
'product3'
),
DataFixture(
ProductFixture::class,
[
'name' => 'Lifelong 4',
'sku' => 'lifelong4',
'description' => 'Lifelong product 4',
'category_ids' => ['$category.id$'],
],
'product4'
),
]
public function testSearchProductsWithFilterAndMatchTypeInQuery(): void
{
$response1 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, false, '', ''));
$response2 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, false, 'FULL', ''));
$response3 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, false, 'PARTIAL', ''));
$response4 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(false, true, '', ''));
$response5 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(false, true, '', 'FULL'));
$response6 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(false, true, '', 'PARTIAL'));
$response7 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, true, '', ''));
$response8 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, true, 'FULL', 'FULL'));
$response9 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, true, 'PARTIAL', 'PARTIAL'));
$response10 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, true, 'FULL', 'PARTIAL'));
$response11 = $this->graphQlQuery($this->getProductSearchQueryWithMatchType(true, true, 'PARTIAL', 'FULL'));
$this->assertEquals($response1, $response2);
$this->assertNotEquals($response2, $response3);
$this->assertEquals(2, $response1['products']['total_count']); // product 2, product 3
$this->assertEquals(2, $response2['products']['total_count']); // product 2, product 3
$this->assertEquals(4, $response3['products']['total_count']); // all
$this->assertEquals('life2', $response1['products']['items'][1]['sku']);
$this->assertEquals('life2', $response2['products']['items'][1]['sku']);
$this->assertEquals('lifelong4', $response3['products']['items'][0]['sku']);
$this->assertEquals($response4, $response5);
$this->assertNotEquals($response5, $response6);
$this->assertEquals(2, $response4['products']['total_count']); // product 1, product 3
$this->assertEquals(2, $response5['products']['total_count']); // product 1, product 3
$this->assertEquals(4, $response6['products']['total_count']); // all
$this->assertEquals('lifelong1', $response4['products']['items'][1]['sku']);
$this->assertEquals('lifelong1', $response5['products']['items'][1]['sku']);
$this->assertEquals('lifelong4', $response6['products']['items'][0]['sku']);
$this->assertEquals($response7, $response8);
$this->assertNotEquals($response8, $response9);
$this->assertEquals(1, $response7['products']['total_count']); // product 3
$this->assertEquals(1, $response8['products']['total_count']); // product 3
$this->assertEquals(4, $response9['products']['total_count']); // all
$this->assertEquals(2, $response10['products']['total_count']); // product 2, product 3
$this->assertEquals(2, $response11['products']['total_count']); // product 1, product 3
$this->assertEquals('life3', $response7['products']['items'][0]['sku']);
$this->assertEquals('life3', $response8['products']['items'][0]['sku']);
$this->assertEquals('lifelong4', $response9['products']['items'][0]['sku']);
$this->assertEquals('life2', $response10['products']['items'][1]['sku']);
$this->assertEquals('lifelong1', $response11['products']['items'][1]['sku']);
}
/**
* Get a combinations of queries which contain different match_type
*
* @param bool $filterByName
* @param bool $filterByDescription
* @param string $matchTypeName
* @param string $matchTypeDescription
* @return string
*/
private function getProductSearchQueryWithMatchType(
bool $filterByName,
bool $filterByDescription,
string $matchTypeName = '',
string $matchTypeDescription = ''
): string {
$matchTypeName = $matchTypeName ? 'match_type:' . $matchTypeName : '';
$matchTypeDescription = $matchTypeDescription ? 'match_type:' . $matchTypeDescription : '';
$name = $filterByName ? 'name : { match : "Life", '.$matchTypeName.'}' : '';
$description = $filterByDescription ? 'description: { match: "Life", '.$matchTypeDescription.'}' : '';
return <<<QUERY
{
products(filter :
{
$name
$description
}){
total_count
items {
name
sku
description {
html
}
}
}
}
QUERY;
}
}