ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,383 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Exception;
use Magento\CatalogInventory\Model\Configuration;
use Magento\Config\Model\ResourceModel\Config;
use Magento\ConfigurableProductGraphQl\Model\Options\SelectionUidFormatter;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Add configurable product to cart testcases
*/
class AddConfigurableProductToCartSingleMutationTest extends GraphQlAbstract
{
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @var Config $config
*/
private $resourceConfig;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var ReinitableConfigInterface
*/
private $reinitConfig;
/**
* @var SelectionUidFormatter
*/
private $selectionUidFormatter;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
$this->resourceConfig = $objectManager->get(Config::class);
$this->scopeConfig = $objectManager->get(ScopeConfigInterface::class);
$this->reinitConfig = $objectManager->get(ReinitableConfigInterface::class);
$this->selectionUidFormatter = $objectManager->get(SelectionUidFormatter::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductToCart(): void
{
$product = $this->getConfigurableProductInfo();
$quantity = 2;
$parentSku = $product['sku'];
$attributeId = (int) $product['configurable_options'][0]['attribute_id'];
$valueIndex = $product['configurable_options'][0]['values'][1]['value_index'];
$productRowId = (string) $product['configurable_options'][0]['product_id'];
$selectedConfigurableOptionsQuery = $this->generateSuperAttributesUIDQuery($attributeId, $valueIndex);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$query = $this->getQuery(
$maskedQuoteId,
$product['sku'],
2,
$selectedConfigurableOptionsQuery
);
$response = $this->graphQlMutation($query);
$expectedProductOptionsValueUid = $this->selectionUidFormatter->encode($attributeId, $valueIndex);
$expectedProductOptionsUid = base64_encode("configurable/$productRowId/$attributeId");
$cartItem = current($response['addProductsToCart']['cart']['items']);
self::assertEquals($quantity, $cartItem['quantity']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertEquals(base64_encode((string)$cartItem['product']['id']), $cartItem['product']['uid']);
self::assertArrayHasKey('configurable_options', $cartItem);
$option = current($cartItem['configurable_options']);
self::assertEquals($attributeId, $option['id']);
self::assertEquals($valueIndex, $option['value_id']);
self::assertEquals($expectedProductOptionsValueUid, $option['configurable_product_option_value_uid']);
self::assertEquals($expectedProductOptionsUid, $option['configurable_product_option_uid']);
self::assertArrayHasKey('option_label', $option);
self::assertArrayHasKey('value_label', $option);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/configurable_products_with_custom_attribute_layered_navigation.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductWithWrongSuperAttributes(): void
{
$product = $this->getConfigurableProductInfo();
$quantity = 2;
$parentSku = $product['sku'];
$selectedConfigurableOptionsQuery = $this->generateSuperAttributesUIDQuery(0, 0);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$quantity,
$selectedConfigurableOptionsQuery
);
$response = $this->graphQlMutation($query);
self::assertEquals(
'You need to choose options for your item.',
$response['addProductsToCart']['user_errors'][0]['message']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddProductIfQuantityIsNotAvailable(): void
{
$product = $this->getConfigurableProductInfo();
$parentSku = $product['sku'];
$attributeId = (int) $product['configurable_options'][0]['attribute_id'];
$valueIndex = $product['configurable_options'][0]['values'][1]['value_index'];
$selectedConfigurableOptionsQuery = $this->generateSuperAttributesUIDQuery($attributeId, $valueIndex);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
2000,
$selectedConfigurableOptionsQuery
);
$response = $this->graphQlMutation($query);
self::assertEquals(
'The requested qty is not available',
$response['addProductsToCart']['user_errors'][0]['message']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddNonExistentConfigurableProductParentToCart(): void
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = 'configurable_no_exist';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
1,
''
);
$response = $this->graphQlMutation($query);
self::assertEquals(
'Could not find a product with SKU "configurable_no_exist"',
$response['addProductsToCart']['user_errors'][0]['message']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_zero_qty_first_child.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testOutOfStockVariationToCart(): void
{
$showOutOfStock = $this->scopeConfig->getValue(Configuration::XML_PATH_SHOW_OUT_OF_STOCK);
// Changing SHOW_OUT_OF_STOCK to show the out of stock option, otherwise graphql won't display it.
$this->resourceConfig->saveConfig(Configuration::XML_PATH_SHOW_OUT_OF_STOCK, 1);
$this->reinitConfig->reinit();
$product = $this->getConfigurableProductInfo();
$attributeId = (int) $product['configurable_options'][0]['attribute_id'];
$valueIndex = $product['configurable_options'][0]['values'][0]['value_index'];
// Asserting that the first value is the right option we want to add to cart
self::assertEquals(
$product['configurable_options'][0]['values'][0]['label'],
'Option 1'
);
$parentSku = $product['sku'];
$configurableOptionsQuery = $this->generateSuperAttributesUIDQuery($attributeId, $valueIndex);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
1,
$configurableOptionsQuery
);
$response = $this->graphQlMutation($query);
$expectedErrorMessages = [
'There are no source items with the in stock status',
'This product is out of stock.'
];
self::assertContains(
$response['addProductsToCart']['user_errors'][0]['message'],
$expectedErrorMessages
);
$this->resourceConfig->saveConfig(Configuration::XML_PATH_SHOW_OUT_OF_STOCK, $showOutOfStock);
$this->reinitConfig->reinit();
}
/**
* @param string $maskedQuoteId
* @param string $parentSku
* @param int $quantity
* @param string $selectedOptionsQuery
* @return string
*/
private function getQuery(
string $maskedQuoteId,
string $parentSku,
int $quantity,
string $selectedOptionsQuery
): string {
return <<<QUERY
mutation {
addProductsToCart(
cartId:"{$maskedQuoteId}"
cartItems: [
{
sku: "{$parentSku}"
quantity: $quantity
{$selectedOptionsQuery}
}
]
) {
cart {
items {
id
uid
quantity
product {
sku
uid
id
}
... on ConfigurableCartItem {
configurable_options {
id
configurable_product_option_uid
option_label
value_id
configurable_product_option_value_uid
value_label
}
}
}
},
user_errors {
message
}
}
}
QUERY;
}
/**
* Returns information about testable configurable product retrieved from GraphQl query
*
* @return array
* @throws Exception
*/
private function getConfigurableProductInfo(): array
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
return current($searchResponse['products']['items']);
}
/**
* Generates UID for super configurable product super attributes
*
* @param int $attributeId
* @param int $valueIndex
* @return string
*/
private function generateSuperAttributesUIDQuery(int $attributeId, int $valueIndex): string
{
return 'selected_options: ["' . $this->selectionUidFormatter->encode($attributeId, $valueIndex) . '"]';
}
/**
* Returns GraphQl query for fetching configurable product information
*
* @param string $term
* @return string
*/
private function getFetchProductQuery(string $term): string
{
return <<<QUERY
{
products(
search:"{$term}"
pageSize:1
) {
items {
sku
uid
... on ConfigurableProduct {
configurable_options {
attribute_id
attribute_uid
attribute_code
id
uid
label
position
product_id
use_default
values {
uid
default_label
label
store_label
use_default_value
value_index
}
}
configurable_product_options_selection {
options_available_for_selection {
attribute_code
option_value_uids
}
configurable_options {
uid
attribute_code
label
values {
uid
is_available
is_use_default
label
}
}
variant {
uid
sku
url_key
url_path
}
media_gallery {
url
label
disabled
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,780 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Exception;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Add configurable product to cart testcases
*/
class AddConfigurableProductToCartTest extends GraphQlAbstract
{
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$quantity = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_20';
$attributeId = (int) $product['configurable_options'][0]['attribute_id'];
$optionId = $product['configurable_options'][0]['values'][1]['value_index'];
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
$quantity
);
$response = $this->graphQlMutation($query);
$cartItem = current($response['addConfigurableProductsToCart']['cart']['items']);
self::assertEquals($quantity, $cartItem['quantity']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertArrayHasKey('configurable_options', $cartItem);
$option = current($cartItem['configurable_options']);
self::assertEquals($attributeId, $option['id']);
self::assertEquals($optionId, $option['value_id']);
self::assertArrayHasKey('option_label', $option);
self::assertArrayHasKey('value_label', $option);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddMultipleConfigurableProductToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$quantityOne = 1;
$quantityTwo = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$skuOne = 'simple_10';
$skuTwo = 'simple_20';
$query = <<<QUERY
mutation {
addConfigurableProductsToCart(input:{
cart_id:"{$maskedQuoteId}"
cart_items:[
{
parent_sku:"{$parentSku}"
data:{
sku:"{$skuOne}"
quantity:{$quantityOne}
}
}
{
parent_sku:"{$parentSku}"
data:{
sku:"{$skuTwo}"
quantity:{$quantityTwo}
}
}
]
}) {
cart {
items {
id
quantity
product {
sku
}
... on ConfigurableCartItem {
configurable_options {
option_label
value_label
value_id
}
configured_variant {
sku
varchar_attribute
}
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$cartItems = $response['addConfigurableProductsToCart']['cart']['items'];
self::assertCount(2, $cartItems);
$firstCartItem = $cartItems[0];
self::assertEquals($quantityOne, $firstCartItem['quantity']);
self::assertEquals('varchar10', $firstCartItem['configured_variant']['varchar_attribute']);
$secondCartItem = $cartItems[1];
self::assertEquals($quantityTwo, $secondCartItem['quantity']);
self::assertEquals('varchar20', $secondCartItem['configured_variant']['varchar_attribute']);
}
/**
* @magentoApiDataFixture Magento/Catalog/_files/configurable_products_with_custom_attribute_layered_navigation.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*
*/
public function testAddVariationFromAnotherConfigurableProductWithTheSameSuperAttributeToCart()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find specified product.');
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable_12345'));
$product = current($searchResponse['products']['items']);
$quantity = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_20';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
$quantity
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_different_super_attribute.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*
*/
public function testAddVariationFromAnotherConfigurableProductWithDifferentSuperAttributeToCart()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find specified product.');
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable_12345'));
$product = current($searchResponse['products']['items']);
$quantity = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_20';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
$quantity
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddProductIfQuantityIsNotAvailable()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The requested qty is not available');
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_20';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
2000
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddNonExistentConfigurableProductParentToCart()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find a product with SKU "configurable_no_exist"');
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = 'configurable_no_exist';
$sku = 'simple_20';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
2000
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote_not_default_website.php
*/
public function testAddConfigurableProductNotAssignedToWebsite()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find a product with SKU "configurable"');
$reservedOrderId = 'test_order_2';
$parentSku = 'configurable';
$sku = 'simple_20';
$headerMap = ['Store' => 'fixture_second_store'];
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId, $parentSku, $sku, 1);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddNonExistentConfigurableProductVariationToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_no_exist';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
2000
);
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'Could not add the product with SKU configurable to the shopping cart: Could not find specified product.'
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_product_only_parent_two_websites.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote_not_default_website.php
*/
public function testAddUnassignedToWebsiteConfigurableProductVariationToCart()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'Could not add the product with SKU configurable to the shopping cart: Could not find specified product.'
);
$reservedOrderId = 'test_order_2';
$parentSku = 'configurable';
$sku = 'simple_20';
$headerMap = ['Store' => 'fixture_second_store'];
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId, $parentSku, $sku, 1);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_disable_first_child.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddDisabledVariationToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_10';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
1
);
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'Could not add the product with SKU configurable to the shopping cart'
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_zero_qty_first_child.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testOutOfStockVariationToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_10';
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
1
);
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'Could not add the product with SKU configurable to the shopping cart'
);
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_custom_option_dropdown.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductToCartWithCustomOption()
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$sku = 'configurable';
$variantSku = 'simple_10';
$productOptions = $this->getAvailableProductCustomOption($sku);
$optionId = $productOptions[0]['option_id'];
$optionValueId = $productOptions[0]['value'][1]['option_type_id'];
$mutation = <<<QUERY
mutation {
addConfigurableProductsToCart(input: {
cart_id: "{$maskedQuoteId}",
cart_items: [
{
parent_sku: "{$sku}",
variant_sku: "{$variantSku}",
data: {
sku: "{$variantSku}",
quantity: 1
},
customizable_options: [
{id: {$optionId}, value_string: "{$optionValueId}"}]
}
]
}) {
cart {
items {
id
quantity
product {
sku
name
}
... on ConfigurableCartItem {
configurable_options {
option_label
value_label
}
customizable_options {
id
label
values{
label
value
}
}
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation($mutation);
$this->assertArrayNotHasKey('errors', $response);
$this->assertCount(1, $response['addConfigurableProductsToCart']['cart']['items']);
$item = $response['addConfigurableProductsToCart']['cart']['items'][0];
$this->assertEquals($sku, $item['product']['sku']);
$expectedOptions = [
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 1'
]
],
'customizable_options' => [
[
'id' => $optionId,
'label' => 'Dropdown Options',
'values' => [
[
'label' => 'Option 2',
'value' => $optionValueId
]
]
]
]
];
$this->assertResponseFields($item['configurable_options'], $expectedOptions['configurable_options']);
$this->assertResponseFields($item['customizable_options'], $expectedOptions['customizable_options']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
* @magentoApiDataFixture Magento/Store/_files/second_store.php
*/
public function testAddConfigurableProductToCartWithDifferentStoreHeader()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$quantity = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSku = $product['sku'];
$sku = 'simple_20';
$attributeId = (int) $product['configurable_options'][0]['attribute_id'];
$optionId = $product['configurable_options'][0]['values'][1]['value_index'];
$query = $this->getQuery(
$maskedQuoteId,
$parentSku,
$sku,
$quantity
);
$headerMap = ['Store' => 'fixture_second_store'];
$response = $this->graphQlMutation($query, [], '', $headerMap);
$cartItem = current($response['addConfigurableProductsToCart']['cart']['items']);
self::assertEquals($quantity, $cartItem['quantity']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertArrayHasKey('configurable_options', $cartItem);
$option = current($cartItem['configurable_options']);
self::assertEquals($attributeId, $option['id']);
self::assertEquals($optionId, $option['value_id']);
self::assertArrayHasKey('option_label', $option);
self::assertArrayHasKey('value_label', $option);
}
/**
* @magentoConfigFixture default_store checkout/cart/configurable_product_image itself
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_child_products_with_images.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductWithImageToCartItselfImage(): void
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$quantity = 1;
$parentSku = $product['sku'];
$sku = 'simple_20';
$query = $this->graphQlQueryForVariant(
$this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'),
$parentSku,
$sku,
$quantity
);
$response = $this->graphQlMutation($query);
$cartItem = current($response['addConfigurableProductsToCart']['cart']['items']);
self::assertEquals($quantity, $cartItem['quantity']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertArrayHasKey('configured_variant', $cartItem);
$variant = $cartItem['configured_variant'];
$expectedThumbnailUrl = 'magento_thumbnail.jpg';
$expectedThumbnailLabel = 'Thumbnail Image';
$variantImage = basename($variant['thumbnail']['url']);
self::assertEquals($expectedThumbnailUrl, $variantImage);
self::assertEquals($expectedThumbnailLabel, $variant['thumbnail']['label']);
self::assertEquals($sku, $variant['sku']);
}
/**
* @magentoConfigFixture default_store checkout/cart/configurable_product_image parent
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_child_products_with_images.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductWithImageToCartParentImage(): void
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$product = current($searchResponse['products']['items']);
$quantity = 1;
$parentSku = $product['sku'];
$sku = 'simple_20';
$query = $this->graphQlQueryForVariant(
$this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'),
$parentSku,
'simple_20',
$quantity
);
$response = $this->graphQlMutation($query);
$cartItem = current($response['addConfigurableProductsToCart']['cart']['items']);
self::assertEquals($quantity, $cartItem['quantity']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertArrayHasKey('configured_variant', $cartItem);
$variant = $cartItem['configured_variant'];
$expectedThumbnailUrl = 'magento_thumbnail.jpg';
$expectedThumbnailLabel = 'Thumbnail Image';
$variantImage = basename($variant['thumbnail']['url']);
self::assertEquals($expectedThumbnailUrl, $variantImage);
self::assertEquals($expectedThumbnailLabel, $variant['thumbnail']['label']);
self::assertEquals($sku, $variant['sku']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
* @magentoApiDataFixture Magento/Store/_files/second_store.php
*/
public function testAddMoreProductsFromAnotherStore()
{
$parentSku = 'configurable';
$sku = 'simple_20';
$quantity = 400; // the number should be greater than the available qty / 3
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$query = $this->getQuery($maskedQuoteId, $parentSku, $sku, $quantity);
$headerMap = ['Store' => 'default'];
$this->graphQlMutation($query, [], '', $headerMap);
$headerMap = ['Store' => 'fixture_second_store'];
$response = $this->graphQlMutation($query, [], '', $headerMap);
self::assertEquals($maskedQuoteId, $response['addConfigurableProductsToCart']['cart']['id']);
$cartItem = current($response['addConfigurableProductsToCart']['cart']['items']);
self::assertEquals($parentSku, $cartItem['product']['sku']);
self::assertEquals($quantity * 2, $cartItem['quantity']);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_in_multiple_websites_disable_first_child.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddConfigurableProductWithDisabledChildToCart(): void
{
$quantity = 1;
$parentSku = 'configurable';
$sku = 'simple_Option_1';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find specified product.');
$query = $this->getQuery($maskedQuoteId, $parentSku, $sku, $quantity);
$headerMap = ['Store' => 'default'];
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @param string $maskedQuoteId
* @param string $parentSku
* @param string $sku
* @param int $quantity
* @return string
*/
private function getQuery(string $maskedQuoteId, string $parentSku, string $sku, int $quantity): string
{
return <<<QUERY
mutation {
addConfigurableProductsToCart(
input:{
cart_id:"{$maskedQuoteId}"
cart_items:{
parent_sku: "{$parentSku}"
data:{
sku:"{$sku}"
quantity:{$quantity}
}
}
}
) {
cart {
id
items {
id
quantity
product {
sku
}
... on ConfigurableCartItem {
configurable_options {
id
option_label
value_id
value_label
}
}
}
}
}
}
QUERY;
}
/**
* @param string $maskedQuoteId
* @param string $parentSku
* @param string $sku
* @param int $quantity
* @return string
*/
private function graphQlQueryForVariant(
string $maskedQuoteId,
string $parentSku,
string $sku,
int $quantity
): string {
return <<<QUERY
mutation {
addConfigurableProductsToCart(
input:{
cart_id:"{$maskedQuoteId}"
cart_items:{
parent_sku: "{$parentSku}"
data:{
sku:"{$sku}"
quantity:{$quantity}
}
}
}
) {
cart {
items {
id
quantity
product {
sku
}
... on ConfigurableCartItem {
configured_variant {
sku
thumbnail {
label
url
}
}
}
}
}
}
}
QUERY;
}
private function getFetchProductQuery(string $term): string
{
return <<<QUERY
{
products(
search:"{$term}"
pageSize:1
) {
items {
sku
... on ConfigurableProduct {
configurable_options {
attribute_id
attribute_code
id
label
position
product_id
use_default
values {
default_label
label
store_label
use_default_value
value_index
}
}
}
}
}
}
QUERY;
}
/**
* Get product customizable dropdown options
*
* @param string $productSku
* @return array
* @throws Exception
*/
private function getAvailableProductCustomOption(string $productSku): array
{
$query = <<<QUERY
{
products(filter: {sku: {eq: "${productSku}"}}) {
items {
name
... on CustomizableProductInterface {
options {
option_id
title
... on CustomizableDropDownOption {
value {
option_type_id
title
}
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertNotEmpty($response['products']['items'], "No result for product with sku: '{$productSku}'");
return $response['products']['items'][0]['options'];
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Exception;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Add configurable product to cart testcases
*/
class AddConfigurableProductsWithDifferentParentsToCartTest extends GraphQlAbstract
{
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products.php
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testAddMultipleConfigurableProductsWithDifferentParentsToCart()
{
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable'));
$productOne = current($searchResponse['products']['items']);
$searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable_12345'));
$productTwo = current($searchResponse['products']['items']);
$quantityOne = 1;
$quantityTwo = 2;
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1');
$parentSkuOne = $productOne['sku'];
$parentSkuTwo = $productTwo['sku'];
$skuOne = 'simple_10';
$skuTwo = 'simple_30';
$query = <<<QUERY
mutation {
addConfigurableProductsToCart(input:{
cart_id:"{$maskedQuoteId}"
cart_items:[
{
parent_sku:"{$parentSkuOne}"
data:{
sku:"{$skuOne}"
quantity:{$quantityOne}
}
}
{
parent_sku:"{$parentSkuTwo}"
data:{
sku:"{$skuTwo}"
quantity:{$quantityTwo}
}
}
]
}) {
cart {
items {
id
quantity
product {
sku
}
... on ConfigurableCartItem {
configurable_options {
option_label
value_label
value_id
}
configured_variant {
sku
varchar_attribute
}
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$cartItems = $response['addConfigurableProductsToCart']['cart']['items'];
self::assertCount(2, $cartItems);
$firstCartItem = $cartItems[0];
self::assertEquals($quantityOne, $firstCartItem['quantity']);
$secondCartItem = $cartItems[1];
self::assertEquals($quantityTwo, $secondCartItem['quantity']);
}
private function getFetchProductQuery(string $sku): string
{
return <<<QUERY
{
products(
filter: {sku: {eq: "$sku"}}
pageSize:1
) {
items {
sku
... on ConfigurableProduct {
configurable_options {
attribute_id
attribute_code
id
label
position
product_id
use_default
values {
default_label
label
store_label
use_default_value
value_index
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,410 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\ConfigurableProductGraphQl\Model\Options\SelectionUidFormatter;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Model\AttributeRepository;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test configurable product option selection.
*/
class ConfigurableOptionsSelectionMetadataTest extends GraphQlAbstract
{
/**
* @var AttributeRepository
*/
private $attributeRepository;
/**
* @var SelectionUidFormatter
*/
private $selectionUidFormatter;
private $firstConfigurableAttribute = null;
private $secondConfigurableAttribute = null;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepository::class);
$this->selectionUidFormatter = Bootstrap::getObjectManager()->create(SelectionUidFormatter::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testWithoutSelectedOption()
{
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: []
) {
options_available_for_selection {
option_value_uids
attribute_code
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertEquals(2, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection']));
$this->assertEquals(4, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][0]['option_value_uids']));
$this->assertEquals(4, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][1]['option_value_uids']));
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testSelectedFirstAttributeFirstOption()
{
$attribute = $this->getFirstConfigurableAttribute();
$options = $attribute->getOptions();
$firstOptionUid = $this->selectionUidFormatter->encode(
(int)$attribute->getAttributeId(),
(int)$options[1]->getValue()
);
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: ["{$firstOptionUid}"]
) {
options_available_for_selection {
option_value_uids
attribute_code
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertEquals(2, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection']));
$this->assertEquals(1, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][0]['option_value_uids']));
$this->assertEquals($firstOptionUid, $response['products']['items'][0]
['configurable_product_options_selection']['options_available_for_selection'][0]['option_value_uids'][0]);
$this->assertEquals(4, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][1]['option_value_uids']));
$secondAttributeOptions = $this->getSecondConfigurableAttribute()->getOptions();
$this->assertAvailableOptionUids(
$this->getSecondConfigurableAttribute()->getAttributeId(),
$secondAttributeOptions,
$response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][1]['option_value_uids']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testSelectedFirstAttributeLastOption()
{
$attribute = $this->getFirstConfigurableAttribute();
$options = $attribute->getOptions();
$lastOptionUid = $this->selectionUidFormatter->encode(
(int)$attribute->getAttributeId(),
(int)$options[4]->getValue()
);
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: ["{$lastOptionUid}"]
) {
options_available_for_selection {
option_value_uids
attribute_code
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertEquals(2, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection']));
$this->assertEquals(1, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][0]['option_value_uids']));
$this->assertEquals($lastOptionUid, $response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][0]['option_value_uids'][0]);
$this->assertEquals(2, count($response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][1]['option_value_uids']));
$secondAttributeOptions = $this->getSecondConfigurableAttribute()->getOptions();
unset($secondAttributeOptions[0]);
unset($secondAttributeOptions[1]);
unset($secondAttributeOptions[2]);
$this->assertAvailableOptionUids(
$this->getSecondConfigurableAttribute()->getAttributeId(),
$secondAttributeOptions,
$response['products']['items'][0]['configurable_product_options_selection']
['options_available_for_selection'][1]['option_value_uids']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testSelectedVariant()
{
$firstAttribute = $this->getFirstConfigurableAttribute();
$firstOptions = $firstAttribute->getOptions();
$firstAttributeFirstOptionUid = $this->selectionUidFormatter->encode(
(int)$firstAttribute->getAttributeId(),
(int)$firstOptions[1]->getValue()
);
$secodnAttribute = $this->getSecondConfigurableAttribute();
$secondOptions = $secodnAttribute->getOptions();
$secondAttributeFirstOptionUid = $this->selectionUidFormatter->encode(
(int)$secodnAttribute->getAttributeId(),
(int)$secondOptions[1]->getValue()
);
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: ["{$firstAttributeFirstOptionUid}", "{$secondAttributeFirstOptionUid}"]
) {
options_available_for_selection {
option_value_uids
}
variant {
id
sku
name
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertNotNull($response['products']['items'][0]['configurable_product_options_selection']
['variant']);
$this->assertEquals(
'simple_' . $firstOptions[1]->getValue() . '_' . $secondOptions[1]->getValue(),
$response['products']['items'][0]['configurable_product_options_selection']
['variant']['sku']
);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testMediaGalleryForAll()
{
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: []
) {
options_available_for_selection {
option_value_uids
attribute_code
}
media_gallery {
url
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertEquals(14, count($response['products']['items'][0]['configurable_product_options_selection']
['media_gallery']));
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testMediaGalleryWithSelection()
{
$attribute = $this->getFirstConfigurableAttribute();
$options = $attribute->getOptions();
$lastOptionUid = $this->selectionUidFormatter->encode(
(int)$attribute->getAttributeId(),
(int)$options[4]->getValue()
);
$query = <<<QUERY
{
products(filter:{
sku: {eq: "configurable_12345"}
})
{
items
{
id
sku
name
description {
html
}
... on ConfigurableProduct {
configurable_product_options_selection(
configurableOptionValueUids: ["$lastOptionUid"]
) {
options_available_for_selection {
option_value_uids
attribute_code
}
media_gallery {
url
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertEquals(1, count($response['products']['items']));
$this->assertEquals(2, count($response['products']['items'][0]['configurable_product_options_selection']
['media_gallery']));
}
/**
* Assert option uid.
*
* @param $attributeId
* @param $expectedOptions
* @param $selectedOptions
*/
private function assertAvailableOptionUids($attributeId, $expectedOptions, $selectedOptions)
{
unset($expectedOptions[0]);
foreach ($expectedOptions as $option) {
$this->assertContains(
$this->selectionUidFormatter->encode((int)$attributeId, (int)$option->getValue()),
$selectedOptions
);
}
}
/**
* Get first configurable attribute.
*
* @return AttributeInterface
* @throws NoSuchEntityException
*/
private function getFirstConfigurableAttribute()
{
if (!$this->firstConfigurableAttribute) {
$attributeCode = 'test_configurable_first';
$this->firstConfigurableAttribute = $this->attributeRepository->get('catalog_product', $attributeCode);
}
return $this->firstConfigurableAttribute;
}
/**
* Get second configurable attribute.
*
* @return AttributeInterface
* @throws NoSuchEntityException
*/
private function getSecondConfigurableAttribute()
{
if (!$this->secondConfigurableAttribute) {
$attributeCode = 'test_configurable_second';
$this->secondConfigurableAttribute = $this->attributeRepository->get('catalog_product', $attributeCode);
}
return $this->secondConfigurableAttribute;
}
}
@@ -0,0 +1,379 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\ConfigurableProductGraphQl\Model\Options\SelectionUidFormatter;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Model\AttributeRepository;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Query\Uid;
use Magento\Indexer\Model\IndexerFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test configurable product option selection.
*/
class ConfigurableOptionsSelectionTest extends GraphQlAbstract
{
/**
* @var AttributeRepository
*/
private $attributeRepository;
/**
* @var SelectionUidFormatter
*/
private $selectionUidFormatter;
/**
* @var IndexerFactory
*/
private $indexerFactory;
/**
* @var Uid
*/
private $idEncoder;
private $firstConfigurableAttribute;
private $secondConfigurableAttribute;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepository::class);
$this->selectionUidFormatter = Bootstrap::getObjectManager()->create(SelectionUidFormatter::class);
$this->indexerFactory = Bootstrap::getObjectManager()->create(IndexerFactory::class);
$this->idEncoder = Bootstrap::getObjectManager()->create(Uid::class);
}
/**
* Test the first option of the first attribute selected
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testSelectedFirstAttributeFirstOption(): void
{
$attribute = $this->getFirstConfigurableAttribute();
$options = $attribute->getOptions();
$sku = 'configurable_12345';
$firstOptionUid = $this->selectionUidFormatter->encode(
(int)$attribute->getAttributeId(),
(int)$options[1]->getValue()
);
$this->reindexAll();
$response = $this->graphQlQuery($this->getQuery($sku, [$firstOptionUid]));
self::assertNotEmpty($response['products']['items']);
$product = current($response['products']['items']);
self::assertEquals('ConfigurableProduct', $product['__typename']);
self::assertEquals($sku, $product['sku']);
self::assertNotEmpty($product['configurable_product_options_selection']['configurable_options']);
self::assertNull($product['configurable_product_options_selection']['variant']);
self::assertCount(1, $product['configurable_product_options_selection']['configurable_options']);
self::assertCount(4, $product['configurable_product_options_selection']['configurable_options'][0]['values']);
$secondAttributeOptions = $this->getSecondConfigurableAttribute()->getOptions();
$this->assertAvailableOptionUids(
$this->getSecondConfigurableAttribute()->getAttributeId(),
$secondAttributeOptions,
$this->getOptionsUids(
$product['configurable_product_options_selection']['configurable_options'][0]['values']
)
);
$this->assertMediaGallery($product);
}
/**
* Test selected variant
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testSelectedVariant(): void
{
$firstAttribute = $this->getFirstConfigurableAttribute();
$firstOptions = $firstAttribute->getOptions();
$firstAttributeFirstOptionUid = $this->selectionUidFormatter->encode(
(int)$firstAttribute->getAttributeId(),
(int)$firstOptions[1]->getValue()
);
$secondAttribute = $this->getSecondConfigurableAttribute();
$secondOptions = $secondAttribute->getOptions();
$secondAttributeFirstOptionUid = $this->selectionUidFormatter->encode(
(int)$secondAttribute->getAttributeId(),
(int)$secondOptions[1]->getValue()
);
$sku = 'configurable_12345';
$this->reindexAll();
$response = $this->graphQlQuery(
$this->getQuery($sku, [$firstAttributeFirstOptionUid, $secondAttributeFirstOptionUid])
);
self::assertNotEmpty($response['products']['items']);
$product = current($response['products']['items']);
self::assertEquals('ConfigurableProduct', $product['__typename']);
self::assertEquals($sku, $product['sku']);
self::assertEmpty($product['configurable_product_options_selection']['configurable_options']);
self::assertNotNull($product['configurable_product_options_selection']['variant']);
$variantId = $this->idEncoder->decode($product['configurable_product_options_selection']['variant']['uid']);
self::assertIsNumeric($variantId);
self::assertIsString($product['configurable_product_options_selection']['variant']['sku']);
$urlKey = 'configurable-option-first-option-1-second-option-1';
self::assertEquals($urlKey, $product['configurable_product_options_selection']['variant']['url_key']);
$this->assertMediaGallery($product);
}
/**
* Test without selected options
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testWithoutSelectedOption(): void
{
$sku = 'configurable_12345';
$this->reindexAll();
$response = $this->graphQlQuery($this->getQuery($sku));
self::assertNotEmpty($response['products']['items']);
$product = current($response['products']['items']);
self::assertEquals('ConfigurableProduct', $product['__typename']);
self::assertEquals($sku, $product['sku']);
self::assertNotEmpty($product['configurable_product_options_selection']['configurable_options']);
self::assertNull($product['configurable_product_options_selection']['variant']);
self::assertCount(2, $product['configurable_product_options_selection']['configurable_options']);
self::assertCount(4, $product['configurable_product_options_selection']['configurable_options'][0]['values']);
self::assertCount(4, $product['configurable_product_options_selection']['configurable_options'][1]['values']);
$firstAttributeOptions = $this->getFirstConfigurableAttribute()->getOptions();
$this->assertAvailableOptionUids(
$this->getFirstConfigurableAttribute()->getAttributeId(),
$firstAttributeOptions,
$this->getOptionsUids(
$product['configurable_product_options_selection']['configurable_options'][0]['values']
)
);
$secondAttributeOptions = $this->getSecondConfigurableAttribute()->getOptions();
$this->assertAvailableOptionUids(
$this->getSecondConfigurableAttribute()->getAttributeId(),
$secondAttributeOptions,
$this->getOptionsUids(
$product['configurable_product_options_selection']['configurable_options'][1]['values']
)
);
$this->assertMediaGallery($product);
}
/**
* Test with wrong selected options
*
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes_combination.php
*/
public function testWithWrongSelectedOptions(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('configurableOptionValueUids values are incorrect');
$attribute = $this->getFirstConfigurableAttribute();
$options = $attribute->getOptions();
$sku = 'configurable_12345';
$firstOptionUid = $this->selectionUidFormatter->encode(
(int)$attribute->getAttributeId(),
$options[1]->getValue() + 100
);
$this->reindexAll();
$this->graphQlQuery($this->getQuery($sku, [$firstOptionUid]));
}
/**
* Get GraphQL query to test configurable product options selection
*
* @param string $productSku
* @param array $optionValueUids
* @param int $pageSize
* @param int $currentPage
* @return string
*/
private function getQuery(
string $productSku,
array $optionValueUids = [],
int $pageSize = 20,
int $currentPage = 1
): string {
if (empty($optionValueUids)) {
$configurableOptionValueUids = '';
} else {
$configurableOptionValueUids = '(configurableOptionValueUids: [';
foreach ($optionValueUids as $configurableOptionValueUid) {
$configurableOptionValueUids .= '"' . $configurableOptionValueUid . '",';
}
$configurableOptionValueUids .= '])';
}
return <<<QUERY
{
products(filter:{
sku: {eq: "{$productSku}"}
},
pageSize: {$pageSize}, currentPage: {$currentPage}
)
{
items {
__typename
sku
... on ConfigurableProduct {
configurable_product_options_selection {$configurableOptionValueUids} {
configurable_options {
uid
attribute_code
label
values {
uid
is_available
is_use_default
label
swatch {
value
}
}
}
variant {
uid
sku
url_key
}
media_gallery {
url
label
disabled
}
}
}
}
}
}
QUERY;
}
/**
* Get first configurable attribute.
*
* @return AttributeInterface
* @throws NoSuchEntityException
*/
private function getFirstConfigurableAttribute(): AttributeInterface
{
if (!$this->firstConfigurableAttribute) {
$this->firstConfigurableAttribute = $this->attributeRepository->get(
'catalog_product',
'test_configurable_first'
);
}
return $this->firstConfigurableAttribute;
}
/**
* Get second configurable attribute.
*
* @return AttributeInterface
* @throws NoSuchEntityException
*/
private function getSecondConfigurableAttribute(): AttributeInterface
{
if (!$this->secondConfigurableAttribute) {
$this->secondConfigurableAttribute = $this->attributeRepository->get(
'catalog_product',
'test_configurable_second'
);
}
return $this->secondConfigurableAttribute;
}
/**
* Assert option uid.
*
* @param $attributeId
* @param $expectedOptions
* @param $selectedOptions
*/
private function assertAvailableOptionUids($attributeId, $expectedOptions, $selectedOptions): void
{
unset($expectedOptions[0]);
foreach ($expectedOptions as $option) {
self::assertContains(
$this->selectionUidFormatter->encode((int)$attributeId, (int)$option->getValue()),
$selectedOptions
);
}
}
/**
* Make fulltext catalog search reindex
*
* @return void
* @throws \Throwable
*/
private function reindexAll(): void
{
$indexLists = [
'catalog_category_product',
'catalog_product_attribute',
'cataloginventory_stock',
'catalogsearch_fulltext',
];
foreach ($indexLists as $indexerId) {
$indexer = $this->indexerFactory->create();
$indexer->load($indexerId)->reindexAll();
}
}
/**
* Retrieve options UIDs
*
* @param array $options
* @return array
*/
private function getOptionsUids(array $options): array
{
$uids = [];
foreach ($options as $option) {
$uids[] = $option['uid'];
}
return $uids;
}
/**
* Assert media gallery fields
*
* @param array $product
*/
private function assertMediaGallery(array $product): void
{
self::assertNotEmpty($product['configurable_product_options_selection']['media_gallery']);
$image = current($product['configurable_product_options_selection']['media_gallery']);
self::assertIsString($image['url']);
self::assertEquals(false, $image['disabled']);
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Checks disabled child product is not in configurable variants.
*/
class ConfigurableProductChildStatusDisabledTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_disable_first_child.php
* @magentoConfigFixture default_store cataloginventory/options/show_out_of_stock 1
*/
public function testConfigurableProductChildStatusDisabled()
{
$parentSku = 'configurable';
$enabledChildSku = 'simple_20';
$disabledChildSku = 'simple_10';
$query = $this->getQuery($parentSku);
$response = $this->graphQlQuery($query);
$this->assertContainsEquals(
['product' => ['sku' => $enabledChildSku, 'stock_status' => 'IN_STOCK']],
$response['products']['items'][0]['variants']
);
$this->assertNotContainsEquals(
['product' => ['sku' => $disabledChildSku, 'stock_status' => 'OUT_OF_STOCK']],
$response['products']['items'][0]['variants']
);
}
/**
* @param string $sku
* @return string
*/
private function getQuery(string $sku)
{
return <<<QUERY
{
products(filter: {sku: {eq: "{$sku}"}})
{
items {
sku
... on ConfigurableProduct {
variants {
product {
sku
stock_status
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,56 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Class ConfigurableProductFrontendLabelAttributeTest
*
* @package Magento\GraphQl\ConfigurableProduct
*/
class ConfigurableProductFrontendLabelAttributeTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_frontend_label_attribute.php
*/
public function testGetFrontendLabelAttribute()
{
$expectLabelValue = 'Default Store View label';
$productSku = 'configurable';
$query = <<<QUERY
{
products(filter: {sku: {eq: "{$productSku}"}}) {
items {
name
... on ConfigurableProduct{
configurable_options{
id
label
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertArrayHasKey('products', $response);
$this->assertArrayHasKey('items', $response['products']);
$this->assertArrayHasKey(0, $response['products']['items']);
$product = $response['products']['items'][0];
$this->assertArrayHasKey('configurable_options', $product);
$this->assertArrayHasKey(0, $product['configurable_options']);
$this->assertArrayHasKey('label', $product['configurable_options'][0]);
$option = $product['configurable_options'][0];
$this->assertEquals($expectLabelValue, $option['label']);
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test configurable product queries work correctly with multiple websites
*/
class ConfigurableProductMultipleStoreViewTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_in_multiple_websites.php
*/
public function testConfigurableProductAssignedToOneWebsite()
{
$headerMapFirstStore['Store'] = 'default';
$headerMapSecondStore['Store'] = 'fixture_second_store';
$parentSku = 'configurable';
$query = $this->getQuery($parentSku);
$responseForFirstWebsite = $this->graphQlQuery($query, [], '', $headerMapFirstStore);
$responseForSecondWebsite = $this->graphQlQuery($query, [], '', $headerMapSecondStore);
$secondWebsiteVariants = $responseForSecondWebsite['products']['items'][0]['variants'];
self::assertEmpty($responseForFirstWebsite['products']['items']);
self::assertEquals(2, count($secondWebsiteVariants));
self::assertContains('simple_10', $secondWebsiteVariants[0]['product']);
self::assertContains('Option 1', $secondWebsiteVariants[0]['attributes'][0]);
self::assertContains('simple_20', $secondWebsiteVariants[1]['product']);
self::assertContains('Option 2', $secondWebsiteVariants[1]['attributes'][0]);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_children_on_different_websites.php
* @dataProvider childrenAssignedToDifferentWebsitesDataProvider
* @param string $store
* @param string $childSku
* @param string $attributeLabel
*/
public function testConfigurableProductWithChildrenAssignedToDifferentWebsites(
string $store,
string $childSku,
string $attributeLabel
) {
$headers = ['Store' => $store];
$query = $this->getQuery('configurable');
$response = $this->graphQlQuery($query, [], '', $headers);
self::assertCount(1, $response['products']['items']);
$product = $response['products']['items'][0];
self::assertCount(1, $product['variants']);
$variant = $response['products']['items'][0]['variants'][0];
self::assertEquals($childSku, $variant['product']['sku']);
self::assertCount(1, $variant['attributes']);
$attribute = $variant['attributes'][0];
self::assertEquals($attributeLabel, $attribute['label']);
}
/**
* @return array
*/
public function childrenAssignedToDifferentWebsitesDataProvider(): array
{
return [
['default', 'simple_option_2', 'Option 2'],
['fixture_second_store', 'simple_option_1', 'Option 1'],
];
}
/**
* @param string $sku
* @return string
*/
private function getQuery(string $sku)
{
return <<<QUERY
{
products(filter: {sku: {eq: "{$sku}"}})
{
items {
sku
... on ConfigurableProduct {
variants {
product {
sku
stock_status
}
attributes {
code
label
value_index
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,243 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test products query for configurable product options
*/
class ConfigurableProductOptionsTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_two_attributes.php
* @dataProvider expectedResultDataProvider
* @param $expectedOptions
* @throws \Exception
*/
public function testQueryConfigurableProductLinks($expectedOptions)
{
$configurableProduct = 'configurable';
$query = $this->getQuery($configurableProduct);
$response = $this->graphQlQuery($query);
$this->assertArrayHasKey('products', $response);
$this->assertArrayHasKey('items', $response['products']);
$this->assertConfigurableProductOptions($response['products']['items'], $expectedOptions);
}
/**
* @param $actualResponse
* @param $expectedOptions
*/
private function assertConfigurableProductOptions($actualResponse, $expectedOptions)
{
$this->assertCount(2, $actualResponse);
foreach ($actualResponse as $responseProduct) {
$this->assertNotEmpty(
$responseProduct['configurable_options'],
"Precondition failed: 'configurable_options' must not be empty"
);
$expectedProductOptions = $expectedOptions[$responseProduct['sku']];
foreach ($expectedProductOptions['configurable_options'] as $optionIndex => $expectedProductOption) {
$responseProductOption = $responseProduct['configurable_options'][$optionIndex];
$this->assertEquals(
$expectedProductOption['use_default'],
$responseProductOption['use_default']
);
$this->assertEquals(
$expectedProductOption['label'],
$responseProductOption['label']
);
$this->assertEquals(
$expectedProductOption['position'],
$responseProductOption['position']
);
$this->assertEquals(
$expectedProductOption['attribute_code'],
$responseProductOption['attribute_code']
);
$optionValuesCount = 2;
self::assertCount(
$optionValuesCount,
$responseProductOption['values'],
'Product option values count in response is different with real option values'
);
foreach ($expectedProductOption['values'] as $key => $value) {
$responseProductOptionValue = $responseProductOption['values'][$key];
$this->assertEquals(
$value['label'],
$responseProductOptionValue['label']
);
$this->assertEquals(
$value['store_label'],
$responseProductOptionValue['store_label']
);
$this->assertEquals(
$value['default_label'],
$responseProductOptionValue['default_label']
);
$this->assertEquals(
$value['use_default_value'],
$responseProductOptionValue['use_default_value']
);
}
}
}
}
/**
* @param string $configurableProduct
* @return string
*/
private function getQuery($configurableProduct)
{
return <<<QUERY
{
products(filter: {name: {match: "$configurableProduct"}}) {
items {
id
sku
... on ConfigurableProduct {
configurable_options {
id
attribute_id
label
position
use_default
attribute_code
values {
value_index
label
store_label
default_label
use_default_value
}
product_id
}
}
}
}
}
QUERY;
}
/**
* @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function expectedResultDataProvider()
{
return [
[
[
'configurable_12345' =>
[
'sku' => 'configurable_12345',
'configurable_options' =>
[
[
'label' => 'Test Configurable First',
'position' => 0,
'use_default' => false,
'attribute_code' => 'test_configurable_first',
'values' =>
[
[
'label' => 'First Option 3',
'store_label' => 'First Option 3',
'default_label' => 'First Option 3',
'use_default_value' => true,
],
[
'label' => 'First Option 4',
'store_label' => 'First Option 4',
'default_label' => 'First Option 4',
'use_default_value' => true,
],
],
],
[
'label' => 'Test Configurable Second',
'position' => 1,
'use_default' => false,
'attribute_code' => 'test_configurable_second',
'values' =>
[
[
'label' => 'Second Option 3',
'store_label' => 'Second Option 3',
'default_label' => 'Second Option 3',
'use_default_value' => true,
],
[
'label' => 'Second Option 4',
'store_label' => 'Second Option 4',
'default_label' => 'Second Option 4',
'use_default_value' => true,
],
],
],
],
],
'configurable' =>
[
'sku' => 'configurable',
'configurable_options' =>
[
[
'label' => 'Test Configurable First',
'position' => 0,
'use_default' => false,
'attribute_code' => 'test_configurable_first',
'values' =>
[
[
'label' => 'First Option 1',
'store_label' => 'First Option 1',
'default_label' => 'First Option 1',
'use_default_value' => true,
],
[
'label' => 'First Option 2',
'store_label' => 'First Option 2',
'default_label' => 'First Option 2',
'use_default_value' => true,
],
],
],
[
'label' => 'Test Configurable Second',
'position' => 1,
'use_default' => false,
'attribute_code' => 'test_configurable_second',
'values' =>
[
[
'label' => 'Second Option 1',
'store_label' => 'Second Option 1',
'default_label' => 'Second Option 1',
'use_default_value' => true,
],
[
'label' => 'Second Option 2',
'store_label' => 'Second Option 2',
'default_label' => 'Second Option 2',
'use_default_value' => true,
],
],
],
],
]
]
]
];
}
}
@@ -0,0 +1,85 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Checks the price range of configurable products with disabled child products.
*/
class ConfigurableProductPriceRangeWithDisabledChildProductsTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_disable_first_child.php
*/
public function testConfigurableProductPriceRangeWithDisabledChildProducts(): void
{
$parentSku = 'configurable';
$enabledChildSku = 'simple_20';
$disabledChildSku = 'simple_10';
$enabledChildPrice = 20;
$response = $this->graphQlQuery($this->getQuery($parentSku));
$this->assertEquals(
$enabledChildPrice,
$response['products']['items'][0]['price_range']['minimum_price']['final_price']['value']
);
$this->assertEquals(
$enabledChildPrice,
$response['products']['items'][0]['price_range']['minimum_price']['regular_price']['value']
);
$this->assertContainsEquals(
['product' => ['sku' => $enabledChildSku]],
$response['products']['items'][0]['variants']
);
$this->assertNotContainsEquals(
['product' => ['sku' => $disabledChildSku]],
$response['products']['items'][0]['variants']
);
}
/**
* @param string $sku
* @return string
*/
private function getQuery(string $sku): string
{
return <<<QUERY
{
products(filter: {sku: {eq: "{$sku}"}})
{
items {
sku
price_range {
minimum_price {
discount {
amount_off
percent_off
}
final_price {
value
currency
}
regular_price {
value
currency
}
}
}
...on ConfigurableProduct {
variants {
product {
sku
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test configurable product queries work correctly
*/
class ConfigurableProductQueryTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*/
public function testNonVisibleVariationsNotReturned()
{
$categoryId = '2';
$query = <<<QUERY
{
products(filter: {category_id: {eq: "{$categoryId}"}}) {
items {
__typename
sku
name
url_key
price {
regularPrice {
amount {
currency
value
}
}
}
media_gallery_entries {
media_type
label
position
file
id
types
}
description {
html
}
}
}
}
QUERY;
$result = $this->graphQlQuery($query);
$products = $result['products']['items'];
$this->assertCount(1, $products);
$this->assertEquals('ConfigurableProduct', $products[0]['__typename']);
$this->assertEquals('configurable', $products[0]['sku']);
$this->assertArrayHasKey('media_gallery_entries', $products[0]);
}
}
@@ -0,0 +1,95 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\CatalogInventory\Api\StockRegistryInterface;
/**
* Checks if stock status correctly displays for configurable variants.
*/
class ConfigurableProductStockStatusTest extends GraphQlAbstract
{
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->stockRegistry = Bootstrap::getObjectManager()->create(StockRegistryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Framework/Search/_files/product_configurable.php
* @magentoConfigFixture default_store cataloginventory/options/show_out_of_stock 1
*/
public function testConfigurableProductShowOutOfStock()
{
$parentSku = 'configurable';
$childSkuOutOfStock = 'simple_1010';
$stockItem = $this->stockRegistry->getStockItemBySku($childSkuOutOfStock);
$stockItem->setQty(0);
$this->stockRegistry->updateStockItemBySku($childSkuOutOfStock, $stockItem);
$query = $this->getQuery($parentSku);
$response = $this->graphQlQuery($query);
$this->assertContainsEquals(
['product' => ['sku' => $childSkuOutOfStock, 'stock_status' => 'OUT_OF_STOCK']],
$response['products']['items'][0]['variants']
);
}
/**
* @magentoApiDataFixture Magento/Framework/Search/_files/product_configurable.php
* @magentoConfigFixture default_store cataloginventory/options/show_out_of_stock 0
*/
public function testConfigurableProductDoNotShowOutOfStock()
{
$parentSku = 'configurable';
$childSkuOutOfStock = 'simple_1010';
$stockItem = $this->stockRegistry->getStockItemBySku($childSkuOutOfStock);
$stockItem->setQty(0);
$this->stockRegistry->updateStockItemBySku($childSkuOutOfStock, $stockItem);
$query = $this->getQuery($parentSku);
$response = $this->graphQlQuery($query);
$this->assertEquals(
[['product' => ['sku' => 'simple_1020', 'stock_status' => 'IN_STOCK']]],
$response['products']['items'][0]['variants']
);
}
/**
* @param string $sku
* @return string
*/
private function getQuery(string $sku)
{
return <<<QUERY
{
products(filter: {sku: {eq: "{$sku}"}})
{
items {
sku
... on ConfigurableProduct {
variants {
product {
sku
stock_status
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,507 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Catalog\Pricing\Price\RegularPrice;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test products query for configurable products
*/
class ConfigurableProductViewTest extends GraphQlAbstract
{
/**
* @var array
*/
private $configurableOptions = [];
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_category_and_weight.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testQueryConfigurableProductLinks()
{
$productSku = 'configurable';
$query
= <<<QUERY
{
products(filter: {sku: {eq: "{$productSku}"}}) {
items {
id
name
sku
type_id
... on PhysicalProductInterface {
weight
}
price {
minimalPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
maximalPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
regularPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
}
... on ConfigurableProduct {
configurable_options {
id
attribute_id
attribute_id_v2
label
position
use_default
attribute_code
values {
value_index
label
store_label
default_label
use_default_value
}
product_id
}
variants {
product {
id
name
sku
... on PhysicalProductInterface {
weight
}
price {
minimalPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
maximalPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
regularPrice {
amount {
value
currency
}
adjustments {
amount {
value
currency
}
code
description
}
}
}
categories {
id
}
media_gallery_entries {
disabled
file
id
label
media_type
position
types
content {
base64_encoded_data
type
name
}
video_content {
media_type
video_description
video_metadata
video_provider
video_title
video_url
}
}
}
attributes {
label
code
value_index
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
/**
* @var ProductRepositoryInterface $productRepository
*/
$productRepository = ObjectManager::getInstance()->get(ProductRepositoryInterface::class);
$product = $productRepository->get($productSku, false, null, true);
$this->assertArrayHasKey('products', $response);
$this->assertArrayHasKey('items', $response['products']);
$this->assertCount(1, $response['products']['items']);
$this->assertArrayHasKey(0, $response['products']['items']);
$this->assertBaseFields($product, $response['products']['items'][0]);
$this->assertConfigurableProductOptions($response['products']['items'][0]);
$this->assertConfigurableVariants($response['products']['items'][0]);
}
/**
* @param ProductInterface $product
* @param array $actualResponse
*/
private function assertBaseFields($product, $actualResponse)
{
/** @var \Magento\Framework\Pricing\PriceInfo\Factory $priceInfoFactory */
$priceInfoFactory = ObjectManager::getInstance()->get(\Magento\Framework\Pricing\PriceInfo\Factory::class);
$priceInfo = $priceInfoFactory->create($product);
/** @var \Magento\Catalog\Pricing\Price\FinalPriceInterface $finalPrice */
$finalPrice = $priceInfo->getPrice(FinalPrice::PRICE_CODE);
$minimalPriceAmount = $finalPrice->getMinimalPrice();
$maximalPriceAmount = $finalPrice->getMaximalPrice();
$regularPriceAmount = $priceInfo->getPrice(RegularPrice::PRICE_CODE)->getAmount();
/** @var MetadataPool $metadataPool */
$metadataPool = ObjectManager::getInstance()->get(MetadataPool::class);
$assertionMap = [
[
'response_field' => 'id',
'expected_value' => $product->getData(
$metadataPool->getMetadata(
ProductInterface::class
)->getIdentifierField()
)
],
['response_field' => 'name', 'expected_value' => $product->getName()],
['response_field' => 'sku', 'expected_value' => $product->getSku()],
['response_field' => 'type_id', 'expected_value' => $product->getTypeId()],
['response_field' => 'weight', 'expected_value' => $product->getWeight()],
[
'response_field' => 'price',
'expected_value' => [
'minimalPrice' => [
'amount' => [
'value' => $minimalPriceAmount->getValue(),
'currency' => 'USD'
],
'adjustments' => []
],
'regularPrice' => [
'amount' => [
'value' => $maximalPriceAmount->getValue(),
'currency' => 'USD'
],
'adjustments' => []
],
'maximalPrice' => [
'amount' => [
'value' => $regularPriceAmount->getValue(),
'currency' => 'USD'
],
'adjustments' => []
],
]
],
];
$this->assertResponseFields($actualResponse, $assertionMap);
}
/**
* Asserts various fields for child products for a configurable products
*
* @param $actualResponse
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function assertConfigurableVariants($actualResponse)
{
$this->assertNotEmpty(
$actualResponse['variants'],
"Precondition failed: 'variants' must not be empty"
);
foreach ($actualResponse['variants'] as $variantKey => $variantArray) {
$this->assertNotEmpty($variantArray);
$this->assertNotEmpty($variantArray['product']);
$this->assertTrue(
isset($variantArray['product']['id']),
'variant product elements don\'t contain id key'
);
$variantProductId = $variantArray['product']['id'];
$indexValue = $variantArray['product']['sku'];
unset($variantArray['product']['id']);
$this->assertTrue(
isset($variantArray['product']['categories']),
'variant product doesn\'t contain categories key'
);
$productRepository = ObjectManager::getInstance()->get(ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Model\Product $childProduct */
$childProduct = $productRepository->get($indexValue);
switch ($variantProductId) {
case 10:
$this->assertEmpty(
$actualResponse['variants'][$variantKey]['product']['categories'],
'No category is expected for product, that not visible individually'
);
break;
case 20:
$this->assertEquals(
$actualResponse['variants'][$variantKey]['product']['categories'][0],
['id' => 333]
);
break;
}
unset($variantArray['product']['categories']);
$mediaGalleryEntries = $childProduct->getMediaGalleryEntries();
$this->assertCount(
1,
$mediaGalleryEntries,
"Precondition failed since there are incorrect number of media gallery entries"
);
$this->assertIsArray($actualResponse['variants'][$variantKey]['product']['media_gallery_entries']);
$this->assertCount(
1,
$actualResponse['variants'][$variantKey]['product']['media_gallery_entries'],
"there must be 1 record in the media gallery"
);
$mediaGalleryEntry = $mediaGalleryEntries[0];
$this->assertResponseFields(
$actualResponse['variants'][$variantKey]['product']['media_gallery_entries'][0],
[
'disabled' => (bool)$mediaGalleryEntry->isDisabled(),
'file' => $mediaGalleryEntry->getFile(),
'id' => $mediaGalleryEntry->getId(),
'label' => $mediaGalleryEntry->getLabel(),
'media_type' => $mediaGalleryEntry->getMediaType(),
'position' => $mediaGalleryEntry->getPosition()
]
);
$videoContent = $mediaGalleryEntry->getExtensionAttributes()->getVideoContent();
$this->assertResponseFields(
$actualResponse['variants'][$variantKey]['product']['media_gallery_entries'][0]['video_content'],
[
'media_type' =>$videoContent->getMediaType(),
'video_description' => $videoContent->getVideoDescription(),
'video_metadata' =>$videoContent->getVideoMetadata(),
'video_provider' => $videoContent->getVideoProvider(),
'video_title' => $videoContent->getVideoTitle(),
'video_url' => $videoContent->getVideoUrl()
]
);
unset($variantArray['product']['media_gallery_entries']);
foreach ($variantArray['product'] as $key => $value) {
if ($key !== 'price') {
$this->assertEquals($value, $childProduct->getData($key));
}
}
//assert prices
$this->assertEquals(
[
'minimalPrice' => [
'amount' => [
'value' => $childProduct->getFinalPrice(),
'currency' => 'USD'
],
'adjustments' => []
],
'regularPrice' => [
'amount' => [
'value' => $childProduct->getFinalPrice(),
'currency' => 'USD'
],
'adjustments' => []
],
'maximalPrice' => [
'amount' => [
'value' => $childProduct->getFinalPrice(),
'currency' => 'USD'
],
'adjustments' => []
],
],
$variantArray['product']['price']
);
$configurableOptions = $this->getConfigurableOptions();
$this->assertCount(1, $variantArray['attributes']);
foreach ($variantArray['attributes'] as $attribute) {
$hasAssertion = false;
foreach ($configurableOptions as $option) {
foreach ($option['options'] as $value) {
if ((int)$value['value_index'] === (int)$attribute['value_index']) {
$this->assertEquals((int)$attribute['value_index'], (int)$value['value_index']);
$this->assertEquals($attribute['label'], $value['label']);
$hasAssertion = true;
}
}
$this->assertEquals($attribute['code'], $option['attribute_code']);
}
if (!$hasAssertion) {
$this->fail('variant did not contain correct attributes');
}
}
}
}
private function assertConfigurableProductOptions($actualResponse)
{
$this->assertNotEmpty(
$actualResponse['configurable_options'],
"Precondition failed: 'configurable_options' must not be empty"
);
$configurableAttributeOptions = $this->getConfigurableOptions();
$configurableAttributeOption = array_shift($configurableAttributeOptions);
$this->assertEquals(
$actualResponse['configurable_options'][0]['id'],
$configurableAttributeOption['id']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['use_default'],
(bool)$configurableAttributeOption['use_default']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['attribute_id'],
$configurableAttributeOption['attribute_id']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['attribute_id_v2'],
$configurableAttributeOption['attribute_id']
);
$this->assertIsInt($actualResponse['configurable_options'][0]['attribute_id_v2']);
$this->assertEquals(
$actualResponse['configurable_options'][0]['label'],
$configurableAttributeOption['label']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['position'],
$configurableAttributeOption['position']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['product_id'],
$configurableAttributeOption['product_id']
);
$this->assertEquals(
$actualResponse['configurable_options'][0]['attribute_code'],
$configurableAttributeOption['attribute_code']
);
foreach ($actualResponse['configurable_options'][0]['values'] as $key => $value) {
$this->assertEquals(
$value['label'],
$configurableAttributeOption['options'][$key]['label']
);
$this->assertEquals(
$value['store_label'],
$configurableAttributeOption['options'][$key]['store_label']
);
$this->assertEquals(
$value['default_label'],
$configurableAttributeOption['options'][$key]['default_label']
);
$this->assertEquals(
$value['use_default_value'],
$configurableAttributeOption['options'][$key]['use_default_value']
);
$this->assertEquals(
(int)$value['value_index'],
(int)$configurableAttributeOption['options'][$key]['value_index']
);
}
}
private function getConfigurableOptions()
{
if (!empty($this->configurableOptions)) {
return $this->configurableOptions;
}
$productSku = 'configurable';
/** @var ProductRepositoryInterface $productRepo */
$productRepo = ObjectManager::getInstance()->get(ProductRepositoryInterface::class);
$product = $productRepo->get($productSku);
$configurableAttributeOptions = $product->getExtensionAttributes()->getConfigurableProductOptions();
$configurableAttributeOptionsData = [];
foreach ($configurableAttributeOptions as $option) {
$configurableAttributeOptionsData[$option->getId()] = $option->getData();
$configurableAttributeOptionsData[$option->getId()]['id'] = $option->getId();
$configurableAttributeOptionsData[$option->getId()]['attribute_code']
= $option->getProductAttribute()->getAttributeCode();
unset($configurableAttributeOptionsData[$option->getId()]['values']);
foreach ($option->getValues() as $value) {
$configurableAttributeOptionsData[$option->getId()]['values'][$value->getId()] = $value->getData();
$configurableAttributeOptionsData[$option->getId()]['values'][$value->getId()]['label']
= $value->getLabel();
}
}
return $this->configurableOptions = $configurableAttributeOptionsData;
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct\Options\Uid;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\ResourceModel\Entity\Attribute;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for downloadable product links uid
*/
class CustomizableValueUidTest extends GraphQlAbstract
{
/**
* @var Attribute
*/
private $eavAttribute;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->eavAttribute = $objectManager->get(Attribute::class);
}
/**
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_one_simple.php
*/
public function testQueryUidForConfigurableSuperAttributes()
{
$productSku = 'configurable';
$query = $this->getQuery($productSku);
$response = $this->graphQlQuery($query);
$responseProduct = $response['products']['items'][0];
self::assertNotEmpty($responseProduct['variants']);
foreach ($responseProduct['variants'] as $variant) {
self::assertNotEmpty($variant['attributes']);
foreach ($variant['attributes'] as $attribute) {
$attributeId = (int) $this->eavAttribute->getIdByCode(Product::ENTITY, $attribute['code']);
$uid = $this->getUidByOptionIds($attributeId, $attribute['value_index']);
self::assertEquals($uid, $attribute['uid']);
}
}
}
/**
* Get Uid
*
* @param int $optionId
* @param int $optionValueId
*
* @return string
*/
private function getUidByOptionIds(int $optionId, int $optionValueId): string
{
return base64_encode('configurable/' . $optionId . '/' . $optionValueId);
}
/**
* Get query
*
* @param string $sku
*
* @return string
*/
private function getQuery(string $sku): string
{
return <<<QUERY
query {
products(filter: { sku: { eq: "$sku" } }) {
items {
... on ConfigurableProduct {
variants {
attributes {
uid
code
value_index
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,139 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\QuoteFactory;
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Remove configurable product from cart testcases
*/
class RemoveConfigurableProductFromCartTest extends GraphQlAbstract
{
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var QuoteFactory
*/
private $quoteFactory;
/**
* @var QuoteResource
*/
private $quoteResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
$this->quoteFactory = $objectManager->get(QuoteFactory::class);
$this->quoteResource = $objectManager->get(QuoteResource::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
/**
* @param string $itemArgName
* @param string $reservedOrderId
* @dataProvider removeConfigurableProductFromCartDataProvider
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testRemoveConfigurableProductFromCart(string $itemArgName, string $reservedOrderId)
{
$configurableOptionSku = 'simple_10';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$quoteItemId = $this->getQuoteItemIdBySku($configurableOptionSku);
if ($itemArgName === 'cart_item_uid') {
$quoteItemId = base64_encode($quoteItemId);
}
$query = $this->getQuery($itemArgName, $maskedQuoteId, $quoteItemId);
$response = $this->graphQlMutation($query);
$this->assertArrayHasKey('cart', $response['removeItemFromCart']);
$this->assertArrayHasKey('items', $response['removeItemFromCart']['cart']);
$this->assertCount(0, $response['removeItemFromCart']['cart']['items']);
}
/**
* Data provider for testUpdateConfigurableCartItemQuantity
*
* @return array
*/
public function removeConfigurableProductFromCartDataProvider(): array
{
return [
['cart_item_id', 'test_cart_with_configurable'],
['cart_item_uid', 'test_cart_with_configurable'],
];
}
/**
* @param string $itemArgName
* @param string $maskedQuoteId
* @param string $itemId
* @return string
*/
private function getQuery(string $itemArgName, string $maskedQuoteId, string $itemId): string
{
if (is_numeric($itemId)) {
$itemId = (int) $itemId;
} else {
$itemId = '"' . $itemId . '"';
}
return <<<QUERY
mutation {
removeItemFromCart(
input: {
cart_id: "{$maskedQuoteId}"
{$itemArgName}: {$itemId}
}
) {
cart {
items {
quantity
}
}
}
}
QUERY;
}
/**
* Returns quote item ID by product's SKU
*
* @param string $sku
* @return string
*/
private function getQuoteItemIdBySku(string $sku): string
{
$quote = $this->quoteFactory->create();
$this->quoteResource->load($quote, 'test_cart_with_configurable', 'reserved_order_id');
/** @var Item $quoteItem */
$quoteItemsCollection = $quote->getItemsCollection();
foreach ($quoteItemsCollection->getItems() as $item) {
if ($item->getSku() == $sku) {
return $item->getId();
}
}
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Exception;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Class for Store Config Configurable Product Image settings
*/
class StoreConfigTest extends GraphQlAbstract
{
/**
* Check type of configurable_thumbnail_source storeConfig configurable_thumbnail_source
*
* @magentoConfigFixture default_store checkout/cart/configurable_product_image itself
*
* @throws Exception
*/
public function testReturnTypeAutocompleteOnStorefrontConfig()
{
$query = <<<QUERY
{
storeConfig {
configurable_thumbnail_source
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('configurable_thumbnail_source', $response['storeConfig']);
self::assertEquals('itself', $response['storeConfig']['configurable_thumbnail_source']);
}
}
@@ -0,0 +1,152 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\ConfigurableProduct;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\QuoteFactory;
use Magento\Quote\Model\QuoteIdMaskFactory;
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* checks that qty of configurable product is updated in cart
*/
class UpdateConfigurableCartItemsTest extends GraphQlAbstract
{
/**
* @var QuoteIdMaskFactory
*/
protected $quoteIdMaskFactory;
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @var QuoteFactory
*/
private $quoteFactory;
/**
* @var QuoteResource
*/
private $quoteResource;
/**
* @param string $itemArgName
* @param string $reservedOrderId
* @dataProvider updateConfigurableCartItemQuantityDataProvider
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php
*/
public function testUpdateConfigurableCartItemQuantity(string $itemArgName, string $reservedOrderId)
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$productSku = 'simple_10';
$newQuantity = 123;
$quoteItemId = $this->getQuoteItemBySku($productSku, $reservedOrderId)->getId();
if ($itemArgName === 'cart_item_uid') {
$quoteItemId = base64_encode($quoteItemId);
}
$query = $this->getQuery($itemArgName, $maskedQuoteId, $quoteItemId, $newQuantity);
$response = $this->graphQlMutation($query);
self::assertArrayHasKey('updateCartItems', $response);
self::assertArrayHasKey('quantity', $response['updateCartItems']['cart']['items']['0']);
self::assertEquals($newQuantity, $response['updateCartItems']['cart']['items']['0']['quantity']);
}
/**
* Data provider for testUpdateConfigurableCartItemQuantity
*
* @return array
*/
public function updateConfigurableCartItemQuantityDataProvider(): array
{
return [
['cart_item_id', 'test_cart_with_configurable'],
['cart_item_uid', 'test_cart_with_configurable'],
];
}
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
$this->quoteFactory = $objectManager->get(QuoteFactory::class);
$this->quoteResource = $objectManager->get(QuoteResource::class);
$this->quoteIdMaskFactory = Bootstrap::getObjectManager()->get(QuoteIdMaskFactory::class);
}
/**
* @param string $itemArgName
* @param string $maskedQuoteId
* @param string $quoteItemId
* @param int $newQuantity
* @return string
*/
private function getQuery(string $itemArgName, string $maskedQuoteId, string $quoteItemId, int $newQuantity): string
{
if (is_numeric($quoteItemId)) {
$quoteItemId = (int) $quoteItemId;
} else {
$quoteItemId = '"' . $quoteItemId . '"';
}
return <<<QUERY
mutation {
updateCartItems(input: {
cart_id:"$maskedQuoteId"
cart_items: [
{
$itemArgName: $quoteItemId
quantity: $newQuantity
}
]
}) {
cart {
items {
quantity
}
}
}
}
QUERY;
}
/**
* Returns quote item by product SKU
*
* @param string $sku
* @return Item|bool
* @throws NoSuchEntityException
*/
private function getQuoteItemBySku(string $sku, string $reservedOrderId)
{
$quote = $this->quoteFactory->create();
$this->quoteResource->load($quote, $reservedOrderId, 'reserved_order_id');
$item = false;
foreach ($quote->getAllItems() as $quoteItem) {
if ($quoteItem->getSku() == $sku && $quoteItem->getProductType() == Configurable::TYPE_CODE &&
!$quoteItem->getParentItemId()) {
$item = $quoteItem;
break;
}
}
return $item;
}
}