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,365 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Bundle\Model\Option;
use Magento\Bundle\Model\Product\Type;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Ui\Component\Form\Element\Select;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\WishlistFactory;
/**
* Test coverage for adding a bundle product to wishlist
*/
class AddBundleProductToWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var WishlistFactory
*/
private $wishlistFactory;
/**
* @var mixed
*/
private $productRepository;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
$this->wishlistFactory = $objectManager->get(WishlistFactory::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/product_1.php
*
* @throws Exception
*/
public function testAddBundleProductWithOptions(): void
{
$sku = 'bundle-product';
$product = $this->productRepository->get($sku);
$customerId = 1;
$qty = 2;
$optionQty = 1;
/** @var Type $typeInstance */
$typeInstance = $product->getTypeInstance();
$typeInstance->setStoreFilter($product->getStoreId(), $product);
/** @var Option $option */
$option = $typeInstance->getOptionsCollection($product)->getFirstItem();
/** @var Product $selection */
$selection = $typeInstance->getSelectionsCollection([$option->getId()], $product)->getFirstItem();
$optionId = $option->getId();
$selectionId = $selection->getSelectionId();
$bundleOptions = $this->generateBundleOptionUid((int) $optionId, (int) $selectionId, $optionQty);
$query = $this->getQuery($sku, $qty, $bundleOptions);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);
/** @var Item $item */
$item = $wishlist->getItemCollection()->getFirstItem();
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty($response['addProductsToWishlist']['user_errors']);
$response = $response['addProductsToWishlist']['wishlist'];
$this->assertEquals($wishlist->getItemsCount(), $response['items_count']);
$this->assertEquals($wishlist->getSharingCode(), $response['sharing_code']);
$this->assertEquals($wishlist->getUpdatedAt(), $response['updated_at']);
$this->assertEquals($item->getData('qty'), $response['items_v2']['items'][0]['quantity']);
$this->assertEquals($item->getDescription(), $response['items_v2']['items'][0]['description']);
$this->assertEquals($item->getAddedAt(), $response['items_v2']['items'][0]['added_at']);
$this->assertNotEmpty($response['items_v2']['items'][0]['bundle_options']);
$bundleOptions = $response['items_v2']['items'][0]['bundle_options'];
$this->assertEquals('Bundle Product Items', $bundleOptions[0]['label']);
$this->assertEquals(Select::NAME, $bundleOptions[0]['type']);
$bundleOptionValuesResponse = $bundleOptions[0]['values'][0];
$this->assertNotNull($bundleOptionValuesResponse['id']);
unset($bundleOptionValuesResponse['id']);
$this->assertResponseFields(
$bundleOptionValuesResponse,
[
'label' => 'Simple Product',
'quantity' => 1,
'price' => 2.75
]
);
}
/**
* @magentoApiDataFixture Magento/Bundle/_files/product_with_multiple_options_and_custom_quantity.php
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws Exception
*/
public function testAddingBundleItemWithCustomOptionQuantity()
{
$response = $this->graphQlQuery($this->getProductQuery("bundle-product"));
$bundleItem = $response['products']['items'][0];
$sku = $bundleItem['sku'];
$bundleOptions = $bundleItem['items'];
$customerId = 1;
$uId0 = $bundleOptions[0]['options'][0]['uid'];
$uId1 = $bundleOptions[1]['options'][0]['uid'];
$query= $this->getQueryWithCustomOptionQuantity($sku, 5, $uId0, $uId1);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);
/** @var Item $item */
$item = $wishlist->getItemCollection()->getFirstItem();
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty($response['addProductsToWishlist']['user_errors']);
$response = $response['addProductsToWishlist']['wishlist'];
$this->assertEquals($wishlist->getItemsCount(), $response['items_count']);
$this->assertEquals($wishlist->getSharingCode(), $response['sharing_code']);
$this->assertEquals($wishlist->getUpdatedAt(), $response['updated_at']);
$this->assertEquals($item->getData('qty'), $response['items_v2']['items'][0]['quantity']);
$this->assertEquals($item->getDescription(), $response['items_v2']['items'][0]['description']);
$this->assertEquals($item->getAddedAt(), $response['items_v2']['items'][0]['added_at']);
$this->assertNotEmpty($response['items_v2']['items'][0]['bundle_options']);
$bundleOptions = $response['items_v2']['items'][0]['bundle_options'];
$this->assertEquals('Option 1', $bundleOptions[0]['label']);
$bundleOptionFirstValue = $bundleOptions[0]['values'];
$this->assertEquals(7, $bundleOptionFirstValue[0]['quantity']);
$this->assertEquals('Option 2', $bundleOptions[1]['label']);
$bundleOptionSecondValue = $bundleOptions[1]['values'];
$this->assertEquals(1, $bundleOptionSecondValue[0]['quantity']);
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param string $sku
* @param int $qty
* @param string $bundleOptions
* @param int $wishlistId
*
* @return string
*/
private function getQuery(
string $sku,
int $qty,
string $bundleOptions,
int $wishlistId = 0
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: {$wishlistId},
wishlistItems: [
{
sku: "{$sku}"
quantity: {$qty}
selected_options: [
"{$bundleOptions}"
]
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2 {
items {
id
description
quantity
added_at
... on BundleWishlistItem {
bundle_options {
id
label
type
values {
id
label
quantity
price
}
}
}
}
}
}
}
}
MUTATION;
}
/**
* Query with custom option quantity
*
* @param string $sku
* @param int $qty
* @param string $uId0
* @param string $uId1
* @param int $wishlistId
* @return string
*/
private function getQueryWithCustomOptionQuantity(
string $sku,
int $qty,
string $uId0,
string $uId1,
int $wishlistId = 0
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: {$wishlistId},
wishlistItems: [
{
sku: "{$sku}"
quantity: {$qty}
entered_options: [
{
uid:"{$uId0}",
value:"7"
},
{
uid:"{$uId1}",
value:"7"
}
]
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2 {
items {
id
description
quantity
added_at
... on BundleWishlistItem {
bundle_options {
id
label
type
values {
id
label
quantity
price
}
}
}
}
}
}
}
}
MUTATION;
}
/**
* Returns GraphQL query for retrieving a product with customizable options
*
* @param string $sku
* @return string
*/
private function getProductQuery(string $sku): string
{
return <<<QUERY
{
products(search: "{$sku}") {
items {
sku
... on BundleProduct {
items {
sku
option_id
required
type
title
options {
uid
label
product {
sku
}
can_change_quantity
id
price
quantity
}
}
}
}
}
}
QUERY;
}
/**
* @param int $optionId
* @param int $selectionId
*
* @param int $quantity
*
* @return string
*/
private function generateBundleOptionUid(int $optionId, int $selectionId, int $quantity): string
{
return base64_encode("bundle/$optionId/$selectionId/$quantity");
}
}
@@ -0,0 +1,389 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\WishlistFactory;
/**
* Test coverage for adding a configurable product to wishlist
*/
class AddConfigurableProductToWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var WishlistFactory
*/
private $wishlistFactory;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
$this->wishlistFactory = $objectManager->get(WishlistFactory::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @throws Exception
*/
public function testAddConfigurableProductWithOptions(): void
{
$product = $this->getConfigurableProductInfo();
$customerId = 1;
$qty = 2;
$childSku = $product['variants'][0]['product']['sku'];
$selectedOptions = array_column($product['variants'][0]['attributes'], 'uid');
$parentSku = $product['sku'];
$additionalInput = $this->getSelectedOptionsQuery($selectedOptions);
$query = $this->getQuery($parentSku, $childSku, $qty, $additionalInput);
$response = $this->graphQlMutation($query, [], '', $this->getHeadersMap());
$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);
/** @var Item $wishlistItem */
$wishlistItem = $wishlist->getItemCollection()->getFirstItem();
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty($response['addProductsToWishlist']['user_errors']);
$wishlistResponse = $response['addProductsToWishlist']['wishlist'];
$this->assertEquals($wishlist->getItemsCount(), $wishlistResponse['items_count']);
$this->assertEquals($wishlist->getSharingCode(), $wishlistResponse['sharing_code']);
$this->assertEquals($wishlist->getUpdatedAt(), $wishlistResponse['updated_at']);
$this->assertEquals($wishlistItem->getId(), $wishlistResponse['items_v2']['items'][0]['id']);
$this->assertEquals($wishlistItem->getData('qty'), $wishlistResponse['items_v2']['items'][0]['quantity']);
$this->assertEquals($wishlistItem->getDescription(), $wishlistResponse['items_v2']['items'][0]['description']);
$this->assertEquals($wishlistItem->getAddedAt(), $wishlistResponse['items_v2']['items'][0]['added_at']);
$this->assertNotEmpty($wishlistResponse['items_v2']['items'][0]['configurable_options']);
$configurableOptions = $wishlistResponse['items_v2']['items'][0]['configurable_options'];
$this->assertEquals('Test Configurable', $configurableOptions[0]['option_label']);
$this->assertEquals('Option 1', $configurableOptions[0]['value_label']);
$this->assertEquals($childSku, $wishlistResponse['items_v2']['items'][0]['configured_variant']['sku']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
*
* @throws Exception
*/
public function testAddConfigurableProductWithoutOption(): void
{
$product = $this->getConfigurableProductInfo();
$query = $this->getQuery($product['sku'], $product['sku'], 2);
$response = $this->graphQlMutation($query, [], '', $this->getHeadersMap());
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty(
$response['addProductsToWishlist']['user_errors'],
json_encode($response['addProductsToWishlist']['user_errors'])
);
$wishlistResponse = $response['addProductsToWishlist']['wishlist'];
$this->assertCount(1, $wishlistResponse['items_v2']['items']);
$this->assertEquals($product['sku'], $wishlistResponse['items_v2']['items'][0]['product']['sku']);
$this->assertEmpty($wishlistResponse['items_v2']['items'][0]['configurable_options']);
$this->assertNull($wishlistResponse['items_v2']['items'][0]['configured_variant']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_custom_option_dropdown.php
*
* @throws Exception
*/
public function testAddConfigurableProductWithCustomOptions(): void
{
$product = $this->getConfigurableProductInfo();
$qty = 2;
$childSku = $product['variants'][0]['product']['sku'];
$parentSku = $product['sku'];
$selectedOptions = array_column($product['variants'][0]['attributes'], 'uid');
$optionId = $product['options'][0]['uid'];
$optionValue = $product['options'][0]['value'][0]['option_type_id'];
$customOptions = [$optionId => $optionValue];
$additionalInput = $this->getSelectedOptionsQuery($selectedOptions)
. PHP_EOL
. $this->getCustomOptionsQuery($customOptions);
$query = $this->getQuery($parentSku, $childSku, $qty, $additionalInput);
$response = $this->graphQlMutation($query, [], '', $this->getHeadersMap());
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty($response['addProductsToWishlist']['user_errors']);
$wishlistResponse = $response['addProductsToWishlist']['wishlist'];
$this->assertCount(1, $wishlistResponse['items_v2']['items']);
$this->assertEquals($childSku, $wishlistResponse['items_v2']['items'][0]['configured_variant']['sku']);
$this->assertNotEmpty($wishlistResponse['items_v2']['items'][0]['configurable_options']);
$configurableOptions = $wishlistResponse['items_v2']['items'][0]['configurable_options'];
$this->assertEquals('Test Configurable', $configurableOptions[0]['option_label']);
$this->assertEquals('Option 1', $configurableOptions[0]['value_label']);
$this->assertNotEmpty($wishlistResponse['items_v2']['items'][0]['customizable_options']);
$customizableOptions = $wishlistResponse['items_v2']['items'][0]['customizable_options'];
$this->assertEquals($optionId, $customizableOptions[0]['customizable_option_uid']);
$this->assertEquals($optionValue, $customizableOptions[0]['values'][0]['value']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_with_custom_option_dropdown.php
*
* @throws Exception
*/
public function testShouldValidateCustomDropdownOptionValue(): void
{
$product = $this->getConfigurableProductInfo();
$qty = 2;
$childSku = $product['variants'][0]['product']['sku'];
$parentSku = $product['sku'];
$selectedOptions = array_column($product['variants'][0]['attributes'], 'uid');
$optionId = $product['options'][0]['uid'];
$customOptions = [$optionId => 'invalid-option-id'];
$additionalInput = $this->getSelectedOptionsQuery($selectedOptions)
. PHP_EOL
. $this->getCustomOptionsQuery($customOptions);
$query = $this->getQuery($parentSku, $childSku, $qty, $additionalInput);
$response = $this->graphQlMutation($query, [], '', $this->getHeadersMap());
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertNotEmpty($response['addProductsToWishlist']['user_errors']);
$this->assertEquals(
'Some of the selected item options are not currently available.',
$response['addProductsToWishlist']['user_errors'][0]['message']
);
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeadersMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param string|null $parentSku
* @param string $childSku
* @param int $qty
* @param string $additionalInput
* @param int $wishlistId
*
* @return string
*/
private function getQuery(
string $parentSku,
string $childSku,
int $qty,
string $additionalInput = '',
int $wishlistId = 0
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: {$wishlistId},
wishlistItems: [
{
sku: "{$childSku}"
parent_sku: "{$parentSku}"
quantity: {$qty}
{$additionalInput}
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2(currentPage:1,pageSize:1) {
items{
id
description
quantity
added_at
... on ConfigurableWishlistItem {
configurable_options {
id
configurable_product_option_uid
option_label
value_id
configurable_product_option_value_uid
value_label
}
configured_variant {
sku
}
}
customizable_options {
customizable_option_uid
is_required
label
type
values {
customizable_option_value_uid
label
value
price {
value
}
}
}
product {
sku
}
}
}
}
}
}
MUTATION;
}
/**
* Generates GQL for selected_options
*
* @param array $options
* @return string
*/
private function getSelectedOptionsQuery(array $options): string
{
return 'selected_options: ' . json_encode($options);
}
/**
* Generates GQL for entered_options
*
* @param array $options
* @return string
*/
private function getCustomOptionsQuery(array $options): string
{
$output = [];
foreach ($options as $id => $value) {
$output[] = [
'uid' => $id,
'value' => $value
];
}
return 'entered_options: ' . preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($output));
}
/**
* 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']);
}
/**
* 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
... on CustomizableProductInterface {
options {
uid
... on CustomizableDropDownOption {
value {
option_type_id
}
}
}
}
... on ConfigurableProduct {
variants {
attributes {
uid
}
product {
sku
}
}
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,238 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\WishlistFactory;
/**
* Test coverage for adding a downloadable product to wishlist
*/
class AddDownloadableProductToWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var WishlistFactory
*/
private $wishlistFactory;
/**
* @var GetCustomOptionsWithUidForQueryBySku
*/
private $getCustomOptionsWithUidForQueryBySku;
/**
* Set Up
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class);
$this->wishlistFactory = $this->objectManager->get(WishlistFactory::class);
$this->getCustomOptionsWithUidForQueryBySku =
$this->objectManager->get(GetCustomOptionsWithUidForQueryBySku::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 0
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_custom_options.php
*/
public function testAddDownloadableProductOnDisabledWishlist(): void
{
$qty = 2;
$sku = 'downloadable-product-with-purchased-separately-links';
$links = $this->getProductsLinks($sku);
$linkId = key($links);
$itemOptions = $this->getCustomOptionsWithUidForQueryBySku->execute($sku);
$itemOptions['selected_options'][] = $this->generateProductLinkSelectedOptions($linkId);
$productOptionsQuery = trim(preg_replace(
'/"([^"]+)"\s*:\s*/',
'$1:',
json_encode($itemOptions)
), '{}');
$query = $this->getQuery($qty, $sku, $productOptionsQuery);
$this->expectExceptionMessage('The wishlist configuration is currently disabled.');
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_custom_options.php
*/
public function testAddDownloadableProductWithOptions(): void
{
$customerId = 1;
$sku = 'downloadable-product-with-purchased-separately-links';
$qty = 2;
$links = $this->getProductsLinks($sku);
$linkId = key($links);
$itemOptions = $this->getCustomOptionsWithUidForQueryBySku->execute($sku);
$itemOptions['selected_options'][] = $this->generateProductLinkSelectedOptions($linkId);
$productOptionsQuery = preg_replace(
'/"([^"]+)"\s*:\s*/',
'$1:',
json_encode($itemOptions)
);
$query = $this->getQuery($qty, $sku, trim($productOptionsQuery, '{}'));
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$wishlist = $this->wishlistFactory->create();
$wishlist->loadByCustomerId($customerId, true);
/** @var Item $wishlistItem */
$wishlistItem = $wishlist->getItemCollection()->getFirstItem();
$this->assertArrayHasKey('addProductsToWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['addProductsToWishlist']);
$this->assertEmpty($response['addProductsToWishlist']['user_errors']);
$wishlistResponse = $response['addProductsToWishlist']['wishlist'];
$this->assertEquals($wishlist->getItemsCount(), $wishlistResponse['items_count']);
$this->assertEquals($wishlist->getSharingCode(), $wishlistResponse['sharing_code']);
$this->assertEquals($wishlist->getUpdatedAt(), $wishlistResponse['updated_at']);
$this->assertEquals($wishlistItem->getId(), $wishlistResponse['items_v2']['items'][0]['id']);
$this->assertEquals($wishlistItem->getData('qty'), $wishlistResponse['items_v2']['items'][0]['quantity']);
$this->assertEquals($wishlistItem->getDescription(), $wishlistResponse['items_v2']['items'][0]['description']);
$this->assertEquals($wishlistItem->getAddedAt(), $wishlistResponse['items_v2']['items'][0]['added_at']);
$this->assertNotEmpty($wishlistResponse['items_v2']['items'][0]['links_v2']);
$wishlistItemLinks = $wishlistResponse['items_v2']['items'][0]['links_v2'];
$this->assertEquals('Downloadable Product Link 1', $wishlistItemLinks[0]['title']);
$this->assertNotEmpty($wishlistResponse['items_v2']['items'][0]['samples']);
$wishlistItemSamples = $wishlistResponse['items_v2']['items'][0]['samples'];
$this->assertEquals('Downloadable Product Sample', $wishlistItemSamples[0]['title']);
}
/**
* Function returns array of all product's links
*
* @param string $sku
*
* @return array
*/
private function getProductsLinks(string $sku): array
{
$result = [];
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get($sku, false, null, true);
foreach ($product->getDownloadableLinks() as $linkObject) {
$result[$linkObject->getLinkId()] = [
'title' => $linkObject->getTitle(),
'price' => $linkObject->getPrice(),
];
}
return $result;
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param int $qty
* @param string $sku
* @param string $customizableOptions
*
* @return string
*/
private function getQuery(
int $qty,
string $sku,
string $customizableOptions
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: 0,
wishlistItems: [
{
sku: "{$sku}"
quantity: {$qty}
{$customizableOptions}
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2(currentPage:1 pageSize:1) {
items
{
id
description
quantity
added_at
... on DownloadableWishlistItem {
links_v2 {
id
title
sample_url
}
samples {
id
title
sample_url
}
}
}
}
}
}
}
MUTATION;
}
/**
* Generates uid for downloadable links
*
* @param int $linkId
*
* @return string
*/
private function generateProductLinkSelectedOptions(int $linkId): string
{
return base64_encode("downloadable/$linkId");
}
}
@@ -0,0 +1,442 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare (strict_types = 1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test coverage for add requisition list items to cart
*/
class AddWishlistItemsToCartTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCart(): void
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('addWishlistItemsToCart', $response);
$wishlistAfterAddingToCart = $response['addWishlistItemsToCart']['wishlist'];
$wishlistItems = $wishlistAfterAddingToCart['items_v2']['items'];
$this->assertEmpty($wishlistItems);
$this->assertArrayHasKey('status', $response['addWishlistItemsToCart']);
$this->assertEquals($response['addWishlistItemsToCart']['status'], true);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_configurable_product.php
*/
public function testAddIncompleteItemsToCart(): void
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('addWishlistItemsToCart', $response);
$wishlistAfterAddingToCart = $response['addWishlistItemsToCart']['wishlist'];
$userErrors = $response['addWishlistItemsToCart']['add_wishlist_items_to_cart_user_errors'];
$this->assertEquals($userErrors[0]['message'], 'You need to choose options for your item.');
$this->assertEquals($userErrors[0]['code'], 'UNDEFINED');
$this->assertEquals($userErrors[0]['wishlistId'], $wishlistId);
$this->assertEquals($userErrors[0]['wishlistItemId'], $itemId);
$wishlistItems = $wishlistAfterAddingToCart['items_v2']['items'];
$this->assertNotEmpty($wishlistItems);
$this->assertArrayHasKey('status', $response['addWishlistItemsToCart']);
$this->assertEquals($response['addWishlistItemsToCart']['status'], false);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_multiple_products.php
*/
public function testAddAllItemsToCart(): void
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$query = $this->getAddAllItemsToCartQuery($wishlistId);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('addWishlistItemsToCart', $response);
$wishlistAfterAddingToCart = $response['addWishlistItemsToCart']['wishlist'];
$wishlistItems = $wishlistAfterAddingToCart['items_v2']['items'];
$this->assertEmpty($wishlistItems);
$this->assertArrayHasKey('status', $response['addWishlistItemsToCart']);
$this->assertEquals($response['addWishlistItemsToCart']['status'], true);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCartForInvalidUser(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later.");
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$this->graphQlMutation($query, [], '', $this->getHeaderMap('customer2@example.com', 'password'));
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCartForGuestUser(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current user cannot perform operations on wishlist');
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$this->graphQlMutation($query, [], '', ['Authorization' => 'Bearer test_token']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCartWithoutId(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('"wishlistId" value should be specified');
$wishlistId = '';
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCartWithInvalidId(): void
{
$wishlistId = '9999';
$this->expectException(Exception::class);
$this->expectExceptionMessage('The wishlist was not found.');
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$itemId = $wishlistItem['id'];
$query = $this->getQuery($wishlistId, $itemId);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddItemsToCartWithInvalidItemId(): void
{
$itemId = '9999';
$this->expectException(Exception::class);
$this->expectExceptionMessage('The wishlist item ids "9999" were not found.');
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$query = $this->getQuery($customerWishlist['id'], $itemId);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/** Add all items from customer's wishlist to cart
*
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture wishlist/general/active 1
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testAddAllWishlistItemsToCart(): void
{
$wishlist = $this->getWishlist();
$this->assertNotEmpty($wishlist['customer']['wishlists'], 'No wishlist found');
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$sku2 = 'simple_product';
$quantity2 = 2;
$addProductsToWishlistQuery = $this->addSecondProductToWishlist($wishlistId, $sku2, $quantity2);
$this->graphQlMutation($addProductsToWishlistQuery, [], '', $this->getHeaderMap());
$addWishlistToCartQuery = $this->getAddAllItemsToCartQuery($wishlistId);
$response = $this->graphQlMutation($addWishlistToCartQuery, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('addWishlistItemsToCart', $response);
$this->assertArrayHasKey('status', $response['addWishlistItemsToCart']);
$this->assertEquals($response['addWishlistItemsToCart']['status'], true);
$wishlistAfterItemsAddedToCart = $this->getWishlist();
$this->assertEmpty($wishlistAfterItemsAddedToCart['customer']['wishlists'][0]['items_v2']['items']);
$customerCart = $this->getCustomerCart('customer@example.com');
$this->assertCount(2, $customerCart['customerCart']['items']);
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param string $wishlistId
* @param string $itemId
* @return string
*/
private function getQuery(
string $wishlistId,
string $itemId
): string {
return <<<MUTATION
mutation {
addWishlistItemsToCart
(
wishlistId: "{$wishlistId}"
wishlistItemIds: ["{$itemId}"]
) {
status
wishlist {
items_v2 {
items {
id
}
}
}
add_wishlist_items_to_cart_user_errors{
message
code
wishlistId
wishlistItemId
}
}
}
MUTATION;
}
/**
* Returns GraphQl mutation string
*
* @param string $wishlistId
* @param string $itemId
* @return string
*/
private function getAddAllItemsToCartQuery(
string $wishlistId
): string {
return <<<MUTATION
mutation {
addWishlistItemsToCart
(
wishlistId: "{$wishlistId}"
) {
status
wishlist {
items_v2 {
items {
id
}
}
}
add_wishlist_items_to_cart_user_errors{
message
code
}
}
}
MUTATION;
}
/**
* Get wishlist result
*
* @param string $username
* @return array
*
* @throws Exception
*/
public function getWishlist(string $username = 'customer@example.com'): array
{
return $this->graphQlQuery($this->getCustomerWishlistQuery(), [], '', $this->getHeaderMap($username));
}
public function getCustomerCart(string $username): array
{
return $this->graphQlQuery($this->getCustomerCartQuery(), [], '', $this->getHeaderMap($username));
}
/**
* Get customer wishlist query
*
* @return string
*/
private function getCustomerWishlistQuery(): string
{
return <<<QUERY
query {
customer {
wishlists {
id
items_count
sharing_code
updated_at
items_v2 {
items {
id
quantity
description
product {
sku
}
}
}
}
}
}
QUERY;
}
/**
* Returns the GraphQl mutation string for products added to wishlist
*
* @param string $wishlistId
* @param string $sku2
* @param int $quantity2
* @return string
*/
private function addSecondProductToWishlist(
string $wishlistId,
string $sku,
int $quantity
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: "{$wishlistId}",
wishlistItems: [
{
sku: "{$sku}"
quantity: {$quantity}
}
]
) {
user_errors {
code
message
}
wishlist {
id
items_count
items_v2 {
items {
quantity
id
product {sku name}
}
page_info {current_page page_size total_pages}
}
}
}
}
MUTATION;
}
/**
* Get customer cart query
*
* @return string
*/
private function getCustomerCartQuery(): string
{
return <<<QUERY
{customerCart {
id
total_quantity
items {
uid
quantity
product{sku}
}
}
}
QUERY;
}
}
@@ -0,0 +1,311 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\ResourceModel\Wishlist\CollectionFactory;
class CustomerWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CollectionFactory
*/
private $wishlistCollectionFactory;
protected function setUp(): void
{
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->wishlistCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist.php
*/
public function testCustomerWishlist(): void
{
/** @var \Magento\Wishlist\Model\Wishlist $wishlist */
$collection = $this->wishlistCollectionFactory->create()->filterByCustomerId(1);
/** @var Item $wishlistItem */
$wishlistItem = $collection->getFirstItem();
$query =
<<<QUERY
{
customer {
wishlist {
id
items_count
sharing_code
updated_at
items {
product {
sku
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertEquals((string)$wishlistItem->getId(), $response['customer']['wishlist']['id']);
$this->assertEquals($wishlistItem->getItemsCount(), $response['customer']['wishlist']['items_count']);
$this->assertEquals($wishlistItem->getSharingCode(), $response['customer']['wishlist']['sharing_code']);
$this->assertEquals($wishlistItem->getUpdatedAt(), $response['customer']['wishlist']['updated_at']);
$this->assertEquals('simple', $response['customer']['wishlist']['items'][0]['product']['sku']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCustomerAlwaysHasWishlist(): void
{
$query =
<<<QUERY
{
customer {
wishlist {
id
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertNotEmpty($response['customer']['wishlist']['id']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
*/
public function testGuestCannotGetWishlist()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query =
<<<QUERY
{
customer {
wishlist {
items_count
sharing_code
updated_at
}
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* Add product to wishlist with quantity 0
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_duplicated.php
*/
public function testAddProductToWishlistWithZeroQty()
{
$customerWishlistQuery =
<<<QUERY
{
customer {
wishlist {
id
}
}
}
QUERY;
$response = $this->graphQlQuery(
$customerWishlistQuery,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$qty = 0;
$sku = 'simple-1';
$wishlistId = $response['customer']['wishlist']['id'];
$addProductToWishlistQuery =
<<<QUERY
mutation{
addProductsToWishlist(
wishlistId:{$wishlistId}
wishlistItems:[
{
sku:"{$sku}"
quantity:{$qty}
}
])
{
wishlist{
id
items_count
items{product{name sku} description qty}
}
user_errors{code message}
}
}
QUERY;
$addToWishlistResponse = $this->graphQlMutation(
$addProductToWishlistQuery,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertArrayHasKey('user_errors', $addToWishlistResponse['addProductsToWishlist']);
$this->assertCount(1, $addToWishlistResponse['addProductsToWishlist']['user_errors']);
$this->assertEmpty($addToWishlistResponse['addProductsToWishlist']['wishlist']['items']);
$this->assertEquals(
0,
$addToWishlistResponse['addProductsToWishlist']['wishlist']['items_count'],
'Count is greater than 0'
);
$message = 'The quantity of a wish list item cannot be 0';
$this->assertEquals(
$message,
$addToWishlistResponse['addProductsToWishlist']['user_errors'][0]['message']
);
}
/**
* Add disabled product to wishlist
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/simple_product_disabled.php
*/
public function testAddProductToWishlistWithDisabledProduct()
{
$customerWishlistQuery =
<<<QUERY
{
customer {
wishlist {
id
}
}
}
QUERY;
$response = $this->graphQlQuery(
$customerWishlistQuery,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$qty = 2;
$sku = 'product_disabled';
$wishlistId = $response['customer']['wishlist']['id'];
$addProductToWishlistQuery =
<<<QUERY
mutation{
addProductsToWishlist(
wishlistId:{$wishlistId}
wishlistItems:[
{
sku:"{$sku}"
quantity:{$qty}
}
])
{
wishlist{
id
items_count
items{product{name sku} description qty}
}
user_errors{code message}
}
}
QUERY;
$addToWishlistResponse = $this->graphQlMutation(
$addProductToWishlistQuery,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertArrayHasKey('user_errors', $addToWishlistResponse['addProductsToWishlist']);
$this->assertCount(1, $addToWishlistResponse['addProductsToWishlist']['user_errors']);
$this->assertEmpty($addToWishlistResponse['addProductsToWishlist']['wishlist']['items']);
$this->assertEquals(
0,
$addToWishlistResponse['addProductsToWishlist']['wishlist']['items_count'],
'Count is greater than 0'
);
$message = 'Could not find a product with SKU "' . $sku . '"';
$this->assertEquals(
$message,
$addToWishlistResponse['addProductsToWishlist']['user_errors'][0]['message']
);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 0
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCustomerCannotGetWishlistWhenDisabled()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The wishlist configuration is currently disabled.');
$query =
<<<QUERY
{
customer {
wishlist {
items_count
sharing_code
updated_at
}
}
}
QUERY;
$this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,238 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\ResourceModel\Wishlist\CollectionFactory;
use Magento\Wishlist\Model\Wishlist;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Registry;
/**
* Test coverage for customer wishlists
*/
class CustomerWishlistsTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CollectionFactory
*/
private $wishlistCollectionFactory;
/**
* Set Up
*/
protected function setUp(): void
{
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->wishlistCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class);
}
/**
* Test fetching customer wishlist
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist.php
*/
public function testCustomerWishlist(): void
{
$customerId = 1;
/** @var Wishlist $wishlist */
$collection = $this->wishlistCollectionFactory->create()->filterByCustomerId($customerId);
/** @var Item $wishlistItem */
$wishlistItem = $collection->getFirstItem();
$response = $this->graphQlQuery(
$this->getQuery(),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertArrayHasKey('wishlists', $response['customer']);
$wishlist = $response['customer']['wishlists'][0];
$this->assertEquals($wishlistItem->getItemsCount(), $wishlist['items_count']);
$this->assertEquals($wishlistItem->getSharingCode(), $wishlist['sharing_code']);
$this->assertEquals($wishlistItem->getUpdatedAt(), $wishlist['updated_at']);
$wishlistItemResponse = $wishlist['items_v2']['items'][0];
$this->assertEquals('simple', $wishlistItemResponse['product']['sku']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @throws Exception
*/
public function testWishlistCreationScenario(): void
{
try {
$customerEmail = 'customer2@wishlist.com';
$this->graphQlMutation(
$this->getCreateCustomerQuery($customerEmail),
[],
''
);
$response = $this->graphQlQuery(
$this->getQuery(),
[],
'',
$this->getCustomerAuthHeaders($customerEmail, '123123^q')
);
$this->assertArrayHasKey('wishlists', $response['customer']);
$wishlists = $response['customer']['wishlists'];
$this->assertNotEmpty($wishlists);
$wishlist = $wishlists[0];
$this->assertEquals(0, $wishlist['items_count']);
$sku = 'simple-1';
$qty = 1;
$addProductToWishlistQuery =
<<<QUERY
mutation{
addProductsToWishlist(
wishlistId:{$wishlist['id']}
wishlistItems:[
{
sku:"{$sku}"
quantity:{$qty}
}
])
{
wishlist{
id
items_count
items{product{name sku} description qty}
}
user_errors{code message}
}
}
QUERY;
$addToWishlistResponse = $this->graphQlMutation(
$addProductToWishlistQuery,
[],
'',
$this->getCustomerAuthHeaders($customerEmail, '123123^q')
);
$this->assertArrayHasKey('user_errors', $addToWishlistResponse['addProductsToWishlist']);
$this->assertCount(0, $addToWishlistResponse['addProductsToWishlist']['user_errors']);
} finally {
/** @var Registry $registry */
$registry = Bootstrap::getObjectManager()
->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$objectManager = Bootstrap::getObjectManager();
$customerRepository = $objectManager->create(CustomerRepositoryInterface::class);
$customer = $customerRepository->get($customerEmail);
$customerRepository->delete($customer);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
/**
* Testing fetching the wishlist when wishlist is disabled
*
* @magentoConfigFixture default_store wishlist/general/active 0
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCustomerCannotGetWishlistWhenDisabled(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The wishlist configuration is currently disabled.');
$this->graphQlQuery(
$this->getQuery(),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
}
/**
* Test wishlist fetching for a guest customer
*
* @magentoConfigFixture default_store wishlist/general/active 1
*/
public function testGuestCannotGetWishlist(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$this->graphQlQuery($this->getQuery());
}
/**
* Returns GraphQl query string
*
* @return string
*/
private function getQuery(): string
{
return <<<QUERY
query {
customer {
wishlists {
id
items_count
sharing_code
updated_at
items_v2 {
items {
product {name sku}
}
}
}
}
}
QUERY;
}
private function getCreateCustomerQuery($customerEmail): string
{
return <<<QUERY
mutation {
createCustomer(input: {
firstname: "test"
lastname: "test"
email: "$customerEmail"
password: "123123^q"
})
{
customer {
email
}
}
}
QUERY;
}
/**
* Getting customer auth headers
*
* @param string $email
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,182 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test coverage for deleting a product from wishlist
*/
class DeleteProductsFromWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testDeleteWishlistItemFromWishlist(): void
{
$wishlist = $this->getWishlist();
$customerWishlists = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlists['id'];
$wishlistItems = $customerWishlists['items_v2']['items'];
$this->assertEquals(1, $customerWishlists['items_count']);
$query = $this->getQuery($wishlistId, $wishlistItems[0]['id']);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('removeProductsFromWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['removeProductsFromWishlist']);
$this->assertEmpty($response['removeProductsFromWishlist']['user_errors'], 'User error is not empty');
$wishlistResponse = $response['removeProductsFromWishlist']['wishlist'];
$this->assertEquals(0, $wishlistResponse['items_count']);
$this->assertEmpty($wishlistResponse['items_v2']['items'], 'Wishlist item is not removed');
}
/**
* Test deleting the wishlist item of another customer
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Wishlist/_files/two_wishlists_for_two_diff_customers.php
*/
public function testUnauthorizedWishlistItemDelete()
{
$wishlist = $this->getWishlist();
$wishlistItem = $wishlist['customer']['wishlists'][0]['items_v2']['items'];
$wishlist2 = $this->getWishlist('customer_two@example.com');
$wishlist2Id = $wishlist2['customer']['wishlists'][0]['id'];
$query = $this->getQuery($wishlist2Id, $wishlistItem[0]['id']);
$response = $this->graphQlMutation(
$query,
[],
'',
$this->getHeaderMap('customer_two@example.com')
);
self::assertEquals(1, $response['removeProductsFromWishlist']['wishlist']['items_count']);
self::assertNotEmpty($response['removeProductsFromWishlist']['wishlist']['items_v2']['items'], 'empty wish list items');
self::assertCount(1, $response['removeProductsFromWishlist']['wishlist']['items_v2']['items']);
self::assertEquals(
'The wishlist item with ID "' . $wishlistItem[0]['id'] . '" does not belong to the wishlist',
$response['removeProductsFromWishlist']['user_errors'][0]['message']
);
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param int $wishlistId
* @param int $wishlistItemId
*
* @return string
*/
private function getQuery(
string $wishlistId,
string $wishlistItemId
): string {
return <<<MUTATION
mutation {
removeProductsFromWishlist(
wishlistId: "{$wishlistId}",
wishlistItemsIds: ["{$wishlistItemId}"]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
items_v2 {
items {id description quantity product {name sku}}
}
}
}
}
MUTATION;
}
/**
* Get wishlist result
*
* @return array
*
* @throws Exception
*/
public function getWishlist(string $username = 'customer@example.com'): array
{
return $this->graphQlQuery($this->getCustomerWishlistQuery(), [], '', $this->getHeaderMap($username));
}
/**
* Get customer wishlist query
*
* @return string
*/
private function getCustomerWishlistQuery(): string
{
return <<<QUERY
query {
customer {
wishlists {
id
items_count
sharing_code
updated_at
items_v2 {
items {
id
quantity
description
product {
sku
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface;
/**
* Generate an array with test values for customizable options with encoded uid value
*/
class GetCustomOptionsWithUidForQueryBySku
{
/**
* @var ProductCustomOptionRepositoryInterface
*/
private $productCustomOptionRepository;
/**
* @param ProductCustomOptionRepositoryInterface $productCustomOptionRepository
*/
public function __construct(ProductCustomOptionRepositoryInterface $productCustomOptionRepository)
{
$this->productCustomOptionRepository = $productCustomOptionRepository;
}
/**
* Returns array of custom options for the product
*
* @param string $sku
*
* @return array
*/
public function execute(string $sku): array
{
$customOptions = $this->productCustomOptionRepository->getList($sku);
$selectedOptions = [];
$enteredOptions = [];
foreach ($customOptions as $customOption) {
$optionType = $customOption->getType();
if ($optionType === 'field' || $optionType === 'area' || $optionType === 'date') {
$enteredOptions[] = [
'uid' => $this->encodeEnteredOption((int)$customOption->getOptionId()),
'value' => '2012-12-12'
];
} elseif ($optionType === 'drop_down') {
$optionSelectValues = $customOption->getValues();
$selectedOptions[] = $this->encodeSelectedOption(
(int)$customOption->getOptionId(),
(int)reset($optionSelectValues)->getOptionTypeId()
);
} elseif ($optionType === 'multiple') {
foreach ($customOption->getValues() as $optionValue) {
$selectedOptions[] = $this->encodeSelectedOption(
(int)$customOption->getOptionId(),
(int)$optionValue->getOptionTypeId()
);
}
}
}
return [
'selected_options' => $selectedOptions,
'entered_options' => $enteredOptions
];
}
/**
* Returns uid of the selected custom option
*
* @param int $optionId
* @param int $optionValueId
*
* @return string
*/
private function encodeSelectedOption(int $optionId, int $optionValueId): string
{
return base64_encode("custom-option/$optionId/$optionValueId");
}
/**
* Returns uid of the entered custom option
*
* @param int $optionId
*
* @return string
*/
private function encodeEnteredOption(int $optionId): string
{
return base64_encode("custom-option/$optionId");
}
}
@@ -0,0 +1,344 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\WishlistFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Ui\Component\Form\Element\Select;
/**
* Test coverage for updating a bundle product from wishlist
*/
class UpdateBundleProductsFromWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var WishlistFactory
*/
private $wishlistFactory;
/**
* @var mixed
*/
private $productRepository;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
$this->wishlistFactory = $objectManager->get(WishlistFactory::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
/**
* Test that a wishlist item bundle product is properly updated.
*
* This includes the selected options for the bundle product.
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_dropdown_options.php
* @throws Exception
*/
public function testUpdateBundleProductWithOptions(): void
{
// Add the fixture bundle product to the fixture customer's wishlist
$wishlist = $this->addBundleProductToWishlist(
'bundle-product-dropdown-options',
'simple-1'
);
$wishlistId = (int) $wishlist['addProductsToWishlist']['wishlist']['id'];
$wishlistItemId = (int) $wishlist['addProductsToWishlist']['wishlist']['items_v2']['items'][0]['id'];
$previousItemsCount = $wishlist['addProductsToWishlist']['wishlist']['items_count'];
// Set the new values to update the wishlist item with
$newQuantity = 5;
$newDescription = 'This is a test.';
$newBundleOptionUid = $this->getBundleProductOptionUid(
'bundle-product-dropdown-options',
'simple2'
);
// Update the newly added wishlist item as the fixture customer
$query = $this->getUpdateQuery(
$wishlistItemId,
$newQuantity,
$newDescription,
$newBundleOptionUid,
$wishlistId
);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
// Assert that the response has the expected base properties
self::assertArrayHasKey('updateProductsInWishlist', $response);
self::assertArrayHasKey('wishlist', $response['updateProductsInWishlist']);
// Assert that the wishlist item count is unchanged
$responseWishlist = $response['updateProductsInWishlist']['wishlist'];
self::assertEquals($previousItemsCount, $responseWishlist['items_count']);
// Assert that the wishlist item quantity and description are updated
$responseWishlistItem = $responseWishlist['items_v2']['items'][0];
self::assertEquals($newQuantity, $responseWishlistItem['quantity']);
self::assertEquals($newDescription, $responseWishlistItem['description']);
// Assert that the bundle option for this wishlist item is accurate
self::assertNotEmpty($responseWishlistItem['bundle_options']);
$responseBundleOption = $responseWishlistItem['bundle_options'][0];
self::assertEquals('Dropdown Options', $responseBundleOption['label']);
self::assertEquals(Select::NAME, $responseBundleOption['type']);
// Assert that the selected value for this bundle option is updated
self::assertNotEmpty($responseBundleOption['values']);
$responseOptionSelection = $responseBundleOption['values'][0];
self::assertEquals($newBundleOptionUid, $responseOptionSelection['uid']);
self::assertEquals('Simple Product2', $responseOptionSelection['label']);
self::assertEquals(1, $responseOptionSelection['quantity']);
self::assertEquals(10, $responseOptionSelection['price']);
}
/**
* Returns GraphQl mutation string
*
* @param int $wishlistItemId
* @param int $qty
* @param string $description
* @param string $bundleOptions
* @param int $wishlistId
* @return string
*/
private function getUpdateQuery(
int $wishlistItemId,
int $qty,
string $description,
string $bundleOptions,
int $wishlistId = 0
): string {
return <<<MUTATION
mutation {
updateProductsInWishlist(
wishlistId: {$wishlistId},
wishlistItems: [
{
wishlist_item_id: "{$wishlistItemId}"
quantity: {$qty}
description: "{$description}"
selected_options: [
"{$bundleOptions}"
]
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2 {
items{
id
quantity
description
... on BundleWishlistItem {
bundle_options {
id
uid
label
type
values {
id
uid
label
quantity
price
}
}
}
}
}
}
}
}
MUTATION;
}
/**
* Add the specified bundle product with the specified selected option to the wishlist.
*
* @param $bundleProductSku
* @param $selectedOptionSku
* @return array
* @throws AuthenticationException
*/
private function addBundleProductToWishlist($bundleProductSku, $selectedOptionSku): array
{
$bundleOptionUid = $this->getBundleProductOptionUid($bundleProductSku, $selectedOptionSku);
$initialQuantity = 2;
$query = $this->getAddQuery($bundleProductSku, $initialQuantity, $bundleOptionUid);
return $this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* Returns the GraphQl mutation for adding an item to the wishlist.
*
* @param string $sku
* @param int $qty
* @param string $bundleOptions
* @param int $wishlistId
* @return string
*/
private function getAddQuery(
string $sku,
int $qty,
string $bundleOptions,
int $wishlistId = 0
): string {
return <<<MUTATION
mutation {
addProductsToWishlist(
wishlistId: {$wishlistId},
wishlistItems: [
{
sku: "{$sku}"
quantity: {$qty}
selected_options: [
"{$bundleOptions}"
]
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
updated_at
items_v2 {
items{
id
quantity
added_at
... on BundleWishlistItem {
bundle_options {
id
label
type
values {
id
label
quantity
price
}
}
}
}
}
}
}
}
MUTATION;
}
/**
* Get the uid for the specified bundle product option.
*
* @param string $bundleProductSku
* @param string $selectedOptionSku
* @return string|null
*/
private function getBundleProductOptionUid(string $bundleProductSku, string $selectedOptionSku)
{
$query = $this->getBundleProductSearchQuery($bundleProductSku);
$response = $this->graphQlQuery($query);
$bundleProduct = $response["products"]["items"][0];
$bundleProductOptions = $bundleProduct["items"][0]["options"];
$bundleProductOptionUid = null;
// Search the specified bundle product for the specified option based on the product sku
foreach ($bundleProductOptions as $bundleProductOption) {
if (isset($bundleProductOption['product'])
&& $bundleProductOption['product']['sku'] === $selectedOptionSku) {
$bundleProductOptionUid = $bundleProductOption['uid'];
break;
}
}
return $bundleProductOptionUid;
}
/**
* Returns the GraphQl product search query for a bundle product.
*
* @param string $bundleProductSku
* @return string
*/
private function getBundleProductSearchQuery(string $bundleProductSku): string
{
return <<<QUERY
query {
products(search: "{$bundleProductSku}"){
items {
uid
sku
name
... on BundleProduct {
items {
uid
title
type
options {
id
uid
product {
sku
}
}
}
}
}
}
}
QUERY;
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
* @return array
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,304 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test coverage for updating a product from wishlist
*/
class UpdateProductsFromWishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* Set Up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testUpdateSimpleProductFromWishlist(): void
{
$wishlist = $this->getWishlist();
$qty = 5;
$description = 'New Description';
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$this->assertNotEquals($description, $wishlistItem['description']);
$this->assertNotEquals($qty, $wishlistItem['quantity']);
$query = $this->getQuery($wishlistId, $wishlistItem['id'], $qty, $description);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertArrayHasKey('updateProductsInWishlist', $response);
$this->assertArrayHasKey('wishlist', $response['updateProductsInWishlist']);
$this->assertEmpty($response['updateProductsInWishlist']['user_errors']);
$wishlistResponse = $response['updateProductsInWishlist']['wishlist'];
$this->assertEquals($qty, $wishlistResponse['items_v2']['items'][0]['quantity']);
$this->assertEquals($description, $wishlistResponse['items_v2']['items'][0]['description']);
}
/**
* Test updating the wishlist item of another customer
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/two_customers.php
* @magentoApiDataFixture Magento/Wishlist/_files/two_wishlists_for_two_diff_customers.php
*/
public function testUnauthorizedWishlistItemUpdate()
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$wishlist2 = $this->getWishlist('customer_two@example.com');
$wishlist2Id = $wishlist2['customer']['wishlists'][0]['id'];
$qty = 2;
$description = 'New Description';
$updateWishlistQuery = $this->getQuery($wishlist2Id, $wishlistItem['id'], $qty, $description);
$response = $this->graphQlMutation(
$updateWishlistQuery,
[],
'',
$this->getHeaderMap('customer_two@example.com')
);
self::assertEquals(1, $response['updateProductsInWishlist']['wishlist']['items_count']);
self::assertNotEmpty($response['updateProductsInWishlist']['wishlist']['items_v2'], 'empty wish list items');
self::assertCount(1, $response['updateProductsInWishlist']['wishlist']['items_v2']);
self::assertNotEmpty($response['updateProductsInWishlist']['user_errors'], 'No user errors');
self::assertEquals(
'The wishlist item with ID "' . $wishlistItem['id'] . '" does not belong to the wishlist',
$response['updateProductsInWishlist']['user_errors'][0]['message']
);
}
/**
* update the wishlist by setting an qty = 0
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testUpdateProductInWishlistWithZeroQty()
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$qty = 0;
$description = 'Description for zero quantity';
$updateWishlistQuery = $this->getQuery($wishlistId, $wishlistItem['id'], $qty, $description);
$response = $this->graphQlMutation($updateWishlistQuery, [], '', $this->getHeaderMap());
self::assertEquals(1, $response['updateProductsInWishlist']['wishlist']['items_count']);
self::assertNotEmpty($response['updateProductsInWishlist']['wishlist']['items_v2'], 'empty wish list items');
self::assertCount(1, $response['updateProductsInWishlist']['wishlist']['items_v2']);
self::assertArrayHasKey('user_errors', $response['updateProductsInWishlist']);
self::assertCount(1, $response['updateProductsInWishlist']['user_errors']);
$message = 'The quantity of a wishlist item cannot be 0';
self::assertEquals(
$message,
$response['updateProductsInWishlist']['user_errors'][0]['message']
);
}
/**
* update the wishlist by setting qty to a valid value and no description
*
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
*/
public function testUpdateProductWithValidQtyAndNoDescription()
{
$wishlist = $this->getWishlist();
$customerWishlist = $wishlist['customer']['wishlists'][0];
$wishlistId = $customerWishlist['id'];
$wishlistItem = $customerWishlist['items_v2']['items'][0];
$qty = 2;
$updateWishlistQuery = $this->getQueryWithNoDescription($wishlistId, $wishlistItem['id'], $qty);
$response = $this->graphQlMutation($updateWishlistQuery, [], '', $this->getHeaderMap());
self::assertEquals(1, $response['updateProductsInWishlist']['wishlist']['items_count']);
self::assertNotEmpty($response['updateProductsInWishlist']['wishlist']['items_v2'], 'empty wish list items');
self::assertCount(1, $response['updateProductsInWishlist']['wishlist']['items_v2']['items']);
$itemsInWishlist = $response['updateProductsInWishlist']['wishlist']['items_v2']['items'][0];
self::assertEquals($qty, $itemsInWishlist['quantity']);
self::assertEquals('simple-1', $itemsInWishlist['product']['sku']);
}
/**
* Authentication header map
*
* @param string $username
* @param string $password
*
* @return array
*
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Returns GraphQl mutation string
*
* @param int $wishlistId
* @param int $wishlistItemId
* @param int $qty
* @param string $description
*
* @return string
*/
private function getQuery(
string $wishlistId,
string $wishlistItemId,
int $qty,
string $description
): string {
return <<<MUTATION
mutation {
updateProductsInWishlist(
wishlistId: "{$wishlistId}",
wishlistItems: [
{
wishlist_item_id: "{$wishlistItemId}"
quantity: {$qty}
description: "{$description}"
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
items_v2 {
items{
id
description
quantity
}
}
}
}
}
MUTATION;
}
/**
* Returns GraphQl mutation string
*
* @param int $wishlistId
* @param int $wishlistItemId
* @param int $qty
*
* @return string
*/
private function getQueryWithNoDescription(
string $wishlistId,
string $wishlistItemId,
int $qty
): string {
return <<<MUTATION
mutation {
updateProductsInWishlist(
wishlistId: "{$wishlistId}",
wishlistItems: [
{
wishlist_item_id: "{$wishlistItemId}"
quantity: {$qty}
}
]
) {
user_errors {
code
message
}
wishlist {
id
sharing_code
items_count
items_v2 {
items{
id
quantity
product {sku name}
}
}
}
}
}
MUTATION;
}
/**
* Get wishlist result
*
* @param string $username
* @return array
*
* @throws Exception
*/
public function getWishlist(string $username = 'customer@example.com'): array
{
return $this->graphQlQuery($this->getCustomerWishlistQuery(), [], '', $this->getHeaderMap($username));
}
/**
* Get customer wishlist query
*
* @return string
*/
private function getCustomerWishlistQuery(): string
{
return <<<QUERY
query {
customer {
wishlists {
id
items_count
sharing_code
updated_at
items_v2 {
items {
id
quantity
description
product {
sku
}
}
}
}
}
}
QUERY;
}
}
@@ -0,0 +1,140 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Wishlist;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Model\ResourceModel\Wishlist as WishlistResourceModel;
use Magento\Wishlist\Model\WishlistFactory;
class WishlistTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var WishlistFactory
*/
private $wishlistFactory;
/**
* @var WishlistResourceModel
*/
private $wishlistResource;
protected function setUp(): void
{
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->wishlistFactory = Bootstrap::getObjectManager()->get(WishlistFactory::class);
$this->wishlistResource = Bootstrap::getObjectManager()->get(WishlistResourceModel::class);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
* @magentoApiDataFixture Magento/Wishlist/_files/wishlist.php
*/
public function testGetCustomerWishlist(): void
{
/** @var \Magento\Wishlist\Model\Wishlist $wishlist */
$wishlist = $this->wishlistFactory->create();
$this->wishlistResource->load($wishlist, 1, 'customer_id');
/** @var Item $wishlistItem */
$wishlistItem = $wishlist->getItemCollection()->getFirstItem();
$wishlistItemProduct = $wishlistItem->getProduct();
$query =
<<<QUERY
{
wishlist {
items_count
name
sharing_code
updated_at
items {
id
qty
description
added_at
product {
sku
name
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', 'password')
);
$this->assertEquals($wishlist->getItemsCount(), $response['wishlist']['items_count']);
$this->assertEquals($wishlist->getName(), $response['wishlist']['name']);
$this->assertEquals($wishlist->getSharingCode(), $response['wishlist']['sharing_code']);
$this->assertEquals($wishlist->getUpdatedAt(), $response['wishlist']['updated_at']);
$this->assertEquals($wishlistItem->getId(), $response['wishlist']['items'][0]['id']);
$this->assertEquals($wishlistItem->getData('qty'), $response['wishlist']['items'][0]['qty']);
$this->assertEquals($wishlistItem->getDescription(), $response['wishlist']['items'][0]['description']);
$this->assertEquals($wishlistItem->getAddedAt(), $response['wishlist']['items'][0]['added_at']);
$this->assertEquals($wishlistItemProduct->getSku(), $response['wishlist']['items'][0]['product']['sku']);
$this->assertEquals($wishlistItemProduct->getName(), $response['wishlist']['items'][0]['product']['name']);
}
/**
* @magentoConfigFixture default_store wishlist/general/active 1
*/
public function testGetGuestWishlist()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current user cannot perform operations on wishlist');
$query =
<<<QUERY
{
wishlist {
items_count
name
sharing_code
updated_at
items {
id
qty
description
added_at
product {
sku
name
}
}
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}