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,686 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\GraphQl\PageCache\GraphQLPageCacheAbstract;
use Magento\Eav\Model\AttributeRepository;
use Magento\Framework\ObjectManagerInterface;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Fixture\Config as ConfigFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Test\Fixture\Group as StoreGroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\PageCache\Model\Config;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\GraphQlCache\Model\CacheId\CacheIdCalculator;
/**
* Test caching for attributes form GraphQL query_CUSTOMER_REGISTER_ADDRESS.
*/
class AttributesFormCacheTest extends GraphQLPageCacheAbstract
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var AttributeInterface[]
*/
private $attributesToRemove;
private const QUERY_CUSTOMER_REGISTER_ADDRESS = <<<QRY
{
attributesForm(formCode: "customer_register_address") {
items {
code
}
errors {
type
message
}
}
}
QRY;
private const QUERY_CUSTOMER_EDIT_ADDRESS = <<<QRY
{
attributesForm(formCode: "customer_account_edit") {
items {
code
}
errors {
type
message
}
}
}
QRY;
/**
* @inheritdoc
*/
public function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->attributesToRemove = [];
parent::setUp();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
array_walk($this->attributesToRemove, function ($attribute) use ($eavAttributeRepo) {
$eavAttributeRepo->delete($attribute);
});
parent::tearDown();
}
/**
* Obtains cache ID header from response
*
* @param string $query
* @return string
*/
private function getCacheIdHeader(string $query, array $headers = []): string
{
$response = $this->graphQlQueryWithResponseHeaders(
$query,
[],
'',
$headers
);
$this->assertArrayHasKey(CacheIdCalculator::CACHE_ID_HEADER, $response['headers']);
return $response['headers'][CacheIdCalculator::CACHE_ID_HEADER];
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
],
'attribute_1'
)
]
public function testAttributesFormCacheMissAndHit()
{
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
$cacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
/** First response should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT and attribute should be present in a cached response */
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
foreach ($response['body']['attributesForm']['items'] as $item) {
if (in_array($attribute1->getAttributeCode(), $item)) {
return;
}
}
$this->fail(sprintf(
"Attribute '%s' not found in query_CUSTOMER_REGISTER_ADDRESS response",
$attribute1->getAttributeCode()
));
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(WebsiteFixture::class, as: 'website2'),
DataFixture(
StoreGroupFixture::class,
[
'website_id' => '$website2.id$'
],
'store_group2'
),
DataFixture(
StoreFixture::class,
[
'store_group_id' => '$store_group2.id$'
],
'store2'
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
],
'attribute_1'
)
]
public function testAttributesFormCacheMissAndHitDifferentWebsites()
{
/** @var StoreInterface $store2 */
$store2 = DataFixtureStorageManager::getStorage()->get('store2');
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
$cacheIdStore1 = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
$response = $this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheIdStore1]
);
$this->assertContains($attribute1->getAttributeCode(), array_map(function ($attribute) {
return $attribute['code'];
}, $response['body']['attributesForm']['items']));
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheIdStore1]
);
// obtain CacheID for Store 2 - has to be different than for Store 1:
$cacheIdStore2 = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS, ['Store' => $store2->getCode()]);
// First query execution for a different store should result in a cache miss, while second one should be a hit
$response = $this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[
'Store' => $store2->getCode(),
CacheIdCalculator::CACHE_ID_HEADER => $cacheIdStore2
]
);
$this->assertContains($attribute1->getAttributeCode(), array_map(function ($attribute) {
return $attribute['code'];
}, $response['body']['attributesForm']['items']));
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[
'Store' => $store2->getCode(),
CacheIdCalculator::CACHE_ID_HEADER => $cacheIdStore2
]
);
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
],
'attribute_1'
)
]
public function testAttributesFormCacheInvalidateOnAttributeEdit()
{
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
$cacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
/** First response should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT */
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Modify attribute to invalidate cache */
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
$attribute1->setDefaultValue("default_value");
$eavAttributeRepo->save($attribute1);
/** Response after the change should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT */
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
foreach ($response['body']['attributesForm']['items'] as $item) {
if (in_array($attribute1->getAttributeCode(), $item)) {
return;
}
}
$this->fail(sprintf(
"Attribute '%s' not found in query_CUSTOMER_REGISTER_ADDRESS response",
$attribute1->getAttributeCode()
));
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH)
]
public function testAttributesFormCacheInvalidateOnAttributeCreate()
{
$cacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
/** First response should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT */
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Create new attribute and assign it to customer_register_address */
$attributeCreate = $this->objectManager->get(CustomerAttribute::class);
$attribute = $attributeCreate->apply([
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
]);
$this->attributesToRemove[] = $attribute;
/** Response after the creation of new attribute should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT */
$response = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
// verify created attribute is present in result
foreach ($response['body']['attributesForm']['items'] as $item) {
if (in_array($attribute->getAttributeCode(), $item)) {
return;
}
}
$this->fail(sprintf(
"Attribute '%s' not found in QUERY_CUSTOMER_REGISTER_ADDRESS response",
$attribute->getAttributeCode()
));
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
],
'attribute_1'
)
]
public function testAttributesFormCacheInvalidateOnAttributeDelete()
{
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
$cacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
/** First response should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Second response should be a HIT */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
/** Delete attribute to invalidate cache */
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
$deletedAttributeCode = $attribute1->getAttributeCode();
$eavAttributeRepo->delete($attribute1);
/** First response should be a MISS and attribute should NOT be present in a cached response */
$response = $this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
foreach ($response['body']['attributesForm']['items'] as $item) {
if (in_array($deletedAttributeCode, $item)) {
$this->fail(sprintf(
"Deleted attribute '%s' found in cached query_CUSTOMER_REGISTER_ADDRESS response",
$deletedAttributeCode
));
}
}
/** Second response should be a HIT */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $cacheId]
);
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
],
'attribute'
)
]
public function testAttributesFormCacheInvalidateOnAttributeAssignToForm()
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
$queryEditCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
$queryRegisterCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_REGISTER_ADDRESS);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Second response should be a HIT*/
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Assign $attribute to the 'customer_account_edit' form */
$attribute->setData('used_in_forms', ['customer_account_edit']);
$eavAttributeRepo->save($attribute);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Non-affected "customer_register_address" form -> MISS, then cached and HIT */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
/** Add $attribute to the 'customer_register_address' form */
$attribute->setData('used_in_forms', ['customer_account_edit', 'customer_register_address']);
$eavAttributeRepo->save($attribute);
/** 'customer_register_address' form should be invalidated first now */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
/** Remove $attribute from the 'customer_account_edit' form */
$attribute->setData('used_in_forms', ['customer_register_address']);
$eavAttributeRepo->save($attribute);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
/** Remove $attribute from remaining form(s) */
$attribute->setData('used_in_forms', []);
$eavAttributeRepo->save($attribute);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => [
'customer_register_address',
'customer_account_edit'
]
],
'shared_attribute'
)
]
public function testAttributesFormCacheInvalidateOnDeletedSharedAttribute()
{
/** @var AttributeInterface $sharedAttribute */
$sharedAttribute = DataFixtureStorageManager::getStorage()->get('shared_attribute');
$queryEditCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
$queryRegisterCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_REGISTER_ADDRESS);
/** First response should be a MISS from both queries */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
// /** Second response should be a HIT from both queries */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Delete attribute to invalidate both cached queries */
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
$deletedAttributeCode = $sharedAttribute->getAttributeCode();
$eavAttributeRepo->delete($sharedAttribute);
/** First response after deleting should be a MISS from both queries */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Second response should be a HIT from both queries as they are both cached back */
$responseRegisterAddress = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$responseEditAddress = $this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
// verify created attribute is NOT present in results
foreach ($responseRegisterAddress['body']['attributesForm']['items'] as $item) {
if (in_array($deletedAttributeCode, $item)) {
$this->fail(
sprintf(
"Attribute '%s' found in QUERY_CUSTOMER_REGISTER_ADDRESS response",
$deletedAttributeCode
)
);
}
}
foreach ($responseEditAddress['body']['attributesForm']['items'] as $item) {
if (in_array($deletedAttributeCode, $item)) {
$this->fail(
sprintf(
"Attribute '%s' found in QUERY_CUSTOMER_EDIT_ADDRESS response",
$deletedAttributeCode
)
);
}
}
}
#[
ConfigFixture(Config::XML_PAGECACHE_TYPE, Config::VARNISH),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => [
'customer_account_edit'
]
],
'non_shared_attribute_2'
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => [
'customer_register_address'
]
],
'non_shared_attribute_1'
)
]
public function testAttributesFormCacheInvalidateOnDeletedNonSharedAttribute()
{
/** @var AttributeInterface $nonSharedAttribute1 */
$nonSharedAttribute1 = DataFixtureStorageManager::getStorage()->get('non_shared_attribute_1');
/** @var AttributeInterface $nonSharedAttribute2 */
$nonSharedAttribute2 = DataFixtureStorageManager::getStorage()->get('non_shared_attribute_2');
$queryEditCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_EDIT_ADDRESS);
$queryRegisterCacheId = $this->getCacheIdHeader(self::QUERY_CUSTOMER_REGISTER_ADDRESS);
$eavAttributeRepo = $this->objectManager->get(AttributeRepository::class);
/** First response should be a MISS from both queries */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Second response should be a HIT from all queries */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Delete nonSharedAttribute1 to invalidate cache of 'customer_register_address' ONLY*/
$eavAttributeRepo->delete($nonSharedAttribute1);
/** First response from QUERY_CUSTOMER_REGISTER_ADDRESS after deleting $nonSharedAttribute1 should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
/** other cached queries should not be affected */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Second response should be a HIT from all queries */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** Delete nonSharedAttribute2 to invalidate cache of 'customer_account_edit' ONLY*/
$eavAttributeRepo->delete($nonSharedAttribute2);
/** First response from QUERY_CUSTOMER_EDIT_ADDRESS after deleting $nonSharedAttribute2 should be a MISS */
$this->assertCacheMissAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
/** other cached queries should not be affected */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
/** Second response should be a HIT from all queries */
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_REGISTER_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryRegisterCacheId]
);
$this->assertCacheHitAndReturnResponse(
self::QUERY_CUSTOMER_EDIT_ADDRESS,
[CacheIdCalculator::CACHE_ID_HEADER => $queryEditCacheId]
);
}
}
@@ -0,0 +1,183 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Test\Fixture\Group as StoreGroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test customer EAV form attributes metadata retrieval via GraphQL API
*/
class AttributesFormTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
attributesForm(formCode: "%s") {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address']
],
'attribute_1'
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_address_edit']
],
'attribute_2'
)
]
public function testAttributesForm(): void
{
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
/** @var AttributeInterface $attribute2 */
$attribute2 = DataFixtureStorageManager::getStorage()->get('attribute_2');
$result = $this->graphQlQuery(sprintf(self::QUERY, 'customer_register_address'));
$this->assertNotEmpty($result['attributesForm']['items']);
$codes = $this->getAttributeCodes($result['attributesForm']['items']);
$this->assertContains($attribute1->getAttributeCode(), $codes);
$this->assertContains('country_id', $codes);
$this->assertContains('region_id', $codes);
$this->assertNotContains($attribute2->getAttributeCode(), $codes);
}
public function testAttributesFormAdminHtmlForm(): void
{
$this->assertEquals(
[
'attributesForm' => [
'items' => [],
'errors' => [
[
'type' => 'ENTITY_NOT_FOUND',
'message' => 'Form "adminhtml_customer" could not be found.'
]
]
]
],
$this->graphQlQuery(sprintf(self::QUERY, 'adminhtml_customer'))
);
}
public function testAttributesFormDoesNotExist(): void
{
$this->assertEquals(
[
'attributesForm' => [
'items' => [],
'errors' => [
[
'type' => 'ENTITY_NOT_FOUND',
'message' => 'Form "not_existing_form" could not be found.'
]
]
]
],
$this->graphQlQuery(sprintf(self::QUERY, 'not_existing_form'))
);
}
#[
DataFixture(WebsiteFixture::class, as: 'website2'),
DataFixture(StoreGroupFixture::class, ['website_id' => '$website2.id$'], 'store_group2'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group2.id$'], 'store2'),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'used_in_forms' => ['customer_register_address'],
'website_id' => '$website2.id$',
'scope_is_visible' => 1,
'is_visible' => 0,
],
'attribute_1'
),
]
public function testAttributesFormScope(): void
{
/** @var AttributeInterface $attribute1 */
$attribute1 = DataFixtureStorageManager::getStorage()->get('attribute_1');
$result = $this->graphQlQuery(sprintf(self::QUERY, 'customer_register_address'));
$this->assertNotEmpty($result['attributesForm']['items']);
$codes = $this->getAttributeCodes($result['attributesForm']['items']);
$this->assertNotContains($attribute1->getAttributeCode(), $codes);
/** @var StoreInterface $store */
$store = DataFixtureStorageManager::getStorage()->get('store2');
$result = $this->graphQlQuery(
sprintf(self::QUERY, 'customer_register_address'),
[],
'',
['Store' => $store->getCode()]
);
$this->assertNotEmpty($result['attributesForm']['items']);
$codes = $this->getAttributeCodes($result['attributesForm']['items']);
$this->assertContains(
$attribute1->getAttributeCode(),
$codes,
sprintf(
"Attribute '%s' not found in query response in website scope",
$attribute1->getAttributeCode()
)
);
}
/**
* Retrieve an array of attribute codes based on an array of attributes data
*
* @param array $attributes
* @return array
*/
private function getAttributeCodes(array $attributes): array
{
return array_map(
function (array $attribute) {
return $attribute['code'];
},
$attributes
);
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class BooleanTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
options {
label
value
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'boolean',
'source_model' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean'
],
'attribute'
),
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'BOOLEAN',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'options' => [
[
'label' => 'Yes',
'value' => '1'
],
[
'label' => 'No',
'value' => '0'
]
]
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class CustomerAddressAttributesTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
frontend_class
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
input_filter
validate_rules {
name
value
}
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'frontend_input' => 'date',
'frontend_class' => 'hidden-for-virtual',
'default_value' => '2023-03-22 00:00:00',
'input_filter' => 'DATE',
'validate_rules' =>
'{"DATE_RANGE_MIN":"1679443200","DATE_RANGE_MAX":"1679875200","INPUT_VALIDATION":"DATE"}'
],
'attribute'
),
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$formattedValidationRules = Bootstrap::getObjectManager()->get(FormatValidationRulesCommand::class)->execute(
$attribute->getValidationRules()
);
$result = $this->graphQlQuery(
sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer_address')
);
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER_ADDRESS',
'frontend_input' => 'DATE',
'frontend_class' => 'hidden-for-virtual',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'input_filter' => $attribute->getInputFilter(),
'validate_rules' => $formattedValidationRules
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class DateTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
input_filter
validate_rules {
name
value
}
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'date',
'default_value' => '2023-03-22 00:00:00',
'input_filter' => 'DATE',
'validate_rules' => '
{"DATE_RANGE_MIN":"1679443200","DATE_RANGE_MAX":"1679875200","INPUT_VALIDATION":"DATE"}
'
],
'attribute'
),
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$formattedValidationRules = Bootstrap::getObjectManager()->get(FormatValidationRulesCommand::class)->execute(
$attribute->getValidationRules()
);
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'DATE',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'input_filter' => $attribute->getInputFilter(),
'validate_rules' => $formattedValidationRules
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class FileTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
validate_rules {
name
value
}
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'file',
'validate_rules' => '{"MAX_FILE_SIZE":"10000000","FILE_EXTENSIONS":"PDF"}'
],
'attribute'
)
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$formattedValidationRules = Bootstrap::getObjectManager()->get(FormatValidationRulesCommand::class)->execute(
$attribute->getValidationRules()
);
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'FILE',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'validate_rules' => $formattedValidationRules
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,29 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
/**
* Command to format validation rules appropriately for testing purposes.
*/
class FormatValidationRulesCommand
{
/**
* Execute command to format validation rules provided as argument.
*
* @param array $validationRules
* @return array
*/
public function execute(array $validationRules): array
{
$formattedValidationRules = [];
foreach ($validationRules as $key => $value) {
$formattedValidationRules[] = ['name' => $key, 'value' => $value];
}
return $formattedValidationRules;
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class ImageTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
validate_rules {
name
value
}
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'image',
'validate_rules' => '{"MAX_FILE_SIZE":"10000","MAX_IMAGE_WIDTH":"100"}'
],
'attribute'
)
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$formattedValidationRules = Bootstrap::getObjectManager()->get(FormatValidationRulesCommand::class)->execute(
$attribute->getValidationRules()
);
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'IMAGE',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'validate_rules' => $formattedValidationRules
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class MultilineTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
input_filter
multiline_count
sort_order
validate_rules {
name
value
}
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'multiline',
'default_value' => 'this is line one
this is line two',
'input_filter' => 'STRIPTAGS',
'multiline_count' => 2,
'sort_order' => 3,
'validate_rules' => '{"MIN_TEXT_LENGTH":"100","MAX_TEXT_LENGTH":"200","INPUT_VALIDATION":"EMAIL"}',
],
'attribute'
)
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$formattedValidationRules = Bootstrap::getObjectManager()->get(FormatValidationRulesCommand::class)->execute(
$attribute->getValidationRules()
);
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'MULTILINE',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'input_filter' => $attribute->getInputFilter(),
'multiline_count' => $attribute->getMultilineCount(),
'sort_order' => $attribute->getSortOrder(),
'validate_rules' => $formattedValidationRules
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\Attribute;
use Magento\Eav\Test\Fixture\AttributeOption;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class MultiselectTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
default_value
options {
label
value
is_default
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
Attribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'multiselect',
'source_model' => Table::class
],
'attribute'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 10
],
'option1'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 20,
'is_default' => true
],
'option2'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 30,
'is_default' => true
],
'option3'
),
]
public function testMetadata(): void
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
/** @var AttributeOptionInterface $option1 */
$option1 = DataFixtureStorageManager::getStorage()->get('option1');
/** @var AttributeOptionInterface $option2 */
$option2 = DataFixtureStorageManager::getStorage()->get('option2');
/** @var AttributeOptionInterface $option3 */
$option3 = DataFixtureStorageManager::getStorage()->get('option3');
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'default_value' => $option3->getValue() . ',' . $option2->getValue(),
'options' => [
$this->getOptionData($option1),
$this->getOptionData($option2),
$this->getOptionData($option3)
]
]
],
'errors' => []
]
],
$result
);
$this->assertEquals($option2->getIsDefault(), true);
$this->assertEquals($option3->getIsDefault(), true);
}
/**
* @param AttributeOptionInterface $option
* @return array
*/
private function getOptionData(AttributeOptionInterface $option): array
{
return [
'label' => $option->getLabel(),
'value' => $option->getValue(),
'is_default' => $option->getIsDefault()
];
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Test\Fixture\Attribute;
use Magento\Eav\Test\Fixture\AttributeOption;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class SelectTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
options {
label
value
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
Attribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'select'
],
'attribute'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 10
],
'option1'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 20
],
'option2'
),
]
public function testMetadata(): void
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
/** @var AttributeOptionInterface $option1 */
$option1 = DataFixtureStorageManager::getStorage()->get('option1');
/** @var AttributeOptionInterface $option2 */
$option2 = DataFixtureStorageManager::getStorage()->get('option2');
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'options' => [
$option1->getData(),
$option2->getData()
]
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,252 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Test\Fixture\Attribute;
use Magento\Eav\Test\Fixture\AttributeOption;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Test\Fixture\Store;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test customer EAV attribute options retrieval via GraphQL API
*/
#[
DataFixture(Store::class, as: 'store_1'),
DataFixture(Store::class, as: 'store_2'),
DataFixture(
Attribute::class,
[
'frontend_labels' => [
[
'store_id' => 0,
'label' => 'height'
],
[
'store_id' => '$store_1.id$',
'label' => 'hair'
],
[
'store_id' => '$store_2.id$',
'label' => 'eyes'
],
],
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'select'
],
'attribute'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 10,
'store_labels' => [
[
'store_id' => 0,
'label' => 'tall'
],
[
'store_id' => '$store_1.id$',
'label' => 'red'
],
[
'store_id' => '$store_2.id$',
'label' => 'green'
]
],
],
'option1'
),
DataFixture(
AttributeOption::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$attribute.attribute_code$',
'sort_order' => 20,
'store_labels' => [
[
'store_id' => 0,
'label' => 'short'
],
[
'store_id' => '$store_1.id$',
'label' => 'brown'
],
[
'store_id' => '$store_2.id$',
'label' => 'blue'
]
],
],
'option2'
),
]
class StoreViewOptionsTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
options {
label
}
}
errors {
type
message
}
}
}
QRY;
public function testAttributeLabelsNoStoreViews(): void
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
/** @var AttributeOptionInterface $option1 */
$option1 = DataFixtureStorageManager::getStorage()->get('option1');
/** @var AttributeOptionInterface $option2 */
$option2 = DataFixtureStorageManager::getStorage()->get('option2');
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getDefaultFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'SELECT',
'is_required' => false,
'default_value' => '',
'is_unique' => false,
'options' => [
[
'label' => $option1->getLabel()
],
[
'label' => $option2->getLabel()
],
]
]
],
'errors' => []
]
],
$this->graphQlQuery(
sprintf(
self::QUERY,
$attribute->getAttributeCode(),
'customer'
)
)
);
}
public function testAttributeLabelsMultipleStoreViews(): void
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
/** @var StoreInterface $store1 */
$store1 = DataFixtureStorageManager::getStorage()->get('store_1');
/** @var StoreInterface $store2 */
$store2 = DataFixtureStorageManager::getStorage()->get('store_2');
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel($store1->getId()),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'SELECT',
'is_required' => false,
'default_value' => '',
'is_unique' => false,
'options' => [
[
'label' => 'red'
],
[
'label' => 'brown'
],
]
]
],
'errors' => []
]
],
$this->graphQlQuery(
sprintf(
self::QUERY,
$attribute->getAttributeCode(),
'customer'
),
[],
'',
['Store' => $store1->getCode()]
)
);
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel($store2->getId()),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'SELECT',
'is_required' => false,
'default_value' => '',
'is_unique' => false,
'options' => [
[
'label' => 'green'
],
[
'label' => 'blue'
],
]
]
],
'errors' => []
]
],
$this->graphQlQuery(
sprintf(
self::QUERY,
$attribute->getAttributeCode(),
'customer'
),
[],
'',
['Store' => $store2->getCode()]
)
);
}
}
@@ -0,0 +1,124 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Test\Fixture\Attribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class TextTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
Attribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER
],
'attribute'
)
]
public function testTextField(): void
{
/** @var AttributeInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getDefaultFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'TEXT',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false
]
],
'errors' => []
]
],
$this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'))
);
}
public function testErrorEntityNotFound(): void
{
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [],
'errors' => [
[
'type' => 'ENTITY_NOT_FOUND',
'message' => 'Entity "non_existing_entity_type" could not be found.'
]
]
]
],
$this->graphQlQuery(
sprintf(
self::QUERY,
'lastname',
'non_existing_entity_type'
)
)
);
}
public function testErrorAttributeNotFound(): void
{
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [],
'errors' => [
[
'type' => 'ATTRIBUTE_NOT_FOUND',
'message' => 'Attribute code "non_existing_code" could not be found.'
]
]
]
],
$this->graphQlQuery(
sprintf(
self::QUERY,
'non_existing_code',
'customer'
)
)
);
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer\Attribute;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test catalog EAV attributes metadata retrieval via GraphQL API
*/
class TextareaTest extends GraphQlAbstract
{
private const QUERY = <<<QRY
{
customAttributeMetadataV2(attributes: [{attribute_code: "%s", entity_type: "%s"}]) {
items {
code
label
entity_type
frontend_input
is_required
default_value
is_unique
... on CustomerAttributeMetadata {
input_filter
sort_order
}
}
errors {
type
message
}
}
}
QRY;
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'textarea',
'default_value' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus bibendum finibus' .
'quam, at vulputate quam feugiat tincidunt. Pellentesque venenatis nunc eget dolor' .
'dictum, vel ultricies orci facilisis. Sed hendrerit arcu tristique dui molestie, ' .
'sit amet scelerisque nibh scelerisque. Nulla sed tellus eget tellus volutpat ' .
'vestibulum. Mauris molestie erat sed odio maximus accumsan. Morbi velit felis, ' .
'tristique et lectus sollicitudin, laoreet aliquam nisl. Suspendisse vel ante at ' .
'metus mattis ultrices non nec libero. Cras odio nunc, eleifend vitae interdum a, ' .
'porttitor a dolor. Praesent mi odio, hendrerit quis consequat nec, vestibulum ' .
'vitae justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin auctor' .
'ac quam id rhoncus. Proin vel orci eu justo cursus vestibulum.',
'input_filter' => 'ESCAPEHTML',
'sort_order' => 4,
],
'attribute'
)
]
public function testMetadata(): void
{
/** @var AttributeMetadataInterface $attribute */
$attribute = DataFixtureStorageManager::getStorage()->get('attribute');
$result = $this->graphQlQuery(sprintf(self::QUERY, $attribute->getAttributeCode(), 'customer'));
$this->assertEquals(
[
'customAttributeMetadataV2' => [
'items' => [
[
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
'entity_type' => 'CUSTOMER',
'frontend_input' => 'TEXTAREA',
'is_required' => false,
'default_value' => $attribute->getDefaultValue(),
'is_unique' => false,
'input_filter' => $attribute->getInputFilter(),
'sort_order' => $attribute->getSortOrder(),
]
],
'errors' => []
]
],
$result
);
}
}
@@ -0,0 +1,255 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\CustomerAuthUpdate;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test change customer password
*/
class ChangeCustomerPasswordTest extends GraphQlAbstract
{
/**
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var CustomerAuthUpdate
*/
private $customerAuthUpdate;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
protected function setUp(): void
{
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->accountManagement = Bootstrap::getObjectManager()->get(AccountManagementInterface::class);
$this->customerRegistry = Bootstrap::getObjectManager()->get(CustomerRegistry::class);
$this->customerAuthUpdate = Bootstrap::getObjectManager()->get(CustomerAuthUpdate::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePassword()
{
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$newPassword = 'anotherPassword1';
$query = $this->getQuery($currentPassword, $newPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$response = $this->graphQlMutation($query, [], '', $headerMap);
$this->assertEquals($customerEmail, $response['changeCustomerPassword']['email']);
$this->assertEmpty(
$response['changeCustomerPassword']['custom_attributes'],
'custom_attributes should not contain any static values'
);
try {
// registry contains the old password hash so needs to be reset
$this->customerRegistry->removeByEmail($customerEmail);
$this->accountManagement->authenticate($customerEmail, $newPassword);
} catch (LocalizedException $e) {
$this->fail('Password was not changed: ' . $e->getMessage());
}
}
/**
*/
public function testChangePasswordIfUserIsNotAuthorizedTest()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = $this->getQuery('currentpassword', 'newpassword');
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangeWeakPassword()
{
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$newPassword = 'weakpass';
$query = $this->getQuery($currentPassword, $newPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$this->expectException(\Exception::class);
$this->expectExceptionMessageMatches('/Minimum of different classes of characters in password is.*/');
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePasswordIfPasswordIsInvalid()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Invalid login or password.');
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$newPassword = 'anotherPassword1';
$incorrectCurrentPassword = 'password-incorrect';
$query = $this->getQuery($incorrectCurrentPassword, $newPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePasswordIfCurrentPasswordIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Specify the "currentPassword" value.');
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$newPassword = 'anotherPassword1';
$incorrectCurrentPassword = '';
$query = $this->getQuery($incorrectCurrentPassword, $newPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePasswordIfNewPasswordIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Specify the "newPassword" value.');
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$incorrectNewPassword = '';
$query = $this->getQuery($currentPassword, $incorrectNewPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePasswordIfCustomerIsLocked()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is locked.');
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$newPassword = 'anotherPassword1';
$this->lockCustomer(1);
$query = $this->getQuery($currentPassword, $newPassword);
$headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$this->graphQlMutation($query, [], '', $headerMap);
}
/**
* @param int $customerId
*
* @return void
* @throws NoSuchEntityException
*/
private function lockCustomer(int $customerId): void
{
$customerSecure = $this->customerRegistry->retrieveSecureData($customerId);
$customerSecure->setLockExpires('2030-12-31 00:00:00');
$this->customerAuthUpdate->saveAuth($customerId);
}
/**
* @param $currentPassword
* @param $newPassword
*
* @return string
*/
private function getQuery($currentPassword, $newPassword)
{
$query = <<<QUERY
mutation {
changeCustomerPassword(
currentPassword: "$currentPassword",
newPassword: "$newPassword"
) {
id
email
firstname
lastname
custom_attributes {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
value
label
}
}
}
}
}
QUERY;
return $query;
}
/**
* @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,151 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Test\Fixture\Customer as CustomerFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for confirm customer email
*/
#[
DataFixture(
CustomerFixture::class,
[
'email' => 'customer@example.com',
'confirmation' => 'abcde',
],
'customer'
)
]
class ConfirmEmailTest extends GraphQlAbstract
{
private const QUERY = <<<QUERY
mutation {
confirmEmail(input: {
email: "%s"
confirmation_key: "%s"
}) {
customer {
email
}
}
}
QUERY;
/**
* @var string
*/
private const PASSWORD = 'password';
/**
* @return void
* @throws AuthenticationException
*/
public function testConfirmEmail()
{
$response = $this->graphQlMutation(
sprintf(
self::QUERY,
'customer@example.com',
'abcde',
),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', self::PASSWORD)
);
$this->assertEquals(
[
'confirmEmail' => [
'customer' => [
'email' => 'customer@example.com'
]
]
],
$response
);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is already active.');
$this->graphQlMutation(
sprintf(
self::QUERY,
'customer@example.com',
'abcde',
),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', self::PASSWORD)
);
}
/**
* @return void
* @throws AuthenticationException
*/
public function testConfirmEmailWrongEmail()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Email is invalid');
$this->graphQlMutation(
sprintf(
self::QUERY,
'bad-email',
'abcde',
),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', self::PASSWORD)
);
}
/**
* @return void
* @throws AuthenticationException
*/
public function testConfirmEmailWrongConfirmation()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The confirmation token is invalid. Verify the token and try again.');
$this->graphQlMutation(
sprintf(
self::QUERY,
'customer@example.com',
'wrong-confirmation',
),
[],
'',
$this->getCustomerAuthHeaders('customer@example.com', self::PASSWORD)
);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = Bootstrap::getObjectManager()->get(
CustomerTokenServiceInterface::class
)->createCustomerAccessToken(
$email,
$password
);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,177 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Fixture\DataFixture;
/**
* Tests for confirmation status
*/
class ConfirmationStatusTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
#[
Config('customer/create_account/confirm', 0),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
],
'customer'
)
]
public function testGetConfirmationStatusConfirmationNotRequiredTest()
{
$customer = DataFixtureStorageManager::getStorage()->get('customer');
$query = <<<QUERY
query {
customer {
confirmation_status
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getHeaderMap($customer->getEmail(), 'password')
);
$this->assertEquals(
strtoupper(AccountManagementInterface::ACCOUNT_CONFIRMATION_NOT_REQUIRED),
$response['customer']['confirmation_status']
);
}
#[
Config('customer/create_account/confirm', 1),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
],
'customer'
)
]
public function testGetConfirmationStatusConfirmedTest()
{
$customer = DataFixtureStorageManager::getStorage()->get('customer');
$query = <<<QUERY
query {
customer {
confirmation_status
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getHeaderMap($customer->getEmail(), 'password')
);
$this->assertEquals(
strtoupper(AccountManagementInterface::ACCOUNT_CONFIRMED),
$response['customer']['confirmation_status']
);
}
#[
Config('customer/create_account/confirm', 1),
DataFixture(
Customer::class,
[
'email' => 'another@example.com',
],
'customer'
)
]
public function testGetConfirmationStatusConfirmationRequiredTest()
{
$this->expectExceptionMessage("This account isn't confirmed. Verify and try again.");
/** @var CustomerInterface $customer */
$customer = DataFixtureStorageManager::getStorage()->get('customer');
$headersMap = $this->getHeaderMap($customer->getEmail(), 'password');
$customer->setConfirmation(AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED);
$this->customerRepository->save($this->customerRepository->get($customer->getEmail()));
$query = <<<QUERY
query {
customer {
confirmation_status
}
}
QUERY;
$this->graphQlQuery(
$query,
[],
'',
$headersMap
);
}
#[
DataFixture(
Customer::class,
[
'email' => 'test@example.com',
],
'customer'
)
]
public function testGetConfirmationStatusIfUserIsNotAuthorizedTest()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
query {
customer {
confirmation_status
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @param string $email
* @param string $password
*
* @return array
* @throws AuthenticationException
*/
private function getHeaderMap(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,868 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Create customer address tests
*/
class CreateCustomerAddressTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->addressRepository = Bootstrap::getObjectManager()->get(AddressRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddress()
{
$newAddress = [
'region' => [
'region' => 'Arizona',
'region_id' => 4,
'region_code' => 'AZ'
],
'country_code' => 'US',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'fax' => '123123123',
'postcode' => '7777',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => false
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region: "{$newAddress['region']['region']}"
region_id: {$newAddress['region']['region_id']}
region_code: "{$newAddress['region']['region_code']}"
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
fax: "{$newAddress['fax']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
middlename: "{$newAddress['middlename']}"
prefix: "{$newAddress['prefix']}"
suffix: "{$newAddress['suffix']}"
vat_id: "{$newAddress['vat_id']}"
default_shipping: true
default_billing: false
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
fax
postcode
city
firstname
lastname
middlename
prefix
suffix
vat_id
default_shipping
default_billing
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('createCustomerAddress', $response);
$this->assertArrayHasKey('customer_id', $response['createCustomerAddress']);
$this->assertNull($response['createCustomerAddress']['customer_id']);
$this->assertArrayHasKey('id', $response['createCustomerAddress']);
$address = $this->addressRepository->getById($response['createCustomerAddress']['id']);
$this->assertEquals($address->getId(), $response['createCustomerAddress']['id']);
$address->setCustomerId(null);
$this->assertCustomerAddressesFields($address, $response['createCustomerAddress']);
$this->assertCustomerAddressesFields($address, $newAddress);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressWithNoRegionId()
{
$newAddress = [
'region' => [
'region' => 'Arizona',
'region_id' => 4,
'region_code' => 'AZ'
],
'country_code' => 'US',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'fax' => '123123123',
'postcode' => '7777',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => false
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region: "{$newAddress['region']['region']}"
region_id: {$newAddress['region']['region_id']}
region_code: "{$newAddress['region']['region_code']}"
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
fax: "{$newAddress['fax']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
middlename: "{$newAddress['middlename']}"
prefix: "{$newAddress['prefix']}"
suffix: "{$newAddress['suffix']}"
vat_id: "{$newAddress['vat_id']}"
default_shipping: true
default_billing: false
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
fax
postcode
city
firstname
lastname
middlename
prefix
suffix
vat_id
default_shipping
default_billing
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('createCustomerAddress', $response);
$this->assertArrayHasKey('customer_id', $response['createCustomerAddress']);
$this->assertNull($response['createCustomerAddress']['customer_id']);
$this->assertArrayHasKey('id', $response['createCustomerAddress']);
$address = $this->addressRepository->getById($response['createCustomerAddress']['id']);
$this->assertEquals($address->getId(), $response['createCustomerAddress']['id']);
$address->setCustomerId(null);
$this->assertCustomerAddressesFields($address, $response['createCustomerAddress']);
$this->assertCustomerAddressesFields($address, $newAddress);
}
/**
* Test case for deprecated `country_id` field.
*
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressWithCountryId()
{
$newAddress = [
'region' => [
'region' => 'Arizona',
'region_id' => 4,
'region_code' => 'AZ'
],
'country_id' => 'US',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'fax' => '123123123',
'postcode' => '7777',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => false
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region: "{$newAddress['region']['region']}"
region_id: {$newAddress['region']['region_id']}
region_code: "{$newAddress['region']['region_code']}"
}
country_code: {$newAddress['country_id']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
fax: "{$newAddress['fax']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
middlename: "{$newAddress['middlename']}"
prefix: "{$newAddress['prefix']}"
suffix: "{$newAddress['suffix']}"
vat_id: "{$newAddress['vat_id']}"
default_shipping: true
default_billing: false
}) {
country_id
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('createCustomerAddress', $response);
$this->assertEquals($newAddress['country_id'], $response['createCustomerAddress']['country_id']);
}
/**
*/
public function testCreateCustomerAddressIfUserIsNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$mutation
= <<<MUTATION
mutation{
createCustomerAddress(input: {
prefix: "Mr."
firstname: "John"
middlename: "A"
lastname: "Smith"
telephone: "123456789"
street: ["Line 1", "Line 2"]
city: "Test City"
region: {
region_id: 1
}
country_code: US
postcode: "9999"
default_shipping: true
default_billing: false
}) {
id
}
}
MUTATION;
$this->graphQlMutation($mutation);
}
/**
* Verify customers with valid credentials create new address
* with missing required Firstname attribute
*
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
*/
public function testCreateCustomerAddressWithMissingAttribute()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameters are missing: firstname');
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region_id: 1
}
country_code: US
street: ["Line 1 Street","Line 2"]
company: "Company name"
telephone: "123456789"
fax: "123123123"
postcode: "7777"
city: "City Name"
firstname: ""
lastname: "Phillis"
}) {
id
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
*/
public function testCreateCustomerAddressWithMissingInput()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('"input" value should be specified');
$userName = 'customer@example.com';
$password = 'password';
$mutation = <<<MUTATION
mutation {
createCustomerAddress(
input: {}
) {
city
}
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressWithRedundantStreetLine()
{
$newAddress = [
'region' => [
'region' => 'Arizona',
'region_id' => 4,
'region_code' => 'AZ'
],
'country_code' => 'US',
'street' => ['Line 1 Street', 'Line 2', 'Line 3'],
'company' => 'Company name',
'telephone' => '123456789',
'fax' => '123123123',
'postcode' => '7777',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => false
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region: "{$newAddress['region']['region']}"
region_id: {$newAddress['region']['region_id']}
region_code: "{$newAddress['region']['region_code']}"
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}","{$newAddress['street'][2]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
fax: "{$newAddress['fax']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
middlename: "{$newAddress['middlename']}"
prefix: "{$newAddress['prefix']}"
suffix: "{$newAddress['suffix']}"
vat_id: "{$newAddress['vat_id']}"
default_shipping: true
default_billing: false
}) {
id
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
self::expectExceptionMessage('"Street Address" cannot contain more than 2 lines.');
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @magentoConfigFixture default_store general/country/optional_zip_countries UA
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressWithOptionalZipCode()
{
$newAddress = [
'country_code' => 'VA',
'postcode' => '00120',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'fax' => '123123123',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => false
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
country_code: {$newAddress['country_code']}
postcode: "{$newAddress['postcode']}"
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
fax: "{$newAddress['fax']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
middlename: "{$newAddress['middlename']}"
prefix: "{$newAddress['prefix']}"
suffix: "{$newAddress['suffix']}"
vat_id: "{$newAddress['vat_id']}"
default_shipping: true
default_billing: false
}) {
id
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$response = $this->graphQlMutation(
$mutation,
[],
'',
$this->getCustomerAuthHeaders($userName, $password)
);
$this->assertNotEmpty($response['createCustomerAddress']['id']);
}
/**
* Create new address with invalid input
*
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @dataProvider invalidInputDataProvider
* @param string $input
* @param $exceptionMessage
* @throws Exception
*/
public function testCreateCustomerAddressWithInvalidInput($input, $exceptionMessage)
{
$mutation
= <<<MUTATION
mutation {
createCustomerAddress($input) {
id
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
self::expectException(Exception::class);
self::expectExceptionMessage($exceptionMessage);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressRegionCodeWithoutRegionId()
{
$newAddress = [
'region' => [
'region_code' => 'NY',
],
'country_code' => 'US',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'postcode' => '10019',
'city' => 'Manhattan',
'firstname' => 'Adam',
'lastname' => 'Phillis'
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region_code: "{$newAddress['region']['region_code']}"
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
postcode
city
firstname
lastname
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$this->expectExceptionMessage('A region_id is required for the specified country code');
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressRegionCodeWithRegionIdForNoRegionRequiredCountry()
{
$newAddress = [
'region' => [
'region_code' => 'NY',
'region_id' => 43,
],
'country_code' => 'GB',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'postcode' => '10019',
'city' => 'London',
'firstname' => 'Adams',
'lastname' => 'Phillips'
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region_code: "{$newAddress['region']['region_code']}"
region_id: {$newAddress['region']['region_id']}
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
postcode
city
firstname
lastname
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$this->expectExceptionMessage('The region_id does not match the selected country or region');
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressRegionCodeWithWrongRegionIdForRegionRequiredCountry()
{
$newAddress = [
'region' => [
'region_code' => 'NY',
'region_id' => 53,
],
'country_code' => 'US',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'postcode' => '10019',
'city' => 'London',
'firstname' => 'Adams',
'lastname' => 'Phillips'
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region_code: "{$newAddress['region']['region_code']}"
region_id: {$newAddress['region']['region_id']}
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
postcode
city
firstname
lastname
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$this->expectExceptionMessage('The region_id does not match the selected country or region');
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressRegionCodeWithOutRegionIdForNoRegionRequiredCountry()
{
$newAddress = [
'region' => [
'region_code' => 'some',
'region' => 'some region'
],
'country_code' => 'GB',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company name',
'telephone' => '123456789',
'postcode' => '10019',
'city' => 'London',
'firstname' => 'Adams',
'lastname' => 'Phillips'
];
$mutation
= <<<MUTATION
mutation {
createCustomerAddress(input: {
region: {
region_code: "{$newAddress['region']['region_code']}"
region: "{$newAddress['region']['region']}"
}
country_code: {$newAddress['country_code']}
street: ["{$newAddress['street'][0]}","{$newAddress['street'][1]}"]
company: "{$newAddress['company']}"
telephone: "{$newAddress['telephone']}"
postcode: "{$newAddress['postcode']}"
city: "{$newAddress['city']}"
firstname: "{$newAddress['firstname']}"
lastname: "{$newAddress['lastname']}"
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
postcode
city
firstname
lastname
}
}
MUTATION;
$userName = 'customer@example.com';
$password = 'password';
$response = $this->graphQlMutation(
$mutation,
[],
'',
$this->getCustomerAuthHeaders($userName, $password)
);
$this->assertEquals("some region", $response["createCustomerAddress"]["region"]["region"]);
$this->assertEquals("some", $response["createCustomerAddress"]["region"]["region_code"]);
}
/**
* @return array
*/
public function invalidInputDataProvider()
{
return [
['', 'Syntax Error: Expected Name, found )'],
['input: ""', 'Expected value of type "CustomerAddressInput", found "".'],
['input: "foo"', 'Expected value of type "CustomerAddressInput", found "foo".']
];
}
/**
* Verify the fields for Customer address
*
* @param AddressInterface $address
* @param array $actualResponse
* @param string $countryFieldName
*/
private function assertCustomerAddressesFields(
AddressInterface $address,
array $actualResponse
): void {
/** @var $addresses */
$assertionMap = [
['response_field' => 'country_code', 'expected_value' => $address->getCountryId()],
['response_field' => 'street', 'expected_value' => $address->getStreet()],
['response_field' => 'company', 'expected_value' => $address->getCompany()],
['response_field' => 'telephone', 'expected_value' => $address->getTelephone()],
['response_field' => 'fax', 'expected_value' => $address->getFax()],
['response_field' => 'postcode', 'expected_value' => $address->getPostcode()],
['response_field' => 'city', 'expected_value' => $address->getCity()],
['response_field' => 'firstname', 'expected_value' => $address->getFirstname()],
['response_field' => 'lastname', 'expected_value' => $address->getLastname()],
['response_field' => 'middlename', 'expected_value' => $address->getMiddlename()],
['response_field' => 'prefix', 'expected_value' => $address->getPrefix()],
['response_field' => 'suffix', 'expected_value' => $address->getSuffix()],
['response_field' => 'vat_id', 'expected_value' => $address->getVatId()],
['response_field' => 'default_shipping', 'expected_value' => (bool)$address->isDefaultShipping()],
['response_field' => 'default_billing', 'expected_value' => (bool)$address->isDefaultBilling()],
];
$this->assertResponseFields($actualResponse, $assertionMap);
$this->assertIsArray([$actualResponse['region']], "region field must be of an array type.");
$assertionRegionMap = [
['response_field' => 'region', 'expected_value' => $address->getRegion()->getRegion()],
['response_field' => 'region_code', 'expected_value' => $address->getRegion()->getRegionCode()],
['response_field' => 'region_id', 'expected_value' => $address->getRegion()->getRegionId()]
];
$this->assertResponseFields($actualResponse['region'], $assertionRegionMap);
}
/**
* @param string $email
* @param string $password
* @return array
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,404 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for create customer address with custom attributes V2
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_group_id' => 1,
'attribute_code' => 'simple_attribute',
'sort_order' => 2
],
'simple_attribute',
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_group_id' => 1,
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'multiselect_attribute',
'frontend_input' => 'multiselect',
'sort_order' => 1
],
'multiselect_attribute',
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 1',
'sort_order' => 20
],
'multiselect_attribute_option1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 2',
'sort_order' => 30
],
'multiselect_attribute_option2'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 3',
'sort_order' => 10
],
'multiselect_attribute_option3'
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
],
'customer'
)
]
class CreateCustomerAddressWithCustomAttributesV2Test extends GraphQlAbstract
{
/**
* @var string
*/
private $currentPassword = 'password';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var AttributeMetadataInterface|null
*/
private $simple_attribute;
/**
* @var AttributeMetadataInterface|null
*/
private $multiselect_attribute;
/**
* @var AttributeOptionInterface|null
*/
private $option2;
/**
* @var AttributeOptionInterface|null
*/
private $option3;
/**
* @var CustomerInterface|null
*/
private $customer;
/**
* @return void
* @throws LocalizedException
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->simple_attribute = DataFixtureStorageManager::getStorage()->get('simple_attribute');
$this->multiselect_attribute = DataFixtureStorageManager::getStorage()->get('multiselect_attribute');
$this->option2 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option2');
$this->option3 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option3');
$this->customer = DataFixtureStorageManager::getStorage()->get('customer');
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreateCustomerAddressWithCustomAttributesV2()
{
$query = <<<QUERY
mutation {
createCustomerAddress(input: {
region: {
region_id: 4
region: "Arizona"
region_code: "AZ"
}
country_code: US
street: ["123 Main Street"]
telephone: "7777777777"
postcode: "77777"
city: "Phoenix"
firstname: "Bob"
lastname: "Loblaw"
default_shipping: true
default_billing: false
custom_attributesV2: [
{
attribute_code: "%s"
value: "%s"
},
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
region {
region
region_code
}
country_code
street
telephone
postcode
city
default_shipping
default_billing
custom_attributesV2 {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
value
label
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation(
sprintf(
$query,
$this->simple_attribute->getAttributeCode(),
"brand new customer address value",
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'createCustomerAddress' =>
[
'region' => [
'region' => 'Arizona',
'region_code' => 'AZ'
],
'country_code' => 'US',
'street' => [
'123 Main Street'
],
'telephone' => '7777777777',
'postcode' => '77777',
'city' => 'Phoenix',
'default_shipping' => true,
'default_billing' => false,
'custom_attributesV2' =>
[
0 =>
[
'code' => $this->multiselect_attribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->option3->getLabel(),
'value' => $this->option3->getValue()
],
[
'label' => $this->option2->getLabel(),
'value' => $this->option2->getValue()
]
]
],
1 =>
[
'code' => $this->simple_attribute->getAttributeCode(),
'value' => 'brand new customer address value'
]
],
],
],
$response
);
}
/**
* @return void
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testAttemptToCreateCustomerAddressPassingNonExistingOption()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Attribute multiselect_attribute does not contain option with Id 1345");
$query = <<<QUERY
mutation {
createCustomerAddress(input: {
region: {
region_id: 4
region: "Arizona"
region_code: "AZ"
}
country_code: US
street: ["123 Main Street"]
telephone: "7777777777"
postcode: "77777"
city: "Phoenix"
firstname: "Bob"
lastname: "Loblaw"
default_shipping: true
default_billing: false
custom_attributesV2: [
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
custom_attributesV2 {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
value
label
}
}
}
}
}
QUERY;
$this->graphQlMutation(
sprintf(
$query,
$this->multiselect_attribute->getAttributeCode(),
"1345"
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
}
/**
* @return void
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testAttemptToCreateCustomerAddressPassingSelectedOptionsToDeprecatedCustomAttributes()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
"Field \"selected_options\" is not defined by type \"CustomerAddressAttributeInput\""
);
$query = <<<QUERY
mutation {
createCustomerAddress(input: {
region: {
region_id: 4
region: "Arizona"
region_code: "AZ"
}
country_code: US
street: ["123 Main Street"]
telephone: "7777777777"
postcode: "77777"
city: "Phoenix"
firstname: "Bob"
lastname: "Loblaw"
default_shipping: true
default_billing: false
custom_attributes: [
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
custom_attributes {
attribute_code
value
selected_options {
value
label
}
}
}
}
QUERY;
$this->graphQlMutation(
sprintf(
$query,
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
}
/**
* @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,398 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for create customer functionality
*/
class CreateCustomerTest extends GraphQlAbstract
{
/**
* @var Registry
*/
private $registry;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
protected function setUp(): void
{
parent::setUp();
$this->registry = Bootstrap::getObjectManager()->get(Registry::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
/**
* @dataProvider validEmailAddressDataProvider
* @throws \Exception
*/
public function testCreateCustomerAccountWithPassword(string $email)
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$email}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertNull($response['createCustomer']['customer']['id']);
$this->assertEquals($newFirstname, $response['createCustomer']['customer']['firstname']);
$this->assertEquals($newLastname, $response['createCustomer']['customer']['lastname']);
$this->assertEquals($email, $response['createCustomer']['customer']['email']);
$this->assertTrue($response['createCustomer']['customer']['is_subscribed']);
}
/**
* @return array
*/
public function validEmailAddressDataProvider(): array
{
return [
['new_customer@example.com'],
['jØrgen@somedomain.com'],
['“email”@example.com']
];
}
/**
* @throws \Exception
*/
public function testCreateCustomerAccountWithoutPassword()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertEquals($newFirstname, $response['createCustomer']['customer']['firstname']);
$this->assertEquals($newLastname, $response['createCustomer']['customer']['lastname']);
$this->assertEquals($newEmail, $response['createCustomer']['customer']['email']);
$this->assertTrue($response['createCustomer']['customer']['is_subscribed']);
}
/**
*/
public function testCreateCustomerIfInputDataIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('"input" value should be specified');
$query = <<<QUERY
mutation {
createCustomer(
input: {
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
*/
public function testCreateCustomerIfEmailMissed()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameters are missing: Email');
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @dataProvider invalidEmailAddressDataProvider
*
* @param string $email
* @throws \Exception
*/
public function testCreateCustomerIfEmailIsNotValid(string $email)
{
$firstname = 'Richard';
$lastname = 'Rowe';
$password = 'test123#';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$firstname}"
lastname: "{$lastname}"
email: "{$email}"
password: "{$password}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->expectExceptionMessage('"' . $email . '" is not a valid email address.');
$this->graphQlMutation($query);
}
/**
* @return array
*/
public function invalidEmailAddressDataProvider(): array
{
return [
['plainaddress'],
['#@%^%#$@#$@#.com'],
['@example.com'],
['Joe Smith <email@example.com>'],
['email.example.com'],
['email@example@example.com'],
['email@example.com (Joe Smith)'],
['email@example']
];
}
/**
*/
public function testCreateCustomerIfPassedAttributeDosNotExistsInCustomerInput()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Field "test123" is not defined by type "CustomerInput".');
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
test123: "123test123"
email: "{$newEmail}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
*/
public function testCreateCustomerIfNameEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameters are missing: First Name');
$newEmail = 'customer_created' . rand(1, 2000000) . '@example.com';
$newFirstname = '';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomer(
input: {
email: "{$newEmail}"
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoConfigFixture default_store newsletter/general/active 0
*/
public function testCreateCustomerSubscribed()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
is_subscribed: true
}
) {
customer {
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertFalse($response['createCustomer']['customer']['is_subscribed']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateCustomerIfCustomerWithProvidedEmailAlreadyExists()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'A customer with the same email address already exists in an associated website.'
);
$existedEmail = 'customer@example.com';
$password = 'test123#';
$firstname = 'John';
$lastname = 'Smith';
$query = <<<QUERY
mutation {
createCustomer(
input: {
email: "{$existedEmail}"
password: "{$password}"
firstname: "{$firstname}"
lastname: "{$lastname}"
}
) {
customer {
firstname
lastname
email
}
}
}
QUERY;
$this->graphQlMutation($query);
}
protected function tearDown(): void
{
$newEmail = 'new_customer@example.com';
try {
$customer = $this->customerRepository->get($newEmail);
} catch (\Exception $exception) {
return;
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
$this->customerRepository->delete($customer);
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
parent::tearDown();
}
}
@@ -0,0 +1,399 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for create customer (V2)
*/
class CreateCustomerV2Test extends GraphQlAbstract
{
/**
* @var Registry
*/
private $registry;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
protected function setUp(): void
{
parent::setUp();
$this->registry = Bootstrap::getObjectManager()->get(Registry::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
/**
* @magentoConfigFixture default_store newsletter/general/active 1
* @dataProvider validEmailAddressDataProvider
* @throws \Exception
*/
public function testCreateCustomerAccountWithPassword(string $email)
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$email}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertNull($response['createCustomerV2']['customer']['id']);
$this->assertEquals($newFirstname, $response['createCustomerV2']['customer']['firstname']);
$this->assertEquals($newLastname, $response['createCustomerV2']['customer']['lastname']);
$this->assertEquals($email, $response['createCustomerV2']['customer']['email']);
$this->assertTrue($response['createCustomerV2']['customer']['is_subscribed']);
}
/**
* @return array
*/
public function validEmailAddressDataProvider(): array
{
return [
['new_customer@example.com'],
['jØrgenV2@somedomain.com'],
['“emailV2”@example.com']
];
}
/**
* @throws \Exception
*/
public function testCreateCustomerAccountWithoutPassword()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertEquals($newFirstname, $response['createCustomerV2']['customer']['firstname']);
$this->assertEquals($newLastname, $response['createCustomerV2']['customer']['lastname']);
$this->assertEquals($newEmail, $response['createCustomerV2']['customer']['email']);
$this->assertTrue($response['createCustomerV2']['customer']['is_subscribed']);
}
/**
*/
public function testCreateCustomerIfInputDataIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('CustomerCreateInput.email of required type String! was not provided.');
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
*/
public function testCreateCustomerIfEmailMissed()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Field CustomerCreateInput.email of required type String! was not provided');
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @dataProvider invalidEmailAddressDataProvider
*
* @param string $email
* @throws \Exception
*/
public function testCreateCustomerIfEmailIsNotValid(string $email)
{
$firstname = 'Richard';
$lastname = 'Rowe';
$password = 'test123#';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$firstname}"
lastname: "{$lastname}"
email: "{$email}"
password: "{$password}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->expectExceptionMessage('"' . $email . '" is not a valid email address.');
$this->graphQlMutation($query);
}
/**
* @return array
*/
public function invalidEmailAddressDataProvider(): array
{
return [
['plainaddress'],
['#@%^%#$@#$@#.com'],
['@example.com'],
['Joe Smith <email@example.com>'],
['email.example.com'],
['email@example@example.com'],
['email@example.com (Joe Smith)'],
['email@example']
];
}
/**
*/
public function testCreateCustomerIfPassedAttributeDosNotExistsInCustomerInput()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Field "test123" is not defined by type "CustomerCreateInput".');
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
test123: "123test123"
email: "{$newEmail}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
*/
public function testCreateCustomerIfNameEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameters are missing: First Name');
$newEmail = 'customer_created' . rand(1, 2000000) . '@example.com';
$newFirstname = '';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
email: "{$newEmail}"
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
password: "{$currentPassword}"
is_subscribed: true
}
) {
customer {
id
firstname
lastname
email
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoConfigFixture default_store newsletter/general/active 0
*/
public function testCreateCustomerSubscribed()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
is_subscribed: true
}
) {
customer {
email
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertFalse($response['createCustomerV2']['customer']['is_subscribed']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateCustomerIfCustomerWithProvidedEmailAlreadyExists()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'A customer with the same email address already exists in an associated website.'
);
$existedEmail = 'customer@example.com';
$password = 'test123#';
$firstname = 'John';
$lastname = 'Smith';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
email: "{$existedEmail}"
password: "{$password}"
firstname: "{$firstname}"
lastname: "{$lastname}"
}
) {
customer {
firstname
lastname
email
}
}
}
QUERY;
$this->graphQlMutation($query);
}
protected function tearDown(): void
{
$newEmail = 'new_customer@example.com';
try {
$customer = $this->customerRepository->get($newEmail);
} catch (\Exception $exception) {
return;
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
$this->customerRepository->delete($customer);
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
parent::tearDown();
}
}
@@ -0,0 +1,299 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Registry;
/**
* Tests for create customer V2
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'attribute_code' => 'random_attribute',
'sort_order' => 2
],
'random_attribute',
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'multiselect_attribute',
'frontend_input' => 'multiselect',
'sort_order' => 1
],
'multiselect_attribute',
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 1',
'sort_order' => 20
],
'multiselect_attribute_option1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'option 2',
'sort_order' => 30
],
'multiselect_attribute_option2'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'option 3',
'sort_order' => 10
],
'multiselect_attribute_option3'
)
]
class CreateCustomerV2WithCustomAttributesTest extends GraphQlAbstract
{
/**
* @var string
*/
private $query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "Adam"
lastname: "Smith"
email: "adam@smith.com"
password: "test123#"
custom_attributes: [
{
attribute_code: "%s"
value: "%s"
}
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}
) {
customer {
firstname
lastname
email
custom_attributes {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
}
QUERY;
/**
* @var Registry
*/
private $registry;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var AttributeMetadataInterface|null
*/
private $random_attribute;
/**
* @var AttributeMetadataInterface|null
*/
private $multiselect_attribute;
/**
* @var AttributeOptionInterface|null
*/
private $option2;
/**
* @var AttributeOptionInterface|null
*/
private $option3;
protected function setUp(): void
{
parent::setUp();
$this->registry = Bootstrap::getObjectManager()->get(Registry::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
$this->random_attribute = DataFixtureStorageManager::getStorage()->get('random_attribute');
$this->multiselect_attribute = DataFixtureStorageManager::getStorage()->get('multiselect_attribute');
$this->option2 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option2');
$this->option3 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option3');
}
/**
* @return void
* @throws Exception
*/
public function testCreateCustomerAccountWithCustomAttributes()
{
$response = $this->graphQlMutation(
sprintf(
$this->query,
$this->random_attribute->getAttributeCode(),
'new_value_for_attribute',
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
)
);
$this->assertEquals(
[
'createCustomerV2' =>
[
'customer' =>
[
'firstname' => 'Adam',
'lastname' => 'Smith',
'email' => 'adam@smith.com',
'custom_attributes' =>
[
0 =>
[
'code' => $this->multiselect_attribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->option3->getLabel(),
'value' => $this->option3->getValue()
],
[
'label' => $this->option2->getLabel(),
'value' => $this->option2->getValue()
]
]
],
1 =>
[
'code' => $this->random_attribute->getAttributeCode(),
'value' => 'new_value_for_attribute',
]
],
],
],
],
$response
);
}
public function testCreateCustomerAccountWithNonExistingCustomAttribute()
{
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "John"
lastname: "Doe"
email: "john@doe.com"
password: "test123#"
custom_attributes: [
{
attribute_code: "non_existing_custom_attribute",
value: "void"
}
]
}
) {
customer {
firstname
lastname
email
custom_attributes {
code
... on AttributeValue {
value
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation($query);
$this->assertEquals(
[
'createCustomerV2' =>
[
'customer' =>
[
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'john@doe.com',
'custom_attributes' => []
],
],
],
$response
);
}
protected function tearDown(): void
{
$email1 = 'adam@smith.com';
$email2 = 'john@doe.com';
try {
$customer1 = $this->customerRepository->get($email1);
$customer2 = $this->customerRepository->get($email2);
} catch (Exception $exception) {
return;
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
$this->customerRepository->delete($customer1);
$this->customerRepository->delete($customer2);
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
parent::tearDown();
}
}
@@ -0,0 +1,271 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Integration\Api\CustomerTokenServiceInterface;
/**
* Delete customer address tests
*/
class DeleteCustomerAddressTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
$this->addressRepository = Bootstrap::getObjectManager()->get(AddressRepositoryInterface::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testDeleteCustomerAddress()
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 2;
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('deleteCustomerAddress', $response);
$this->assertTrue($response['deleteCustomerAddress']);
}
/**
*/
public function testDeleteCustomerAddressIfUserIsNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$addressId = 1;
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$this->graphQlMutation($mutation);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*
*/
public function testDeleteDefaultShippingCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Customer Address 2 is set as default shipping address and can not be deleted');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 2;
$address = $this->addressRepository->getById($addressId);
$address->setIsDefaultShipping(true);
$this->addressRepository->save($address);
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*
*/
public function testDeleteDefaultBillingCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Customer Address 2 is set as default billing address and can not be deleted');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 2;
$address = $this->addressRepository->getById($addressId);
$address->setIsDefaultBilling(true);
$this->addressRepository->save($address);
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
*/
public function testDeleteNonExistCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find a address with ID "9999"');
$userName = 'customer@example.com';
$password = 'password';
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: 9999)
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Delete address with missing ID input.
*
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @throws Exception
*/
public function testDeleteCustomerAddressWithMissingData()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Syntax Error: Expected Name, found )');
$userName = 'customer@example.com';
$password = 'password';
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress()
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Delete address with incorrect ID input type.
*
* @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php
* @throws Exception
*/
public function testDeleteCustomerAddressWithIncorrectIdType()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Expected type Int!, found "".');
$this->markTestSkipped(
'Type validation returns wrong message https://github.com/magento/graphql-ce/issues/735'
);
$userName = 'customer@example.com';
$password = 'password';
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: "string")
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/two_customers.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*
*/
public function testDeleteAnotherCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Current customer does not have permission to address with ID "2"');
$userName = 'customer_two@example.com';
$password = 'password';
$addressId = 2;
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*
*/
public function testDeleteCustomerAddressIfAccountIsLocked()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is locked');
$this->markTestSkipped('https://github.com/magento/graphql-ce/issues/750');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 2;
$this->lockCustomer->execute(1);
$mutation
= <<<MUTATION
mutation {
deleteCustomerAddress(id: {$addressId})
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @param string $email
* @param string $password
* @return array
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Framework\Exception\AuthenticationException;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Integration\Api\CustomerTokenServiceInterface;
/**
* Delete customer tests
*/
class DeleteCustomerTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
}
/**
* Test deleting customer
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testDeleteCustomer(): void
{
$response = $this->graphQlMutation($this->getMutation(), [], '', $this->getHeaderMap());
$this->assertArrayHasKey('deleteCustomer', $response);
$this->assertTrue($response['deleteCustomer']);
}
/**
* Test deleting non authorized customer
*/
public function testDeleteCustomerIfUserIsNotAuthorized(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$this->graphQlMutation($this->getMutation());
}
/**
* Test deleting locked customer
*
* @magentoApiDataFixture Magento/Customer/_files/locked_customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testDeleteCustomerIfAccountIsLocked(): 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'
);
$this->graphQlMutation($this->getMutation(), [], '', $this->getHeaderMap());
}
/**
* Retrieve deleteCustomer mutation
*
* @return string
*/
private function getMutation(): string
{
return <<<MUTATION
mutation {
deleteCustomer
}
MUTATION;
}
/**
* Retrieve customer authorization headers
*
* @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);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
return $headerMap;
}
}
@@ -0,0 +1,205 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Model\Log;
use Magento\Customer\Model\Logger;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* API-functional tests cases for generateCustomerToken mutation
*/
class GenerateCustomerTokenTest extends GraphQlAbstract
{
/**
* @var Logger
*/
private $logger;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->logger = Bootstrap::getObjectManager()->get(Logger::class);
}
/**
* Verify customer token with valid credentials
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testGenerateCustomerValidToken(): void
{
$mutation = $this->getQuery();
$response = $this->graphQlMutation($mutation);
$this->assertArrayHasKey('generateCustomerToken', $response);
$this->assertIsArray($response['generateCustomerToken']);
}
/**
* Test customer with invalid data.
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @dataProvider dataProviderInvalidCustomerInfo
* @param string $email
* @param string $password
* @param string $message
*/
public function testGenerateCustomerTokenInvalidData(string $email, string $password, string $message): void
{
$this->expectException(\Exception::class);
$mutation = $this->getQuery($email, $password);
$this->expectExceptionMessage($message);
$this->graphQlMutation($mutation);
}
/**
* Test customer token regeneration.
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testRegenerateCustomerToken(): void
{
$mutation = $this->getQuery();
$response1 = $this->graphQlMutation($mutation);
$token1 = $response1['generateCustomerToken']['token'];
sleep(2);
$response2 = $this->graphQlMutation($mutation);
$token2 = $response2['generateCustomerToken']['token'];
$this->assertNotEquals($token1, $token2, 'Tokens should not be identical!');
}
/**
* @return array
*/
public function dataProviderInvalidCustomerInfo(): array
{
return [
'invalid_email' => [
'invalid_email@example.com',
'password',
'The account sign-in was incorrect or your account is disabled temporarily. ' .
'Please wait and try again later.'
],
'empty_email' => [
'',
'password',
'Specify the "email" value.'
],
'invalid_password' => [
'customer@example.com',
'invalid_password',
'The account sign-in was incorrect or your account is disabled temporarily. ' .
'Please wait and try again later.'
],
'empty_password' => [
'customer@example.com',
'',
'Specify the "password" value.'
]
];
}
/**
* @param string $email
* @param string $password
* @return string
*/
private function getQuery(string $email = 'customer@example.com', string $password = 'password'): string
{
return <<<MUTATION
mutation {
generateCustomerToken(
email: "{$email}"
password: "{$password}"
) {
token
}
}
MUTATION;
}
/**
* Verify customer with empty email
*/
public function testGenerateCustomerTokenWithEmptyEmail(): void
{
$email = '';
$password = 'bad-password';
$mutation = $this->getQuery($email, $password);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: Specify the "email" value.');
$this->graphQlMutation($mutation);
}
/**
* Verify customer with empty password
*/
public function testGenerateCustomerTokenWithEmptyPassword(): void
{
$email = 'customer@example.com';
$password = '';
$mutation = $this->getQuery($email, $password);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: Specify the "password" value.');
$this->graphQlMutation($mutation);
}
/**
* Verify customer log after generate customer token
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCustomerLogAfterGenerateCustomerToken(): void
{
$response = $this->graphQlMutation($this->getQuery());
$this->assertArrayHasKey('generateCustomerToken', $response);
$this->assertIsArray($response['generateCustomerToken']);
/** @var Log $log */
$log = $this->logger->get(1);
$this->assertNotEmpty($log->getLastLoginAt());
}
/**
* Ensure that customer log record is deleted.
*
* @return void
*/
protected function tearDown(): void
{
if ($this->logger->get(1)->getLastLoginAt()) {
/** @var ResourceConnection $resource */
$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class);
/** @var AdapterInterface $connection */
$connection = $resource->getConnection(ResourceConnection::DEFAULT_CONNECTION);
$connection->delete(
$resource->getTableName('customer_log'),
['customer_id' => 1]
);
}
parent::tearDown();
}
}
@@ -0,0 +1,156 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Integration\Api\CustomerTokenServiceInterface;
/**
* Test for customer address retrieval.
*/
class GetAddressesTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testGetCustomerWithAddresses()
{
$query = $this->getQuery();
$userName = 'customer@example.com';
$password = 'password';
$customerToken = $this->customerTokenService->createCustomerAccessToken($userName, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = ObjectManager::getInstance()->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->get('customer@example.com');
$response = $this->graphQlQuery($query, [], '', $headerMap);
$this->assertArrayHasKey('customer', $response);
$this->assertArrayHasKey('addresses', $response['customer']);
$this->assertIsArray([$response['customer']['addresses']],
" Addresses field must be of an array type."
);
self::assertNull($response['customer']['id']);
$this->assertCustomerAddressesFields($customer, $response);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testGetCustomerAddressIfAccountIsLocked()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: The account is locked.');
$query = $this->getQuery();
$userName = 'customer@example.com';
$password = 'password';
$this->lockCustomer->execute(1);
$customerToken = $this->customerTokenService->createCustomerAccessToken($userName, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
$this->graphQlQuery($query, [], '', $headerMap);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testGetCustomerAddressIfUserIsNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: The current customer isn\'t authorized.');
$query = $this->getQuery();
$this->graphQlQuery($query);
}
/**
* Verify the fields for CustomerAddress object
*
* @param CustomerInterface $customer
* @param array $actualResponse
*/
private function assertCustomerAddressesFields($customer, $actualResponse)
{
/** @var AddressInterface $addresses */
$addresses = $customer->getAddresses();
foreach ($addresses as $addressKey => $addressValue) {
$this->assertNotEmpty($addressValue);
$assertionMap = [
['response_field' => 'id', 'expected_value' => $addresses[$addressKey]->getId()],
['response_field' => 'customer_id', 'expected_value' => 0],
['response_field' => 'region_id', 'expected_value' => $addresses[$addressKey]->getRegionId()],
['response_field' => 'country_id', 'expected_value' => $addresses[$addressKey]->getCountryId()],
['response_field' => 'telephone', 'expected_value' => $addresses[$addressKey]->getTelephone()],
['response_field' => 'postcode', 'expected_value' => $addresses[$addressKey]->getPostcode()],
['response_field' => 'city', 'expected_value' => $addresses[$addressKey]->getCity()],
['response_field' => 'firstname', 'expected_value' => $addresses[$addressKey]->getFirstname()],
['response_field' => 'lastname', 'expected_value' => $addresses[$addressKey]->getLastname()]
];
$this->assertResponseFields($actualResponse['customer']['addresses'][$addressKey], $assertionMap);
}
}
/**
* @return string
*/
private function getQuery(): string
{
$query
= <<<QUERY
{
customer {
id
addresses {
id
customer_id
region_id
country_id
telephone
postcode
city
firstname
lastname
}
}
}
QUERY;
return $query;
}
}
@@ -0,0 +1,325 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* GraphQl tests for @see \Magento\CustomerGraphQl\Model\Customer\GetCustomer.
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'frontend_input' => 'multiselect',
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'labels',
'attribute_group_id' => 1,
'sort_order' => 2,
],
'multiselect_customer_address_attribute'
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => 'planet',
'sort_order' => 1,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_group_id' => 1,
],
'varchar_customer_address_attribute'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_customer_address_attribute.attribute_code$',
'label' => 'far',
'sort_order' => 20
],
'multiselect_customer_address_attribute_option_1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_customer_address_attribute.attribute_code$',
'sort_order' => 10,
'label' => 'foreign',
'is_default' => true
],
'multiselect_customer_address_attribute_option_2'
),
DataFixture(
Customer::class,
[
'email' => 'john@doe.com',
'addresses' => [
[
'country_id' => 'US',
'region_id' => 32,
'city' => 'Boston',
'street' => ['10 Milk Street'],
'postcode' => '02108',
'telephone' => '1234567890',
'default_billing' => true,
'default_shipping' => true,
'custom_attributes' => [
[
'attribute_code' => 'labels',
'selected_options' => [
['value' => '$multiselect_customer_address_attribute_option_1.value$'],
['value' => '$multiselect_customer_address_attribute_option_2.value$']
],
],
[
'attribute_code' => 'planet',
'value' => 'Earth'
]
],
],
],
],
'customer'
),
]
class GetAddressesWithCustomAttributesTest extends GraphQlAbstract
{
/**
* @var string
*/
private $currentPassword = 'password';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var AttributeInterface|null
*/
private $varcharCustomerAddressAttribute;
/**
* @var AttributeInterface|null
*/
private $multiselectCustomerAddressAttribute;
/**
* @var AttributeOptionInterface|null
*/
private $multiselectCustomerAttributeOption1;
/**
* @var AttributeOptionInterface|null
*/
private $multiselectCustomerAttributeOption2;
/**
* @var CustomerInterface|null
*/
private $customer;
/**
* @inheridoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class);
$this->varcharCustomerAddressAttribute = DataFixtureStorageManager::getStorage()->get(
'varchar_customer_address_attribute'
);
$this->multiselectCustomerAddressAttribute = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_address_attribute'
);
$this->multiselectCustomerAttributeOption1 = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_address_attribute_option_1'
);
$this->multiselectCustomerAttributeOption2 = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_address_attribute_option_2'
);
$this->customer = DataFixtureStorageManager::getStorage()->get('customer');
}
/**
* @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];
}
public function testGetCustomAddressAttributes()
{
$query = <<<QUERY
query {
customer {
firstname
lastname
email
addresses {
country_id
custom_attributesV2 {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'customer' => [
'firstname' => $this->customer->getFirstname(),
'lastname' => $this->customer->getLastname(),
'email' => $this->customer->getEmail(),
'addresses' => [
[
'country_id' => 'US',
'custom_attributesV2' => [
[
'code' => $this->varcharCustomerAddressAttribute->getAttributeCode(),
'value' => 'Earth'
],
[
'code' => $this->multiselectCustomerAddressAttribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->multiselectCustomerAttributeOption2->getLabel(),
'value' => $this->multiselectCustomerAttributeOption2->getValue(),
],
[
'label' => $this->multiselectCustomerAttributeOption1->getLabel(),
'value' => $this->multiselectCustomerAttributeOption1->getValue(),
]
]
]
]
]
]
]
],
$response
);
}
public function testGetFilteredCustomAddressAttributes()
{
$query = <<<QUERY
query {
customer {
firstname
lastname
email
addresses {
country_id
custom_attributesV2(attributeCodes: ["%s"]) {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
sprintf($query, $this->multiselectCustomerAddressAttribute->getAttributeCode()),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'customer' => [
'firstname' => $this->customer->getFirstname(),
'lastname' => $this->customer->getLastname(),
'email' => $this->customer->getEmail(),
'addresses' => [
[
'country_id' => 'US',
'custom_attributesV2' => [
[
'code' => $this->multiselectCustomerAddressAttribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->multiselectCustomerAttributeOption2->getLabel(),
'value' => $this->multiselectCustomerAttributeOption2->getValue(),
],
[
'label' => $this->multiselectCustomerAttributeOption1->getLabel(),
'value' => $this->multiselectCustomerAttributeOption1->getValue(),
]
]
]
]
]
]
]
],
$response
);
}
}
@@ -0,0 +1,229 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\CustomerAuthUpdate;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Integration\Api\AdminTokenServiceInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Bootstrap as TestBootstrap;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* GraphQl tests for @see \Magento\CustomerGraphQl\Model\Customer\GetCustomer.
*/
class GetCustomerTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var CustomerAuthUpdate
*/
private $customerAuthUpdate;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheridoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class);
$this->customerRegistry = $this->objectManager->get(CustomerRegistry::class);
$this->customerAuthUpdate = $this->objectManager->get(CustomerAuthUpdate::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCustomer()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
query {
customer {
id
firstname
lastname
email
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
$this->assertNull($response['customer']['id']);
$this->assertEquals('John', $response['customer']['firstname']);
$this->assertEquals('Smith', $response['customer']['lastname']);
$this->assertEquals($currentEmail, $response['customer']['email']);
}
/**
*/
public function testGetCustomerIfUserIsNotAuthorized()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
query {
customer {
firstname
lastname
email
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @magentoApiDataFixture Magento/User/_files/user_with_role.php
* @return void
*/
public function testGetCustomerIfUserHasWrongType(): void
{
/** @var $adminTokenService AdminTokenServiceInterface */
$adminTokenService = $this->objectManager->get(AdminTokenServiceInterface::class);
$adminToken = $adminTokenService->createAdminAccessToken('adminUser', TestBootstrap::ADMIN_PASSWORD);
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
query {
customer {
firstname
lastname
email
}
}
QUERY;
$this->graphQlQuery(
$query,
[],
'',
['Authorization' => 'Bearer ' . $adminToken]
);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCustomerIfAccountIsLocked()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$customer = $this->customerRepository->get($currentEmail);
$this->lockCustomer((int)$customer->getId());
$this->expectException(Exception::class);
$this->expectExceptionMessage('The account is locked.');
$query = <<<QUERY
query {
customer {
firstname
lastname
email
}
}
QUERY;
$this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
}
/**
* @magentoConfigFixture customer/create_account/confirm 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
*/
public function testAccountIsNotConfirmed()
{
$this->expectExceptionMessage("This account isn't confirmed. Verify and try again.");
$customerEmail = 'customer@example.com';
$currentPassword = 'password';
$customer = $this->customerRepository->get($customerEmail);
$headersMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword);
$customer = $this->customerRepository->getById((int)$customer->getId())
->setConfirmation(AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED);
$this->customerRepository->save($customer);
$query = <<<QUERY
query {
customer {
firstname
lastname
email
}
}
QUERY;
$this->graphQlQuery($query, [], '', $headersMap);
}
/**
* @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];
}
/**
* @param int $customerId
* @return void
* @throws NoSuchEntityException
*/
private function lockCustomer(int $customerId): void
{
$customerSecure = $this->customerRegistry->retrieveSecureData($customerId);
$customerSecure->setLockExpires('2030-12-31 00:00:00');
$this->customerAuthUpdate->saveAuth($customerId);
}
}
@@ -0,0 +1,297 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* GraphQl tests for @see \Magento\CustomerGraphQl\Model\Customer\GetCustomer.
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => 'shoe_size',
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'sort_order' => 2
],
'varchar_customer_attribute'
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'frontend_input' => 'multiselect',
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'shoe_color',
'attribute_group_id' => 1,
'sort_order' => 1
],
'multiselect_customer_attribute'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_customer_attribute.attribute_code$',
'label' => 'red',
'sort_order' => 20
],
'multiselect_customer_attribute_option_1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_customer_attribute.attribute_code$',
'sort_order' => 10,
'label' => 'white',
'is_default' => true
],
'multiselect_customer_attribute_option_2'
),
DataFixture(
Customer::class,
[
'email' => 'john@doe.com',
'custom_attributes' => [
[
'attribute_code' => 'shoe_size',
'value' => '42'
],
[
'attribute_code' => 'shoe_color',
'selected_options' => [
['value' => '$multiselect_customer_attribute_option_1.value$'],
['value' => '$multiselect_customer_attribute_option_2.value$']
],
],
],
],
'customer'
),
]
class GetCustomerWithCustomAttributesTest extends GraphQlAbstract
{
/**
* @var string
*/
private $currentPassword = 'password';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var AttributeInterface|null
*/
private $varcharCustomerAttribute;
/**
* @var AttributeInterface|null
*/
private $multiselectCustomerAttribute;
/**
* @var AttributeOptionInterface|null
*/
private $multiselectCustomerAttributeOption1;
/**
* @var AttributeOptionInterface|null
*/
private $multiselectCustomerAttributeOption2;
/**
* @var CustomerInterface|null
*/
private $customer;
/**
* @inheridoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class);
$this->varcharCustomerAttribute = DataFixtureStorageManager::getStorage()->get(
'varchar_customer_attribute'
);
$this->multiselectCustomerAttribute = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_attribute'
);
$this->multiselectCustomerAttributeOption1 = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_attribute_option_1'
);
$this->multiselectCustomerAttributeOption2 = DataFixtureStorageManager::getStorage()->get(
'multiselect_customer_attribute_option_2'
);
$this->customer = DataFixtureStorageManager::getStorage()->get('customer');
}
/**
* @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];
}
public function testGetCustomAttributes()
{
$query = <<<QUERY
query {
customer {
firstname
lastname
email
custom_attributes {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'customer' => [
'firstname' => $this->customer->getFirstname(),
'lastname' => $this->customer->getLastname(),
'email' => $this->customer->getEmail(),
'custom_attributes' => [
[
'code' => $this->multiselectCustomerAttribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->multiselectCustomerAttributeOption2->getLabel(),
'value' => $this->multiselectCustomerAttributeOption2->getValue(),
],
[
'label' => $this->multiselectCustomerAttributeOption1->getLabel(),
'value' => $this->multiselectCustomerAttributeOption1->getValue(),
]
]
],
[
'code' => $this->varcharCustomerAttribute->getAttributeCode(),
'value' => '42'
]
]
]
],
$response
);
}
public function testGetFilteredCustomAttributes()
{
$query = <<<QUERY
query {
customer {
firstname
lastname
email
custom_attributes(attributeCodes: ["%s"]) {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
sprintf($query, $this->multiselectCustomerAttribute->getAttributeCode()),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'customer' => [
'firstname' => $this->customer->getFirstname(),
'lastname' => $this->customer->getLastname(),
'email' => $this->customer->getEmail(),
'custom_attributes' => [
[
'code' => $this->multiselectCustomerAttribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->multiselectCustomerAttributeOption2->getLabel(),
'value' => $this->multiselectCustomerAttributeOption2->getValue(),
],
[
'label' => $this->multiselectCustomerAttributeOption1->getLabel(),
'value' => $this->multiselectCustomerAttributeOption1->getValue(),
]
]
]
]
]
],
$response
);
}
}
@@ -0,0 +1,143 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Model\AccountManagement;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Api\StoreResolverInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test email availability functionality
*/
class IsEmailAvailableTest extends GraphQlAbstract
{
/**
* @var ScopeConfigInterface|null
*/
private ?ScopeConfigInterface $scopeConfig;
/**
* @var string|null
*/
private ?string $storeId;
public function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->scopeConfig = $objectManager->get(ScopeConfigInterface::class);
/* @var StoreResolverInterface $storeResolver */
$storeResolver = $objectManager->get(StoreResolverInterface::class);
$this->storeId = $storeResolver->getCurrentStoreId();
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testEmailNotAvailable()
{
$query =
<<<QUERY
{
isEmailAvailable(email: "customer@example.com") {
is_email_available
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('isEmailAvailable', $response);
self::assertArrayHasKey('is_email_available', $response['isEmailAvailable']);
$emailConfig = $this->scopeConfig->getValue(
AccountManagement::GUEST_CHECKOUT_LOGIN_OPTION_SYS_CONFIG,
ScopeInterface::SCOPE_STORE,
$this->storeId
);
if (!$emailConfig) {
self::assertTrue($response['isEmailAvailable']['is_email_available']);
} else {
self::assertFalse($response['isEmailAvailable']['is_email_available']);
}
}
/**
* Verify email availability
*/
public function testEmailAvailable()
{
$query =
<<<QUERY
{
isEmailAvailable(email: "customer@example.com") {
is_email_available
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('isEmailAvailable', $response);
self::assertArrayHasKey('is_email_available', $response['isEmailAvailable']);
self::assertTrue($response['isEmailAvailable']['is_email_available']);
}
/**
*/
public function testEmailAvailableEmptyValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: Email must be specified');
$query =
<<<QUERY
{
isEmailAvailable(email: "") {
is_email_available
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
*/
public function testEmailAvailableMissingValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Field "isEmailAvailable" argument "email" of type "String!" is required');
$query =
<<<QUERY
{
isEmailAvailable {
is_email_available
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
*/
public function testEmailAvailableInvalidValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: Email is invalid');
$query =
<<<QUERY
{
isEmailAvailable(email: "invalid-email") {
is_email_available
}
}
QUERY;
$this->graphQlQuery($query);
}
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Customer\Model\CustomerAuthUpdate;
use Magento\Customer\Model\CustomerRegistry;
/**
* Lock customer account by ID
*/
class LockCustomer
{
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var CustomerAuthUpdate
*/
private $customerAuthUpdate;
/**
* @param CustomerRegistry $customerRegistry
* @param CustomerAuthUpdate $customerAuthUpdate
*/
public function __construct(CustomerRegistry $customerRegistry, CustomerAuthUpdate $customerAuthUpdate)
{
$this->customerRegistry = $customerRegistry;
$this->customerAuthUpdate = $customerAuthUpdate;
}
/**
* Lock customer by ID.
*
* @param int $customerId
*
* @return void
*/
public function execute(int $customerId): void
{
$customerSecure = $this->customerRegistry->retrieveSecureData($customerId);
$customerSecure->setLockExpires('2030-12-31 00:00:00');
$this->customerAuthUpdate->saveAuth($customerId);
}
}
@@ -0,0 +1,108 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
class RequestPasswordResetEmailTest extends GraphQlAbstract
{
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCustomerAccountWithEmailAvailable()
{
$query =
<<<QUERY
mutation {
requestPasswordResetEmail(email: "customer@example.com")
}
QUERY;
$response = $this->graphQlMutation($query);
self::assertArrayHasKey('requestPasswordResetEmail', $response);
self::assertTrue($response['requestPasswordResetEmail']);
}
/**
* Check if customer account is not available
*/
public function testCustomerAccountWithEmailNotAvailable()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Cannot reset the customer\'s password');
$query =
<<<QUERY
mutation {
requestPasswordResetEmail(email: "customerNotAvalible@example.com")
}
QUERY;
$this->graphQlMutation($query);
}
/**
* Check if email value empty
*/
public function testEmailAvailableEmptyValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('You must specify an email address.');
$query = <<<QUERY
mutation {
requestPasswordResetEmail(email: "")
}
QUERY;
$this->graphQlMutation($query);
}
/**
* Check if email is invalid
*/
public function testEmailAvailableInvalidValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The email address has an invalid format.');
$query = <<<QUERY
mutation {
requestPasswordResetEmail(email: "invalid-email")
}
QUERY;
$this->graphQlMutation($query);
}
/**
* Check if email was sent for lock customer
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testRequestPasswordResetEmailForLockCustomer()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is locked');
$this->lockCustomer->execute(1);
$query =
<<<QUERY
mutation {
requestPasswordResetEmail(email: "customer@example.com")
}
QUERY;
$this->graphQlMutation($query);
}
}
@@ -0,0 +1,308 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\AccountManagement;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Class reset password for customer account
*/
class ResetPasswordTest extends GraphQlAbstract
{
const CUSTOMER_EMAIL = "customer@example.com";
const CUSTOMER_NEW_PASSWORD = "new_password123";
/** @var ObjectManagerInterface */
private $objectManager;
/** @var AccountManagementInterface */
private $accountManagement;
/** @var CustomerRegistry */
private $customerRegistry;
/**
* @var LockCustomer
*/
private $lockCustomer;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->accountManagement = $this->objectManager->get(AccountManagementInterface::class);
$this->customerRegistry = $this->objectManager->get(CustomerRegistry::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
parent::setUp();
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @return void
* @throws NoSuchEntityException
* @throws Exception
*
* @throws LocalizedException
*/
public function testResetCustomerAccountPasswordSuccessfully(): void
{
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$response = $this->graphQlMutation($query);
self::assertArrayHasKey('resetPassword', $response);
self::assertTrue($response['resetPassword']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testEmailAvailableEmptyValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('You must specify an email address.');
$query = <<<QUERY
mutation {
resetPassword (
email: ""
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testEmailInvalidValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The email address has an invalid format.');
$query = <<<QUERY
mutation {
resetPassword (
email: "invalid-email"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testResetPasswordTokenEmptyValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('resetPasswordToken must be specified');
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: ""
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testResetPasswordTokenMismatched()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The password token is mismatched. Reset and try again');
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "1234567890XYZ"
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testNewPasswordEmptyValue()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('newPassword must be specified');
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: ""
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testNewPasswordCheckMinLength()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The password needs at least 8 characters. Create a new password and try again');
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "new_"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws NoSuchEntityException
* @throws Exception
* @throws LocalizedException
*/
public function testNewPasswordCheckCharactersStrength()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage(
'Minimum of different classes of characters in password is 3. ' .
'Classes of characters: Lower Case, Upper Case, Digits, Special Characters.'
);
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "new_password"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* Check password reset for lock customer
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testPasswordResetForLockCustomer()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is locked');
$this->lockCustomer->execute(1);
$query = <<<QUERY
mutation {
resetPassword (
email: "{$this->getCustomerEmail()}"
resetPasswordToken: "{$this->getResetPasswordToken()}"
newPassword: "{$this->getNewPassword()}"
)
}
QUERY;
$this->graphQlMutation($query);
}
/**
* Get reset password token
*
* @return string
*
* @throws LocalizedException
* @throws NoSuchEntityException
*/
private function getResetPasswordToken()
{
$this->accountManagement->initiatePasswordReset(
$this->getCustomerEmail(),
AccountManagement::EMAIL_RESET,
1
);
$customerSecure = $this->customerRegistry->retrieveSecureData(1);
return $customerSecure->getRpToken();
}
/**
* Get customer email
*
* @return string
*/
private function getCustomerEmail()
{
return self::CUSTOMER_EMAIL;
}
/**
* Get new password for customer account
*
* @return string
*/
private function getNewPassword()
{
return self::CUSTOMER_NEW_PASSWORD;
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for revoke customer token mutation
*/
class RevokeCustomerTokenTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testRevokeCustomerTokenValidCredentials()
{
$query = <<<QUERY
mutation {
revokeCustomerToken {
result
}
}
QUERY;
$userName = 'customer@example.com';
$password = 'password';
/** @var CustomerTokenServiceInterface $customerTokenService */
$customerTokenService = ObjectManager::getInstance()->get(CustomerTokenServiceInterface::class);
$customerToken = $customerTokenService->createCustomerAccessToken($userName, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
$response = $this->graphQlMutation($query, [], '', $headerMap);
$this->assertTrue($response['revokeCustomerToken']['result']);
}
/**
*/
public function testRevokeCustomerTokenForGuestCustomer()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
mutation {
revokeCustomerToken {
result
}
}
QUERY;
$this->graphQlMutation($query, [], '');
}
}
@@ -0,0 +1,73 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Class for Store Config customers settings
*/
class StoreConfigTest extends GraphQlAbstract
{
/**
* Check type of autocomplete_on_storefront storeConfig value
*
* @magentoConfigFixture default_store customer/password/autocomplete_on_storefront 1
*
* @throws Exception
*/
public function testReturnTypeAutocompleteOnStorefrontConfig()
{
$query = <<<QUERY
{
storeConfig {
autocomplete_on_storefront
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('autocomplete_on_storefront', $response['storeConfig']);
self::assertTrue($response['storeConfig']['autocomplete_on_storefront']);
}
#[
Config('customer/create_account/confirm', 1)
]
public function testCreateAccountConfirmationEnabledStorefrontConfig()
{
$query = <<<QUERY
{
storeConfig {
create_account_confirmation
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('create_account_confirmation', $response['storeConfig']);
self::assertTrue($response['storeConfig']['create_account_confirmation']);
}
#[
Config('customer/create_account/confirm', 0)
]
public function testCreateAccountConfirmationDisabledStorefrontConfig()
{
$query = <<<QUERY
{
storeConfig {
create_account_confirmation
}
}
QUERY;
$response = $this->graphQlQuery($query);
self::assertArrayHasKey('create_account_confirmation', $response['storeConfig']);
self::assertFalse($response['storeConfig']['create_account_confirmation']);
}
}
@@ -0,0 +1,206 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for subscription status
*/
class SubscriptionStatusTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var SubscriberFactory
*/
private $subscriberFactory;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->subscriberFactory = Bootstrap::getObjectManager()->get(SubscriberFactory::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testGetSubscriptionStatusTest()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
query {
customer {
is_subscribed
}
}
QUERY;
$response = $this->graphQlQuery($query, [], '', $this->getHeaderMap($currentEmail, $currentPassword));
$this->assertFalse($response['customer']['is_subscribed']);
}
/**
*/
public function testGetSubscriptionStatusIfUserIsNotAuthorizedTest()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
query {
customer {
is_subscribed
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testSubscribeCustomer()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
is_subscribed: true
}
) {
customer {
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation(
$query,
[],
'',
$this->getHeaderMap($currentEmail, $currentPassword)
);
$this->assertTrue($response['updateCustomer']['customer']['is_subscribed']);
}
/**
*/
public function testChangeSubscriptionStatuIfUserIsNotAuthorizedTest()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
mutation {
updateCustomer(
input: {
is_subscribed: true
}
) {
customer {
is_subscribed
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Newsletter/_files/subscribers.php
*/
public function testUnsubscribeCustomer()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
is_subscribed: false
}
) {
customer {
is_subscribed
}
}
}
QUERY;
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap($currentEmail, $currentPassword));
$this->assertFalse($response['updateCustomer']['customer']['is_subscribed']);
}
/**
* @magentoConfigFixture default_store customer/account_share/scope 0
* @magentoApiDataFixture Magento/Customer/_files/customer_for_second_website_with_address.php
*/
public function testSubscriptionStatusInMultiWebsiteSetup(): void
{
$currentEmail = 'customer_second_ws_with_addr@example.com';
$currentPassword = 'Apassword1';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
is_subscribed: true
}
) {
customer {
is_subscribed
}
}
}
QUERY;
$headers = [
'Store' => 'default',
'Authorization' => sprintf(
'Bearer %s',
$this->customerTokenService->createCustomerAccessToken($currentEmail, $currentPassword)
),
];
$response = $this->graphQlMutation($query, [], '', $headers);
$this->assertTrue($response['updateCustomer']['customer']['is_subscribed']);
}
/**
* @param string $email
* @param string $password
*
* @return array
* @throws AuthenticationException
*/
private function getHeaderMap(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
protected function tearDown(): void
{
parent::tearDown();
$this->subscriberFactory->create()->loadByCustomerId(1)->delete();
}
}
@@ -0,0 +1,598 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Update customer address tests
*/
class UpdateCustomerAddressTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
$this->addressRepository = Bootstrap::getObjectManager()->get(AddressRepositoryInterface::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testUpdateCustomerAddress()
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$mutation = $this->getMutation($addressId);
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('updateCustomerAddress', $response);
$this->assertArrayHasKey('customer_id', $response['updateCustomerAddress']);
$this->assertNull($response['updateCustomerAddress']['customer_id']);
$this->assertArrayHasKey('id', $response['updateCustomerAddress']);
$address = $this->addressRepository->getById($addressId);
$this->assertEquals($address->getId(), $response['updateCustomerAddress']['id']);
$this->assertCustomerAddressesFields($address, $response['updateCustomerAddress']);
$updateAddress = $this->getAddressData();
$this->assertCustomerAddressesFields($address, $updateAddress);
}
/**
* Test case for deprecated `country_id` field.
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testUpdateCustomerAddressWithCountryId()
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$updateAddress = $this->getAddressData();
$mutation = $mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: {$addressId}, input: {
region: {
region: "{$updateAddress['region']['region']}"
region_id: {$updateAddress['region']['region_id']}
region_code: "{$updateAddress['region']['region_code']}"
}
country_code: {$updateAddress['country_code']}
country_id: {$updateAddress['country_code']}
street: ["{$updateAddress['street'][0]}","{$updateAddress['street'][1]}"]
company: "{$updateAddress['company']}"
telephone: "{$updateAddress['telephone']}"
fax: "{$updateAddress['fax']}"
postcode: "{$updateAddress['postcode']}"
city: "{$updateAddress['city']}"
firstname: "{$updateAddress['firstname']}"
lastname: "{$updateAddress['lastname']}"
middlename: "{$updateAddress['middlename']}"
prefix: "{$updateAddress['prefix']}"
suffix: "{$updateAddress['suffix']}"
vat_id: "{$updateAddress['vat_id']}"
default_shipping: true
default_billing: true
}) {
country_id
}
}
MUTATION;
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertArrayHasKey('updateCustomerAddress', $response);
$this->assertEquals($updateAddress['country_code'], $response['updateCustomerAddress']['country_id']);
}
/**
*/
public function testUpdateCustomerAddressIfUserIsNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$addressId = 1;
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id:{$addressId}, input: {
city: "New City"
postcode: "5555"
}) {
id
}
}
MUTATION;
$this->graphQlMutation($mutation);
}
/**
* Verify customers with credentials update address
* with missing required Firstname attribute
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testUpdateCustomerAddressWithMissingAttribute()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameters are missing: firstname');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: {$addressId}, input: {
firstname: ""
lastname: "Phillis"
}) {
id
}
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Verify customers with credentials update address
* with missing required Firstname attribute
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testUpdateCustomerAddressWithoutMissingAttribute()
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: {$addressId}, input: {
firstname: "some"
lastname: "Phillis"
}) {
id
}
}
MUTATION;
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Test custom attributes of the customer's address
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @magentoApiDataFixture Magento/Customer/_files/attribute_user_defined_address_custom_attribute.php
*/
public function testUpdateCustomerAddressHasCustomAttributes()
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$attributes = [
[
'attribute_code' => 'custom_attribute1',
'value'=> '[new-value1,new-value2]'
],
[
'attribute_code' => 'custom_attribute2',
'value'=> '"new-value3"'
]
];
$attributesFragment = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($attributes));
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(
id: {$addressId}
input: {
custom_attributes: {$attributesFragment}
}
) {
custom_attributes {
attribute_code
value
}
}
}
MUTATION;
$response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
$this->assertEquals($attributes, $response['updateCustomerAddress']['custom_attributes']);
}
/**
* Verify the fields for Customer address
*
* @param AddressInterface $address
* @param array $actualResponse
* @param string $countryFieldName
*/
private function assertCustomerAddressesFields(
AddressInterface $address,
$actualResponse
): void {
/** @var $addresses */
$assertionMap = [
['response_field' => 'country_code', 'expected_value' => $address->getCountryId()],
['response_field' => 'street', 'expected_value' => $address->getStreet()],
['response_field' => 'company', 'expected_value' => $address->getCompany()],
['response_field' => 'telephone', 'expected_value' => $address->getTelephone()],
['response_field' => 'fax', 'expected_value' => $address->getFax()],
['response_field' => 'postcode', 'expected_value' => $address->getPostcode()],
['response_field' => 'city', 'expected_value' => $address->getCity()],
['response_field' => 'firstname', 'expected_value' => $address->getFirstname()],
['response_field' => 'lastname', 'expected_value' => $address->getLastname()],
['response_field' => 'middlename', 'expected_value' => $address->getMiddlename()],
['response_field' => 'prefix', 'expected_value' => $address->getPrefix()],
['response_field' => 'suffix', 'expected_value' => $address->getSuffix()],
['response_field' => 'vat_id', 'expected_value' => $address->getVatId()],
['response_field' => 'default_shipping', 'expected_value' => (bool)$address->isDefaultShipping()],
['response_field' => 'default_billing', 'expected_value' => (bool)$address->isDefaultBilling()],
];
$this->assertResponseFields($actualResponse, $assertionMap);
$this->assertIsArray([$actualResponse['region']], "region field must be of an array type.");
$assertionRegionMap = [
['response_field' => 'region', 'expected_value' => $address->getRegion()->getRegion()],
['response_field' => 'region_code', 'expected_value' => $address->getRegion()->getRegionCode()],
['response_field' => 'region_id', 'expected_value' => $address->getRegion()->getRegionId()]
];
$this->assertResponseFields($actualResponse['region'], $assertionRegionMap);
}
/**
* Update address with missing ID input.
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testUpdateCustomerAddressWithMissingId()
{
$userName = 'customer@example.com';
$password = 'password';
$updateAddress = $this->getAddressData();
$defaultShippingText = $updateAddress['default_shipping'] ? 'true' : 'false';
$defaultBillingText = $updateAddress['default_billing'] ? 'true' : 'false';
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(, input: {
region: {
region: "{$updateAddress['region']['region']}"
region_id: {$updateAddress['region']['region_id']}
region_code: "{$updateAddress['region']['region_code']}"
}
country_code: {$updateAddress['country_code']}
street: ["{$updateAddress['street'][0]}","{$updateAddress['street'][1]}"]
company: "{$updateAddress['company']}"
telephone: "{$updateAddress['telephone']}"
fax: "{$updateAddress['fax']}"
postcode: "{$updateAddress['postcode']}"
city: "{$updateAddress['city']}"
firstname: "{$updateAddress['firstname']}"
lastname: "{$updateAddress['lastname']}"
middlename: "{$updateAddress['middlename']}"
prefix: "{$updateAddress['prefix']}"
suffix: "{$updateAddress['suffix']}"
vat_id: "{$updateAddress['vat_id']}"
default_shipping: {$defaultShippingText}
default_billing: {$defaultBillingText}
}) {
id
}
}
MUTATION;
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'Field "updateCustomerAddress" argument "id" of type "Int!" is required but not provided.'
);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Update address with invalid ID input.
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testUpdateCustomerAddressWithInvalidIdType()
{
$userName = 'customer@example.com';
$password = 'password';
$updateAddress = $this->getAddressData();
$defaultShippingText = $updateAddress['default_shipping'] ? 'true' : 'false';
$defaultBillingText = $updateAddress['default_billing'] ? 'true' : 'false';
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: "", input: {
region: {
region: "{$updateAddress['region']['region']}"
region_id: {$updateAddress['region']['region_id']}
region_code: "{$updateAddress['region']['region_code']}"
}
country_code: {$updateAddress['country_code']}
street: ["{$updateAddress['street'][0]}","{$updateAddress['street'][1]}"]
company: "{$updateAddress['company']}"
telephone: "{$updateAddress['telephone']}"
fax: "{$updateAddress['fax']}"
postcode: "{$updateAddress['postcode']}"
city: "{$updateAddress['city']}"
firstname: "{$updateAddress['firstname']}"
lastname: "{$updateAddress['lastname']}"
middlename: "{$updateAddress['middlename']}"
prefix: "{$updateAddress['prefix']}"
suffix: "{$updateAddress['suffix']}"
vat_id: "{$updateAddress['vat_id']}"
default_shipping: {$defaultShippingText}
default_billing: {$defaultBillingText}
}) {
id
}
}
MUTATION;
$this->expectException(Exception::class);
$this->expectExceptionMessage('Int cannot represent non-integer value: ""');
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* Update address with invalid input
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
* @dataProvider invalidInputDataProvider
* @param string $input
* @param string $exceptionMessage
*/
public function testUpdateCustomerAddressWithInvalidInput(string $input, string $exceptionMessage)
{
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: {$addressId}, $input) {
id
}
}
MUTATION;
$this->expectException(Exception::class);
$this->expectExceptionMessage($exceptionMessage);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @return array
*/
public function invalidInputDataProvider()
{
return [
['', '"input" value must be specified'],
[
'input: ""',
'Expected value of type "CustomerAddressInput", found ""'
],
['input: "foo"', 'Expected value of type "CustomerAddressInput", found "foo"']
];
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testUpdateNotExistingCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not find a address with ID "9999"');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 9999;
$mutation = $this->getMutation($addressId);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/two_customers.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testUpdateAnotherCustomerAddress()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Current customer does not have permission to address with ID "1"');
$userName = 'customer_two@example.com';
$password = 'password';
$addressId = 1;
$mutation = $this->getMutation($addressId);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Customer/_files/customer_address.php
*/
public function testUpdateCustomerAddressIfAccountIsLocked()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The account is locked.');
$this->markTestSkipped('https://github.com/magento/graphql-ce/issues/750');
$userName = 'customer@example.com';
$password = 'password';
$addressId = 1;
$this->lockCustomer->execute(1);
$mutation = $this->getMutation($addressId);
$this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password));
}
/**
* @param string $email
* @param string $password
* @return array
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* @return array
*/
private function getAddressData(): array
{
return [
'region' => [
'region' => 'Alberta',
'region_id' => 66,
'region_code' => 'AB'
],
'country_code' => 'CA',
'street' => ['Line 1 Street', 'Line 2'],
'company' => 'Company Name',
'telephone' => '123456789',
'fax' => '123123123',
'postcode' => '7777',
'city' => 'City Name',
'firstname' => 'Adam',
'lastname' => 'Phillis',
'middlename' => 'A',
'prefix' => 'Mr.',
'suffix' => 'Jr.',
'vat_id' => '1',
'default_shipping' => true,
'default_billing' => true
];
}
/**
* @param int $addressId
* @return string
*/
private function getMutation(int $addressId): string
{
$updateAddress = $this->getAddressData();
$defaultShippingText = $updateAddress['default_shipping'] ? "true" : "false";
$defaultBillingText = $updateAddress['default_billing'] ? "true" : "false";
$mutation
= <<<MUTATION
mutation {
updateCustomerAddress(id: {$addressId}, input: {
region: {
region: "{$updateAddress['region']['region']}"
region_id: {$updateAddress['region']['region_id']}
region_code: "{$updateAddress['region']['region_code']}"
}
country_code: {$updateAddress['country_code']}
street: ["{$updateAddress['street'][0]}","{$updateAddress['street'][1]}"]
company: "{$updateAddress['company']}"
telephone: "{$updateAddress['telephone']}"
fax: "{$updateAddress['fax']}"
postcode: "{$updateAddress['postcode']}"
city: "{$updateAddress['city']}"
firstname: "{$updateAddress['firstname']}"
lastname: "{$updateAddress['lastname']}"
middlename: "{$updateAddress['middlename']}"
prefix: "{$updateAddress['prefix']}"
suffix: "{$updateAddress['suffix']}"
vat_id: "{$updateAddress['vat_id']}"
default_shipping: {$defaultShippingText}
default_billing: {$defaultBillingText}
}) {
id
customer_id
region {
region
region_id
region_code
}
country_code
street
company
telephone
fax
postcode
city
firstname
lastname
middlename
prefix
suffix
vat_id
default_shipping
default_billing
}
}
MUTATION;
return $mutation;
}
}
@@ -0,0 +1,379 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for update customer address with custom attributes V2
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_group_id' => 1,
'attribute_code' => 'simple_attribute',
'sort_order' => 2
],
'simple_attribute',
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_set_id' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_group_id' => 1,
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'multiselect_attribute',
'frontend_input' => 'multiselect',
'sort_order' => 1
],
'multiselect_attribute',
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 1',
'sort_order' => 20
],
'multiselect_attribute_option1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 2',
'sort_order' => 30
],
'multiselect_attribute_option2'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 3',
'sort_order' => 10
],
'multiselect_attribute_option3'
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
'addresses' => [
[
'country_id' => 'US',
'region_id' => 32,
'city' => 'Boston',
'street' => ['10 Milk Street'],
'postcode' => '02108',
'telephone' => '1234567890',
'default_billing' => true,
'default_shipping' => true,
'custom_attributes' => [
[
'attribute_code' => '$simple_attribute.attribute_code$',
'value' => 'value_one'
],
[
'attribute_code' => '$multiselect_attribute.attribute_code$',
'selected_options' => [
[
'value' => '$multiselect_attribute_option1.value$'
],
[
'value' => '$multiselect_attribute_option2.value$'
]
]
]
]
]
]
],
'customer'
)
]
class UpdateCustomerAddressWithCustomAttributesV2Test extends GraphQlAbstract
{
/**
* @var string
*/
private $currentPassword = 'password';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var AttributeMetadataInterface|null
*/
private $simple_attribute;
/**
* @var AttributeMetadataInterface|null
*/
private $multiselect_attribute;
/**
* @var AttributeOptionInterface|null
*/
private $option2;
/**
* @var AttributeOptionInterface|null
*/
private $option3;
/**
* @var CustomerInterface|null
*/
private $customer;
/**
* @var AddressInterface|null
*/
private $customerAddress;
/**
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->simple_attribute = DataFixtureStorageManager::getStorage()->get('simple_attribute');
$this->multiselect_attribute = DataFixtureStorageManager::getStorage()->get('multiselect_attribute');
$this->option2 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option2');
$this->option3 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option3');
$this->customer = DataFixtureStorageManager::getStorage()->get('customer');
$customerAddresses = $this->customer->getAddresses();
$this->customerAddress = array_shift($customerAddresses);
}
/**
* @return void
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testUpdateCustomerAddressWithCustomAttributesV2()
{
$query = <<<QUERY
mutation {
updateCustomerAddress(id: "%s", input: {
custom_attributesV2: [
{
attribute_code: "%s"
value: "%s"
},
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
custom_attributesV2 {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
QUERY;
$response = $this->graphQlMutation(
sprintf(
$query,
$this->customerAddress->getId(),
$this->simple_attribute->getAttributeCode(),
"another simple value",
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'updateCustomerAddress' =>
[
'custom_attributesV2' =>
[
0 =>
[
'code' => $this->multiselect_attribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->option3->getLabel(),
'value' => $this->option3->getValue()
],
[
'label' => $this->option2->getLabel(),
'value' => $this->option2->getValue()
]
]
],
1 =>
[
'code' => $this->simple_attribute->getAttributeCode(),
'value' => 'another simple value'
]
],
],
],
$response
);
}
/**
* @return void
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testAttemptToUpdateCustomerAddressPassingNonExistingOption()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Attribute multiselect_attribute does not contain option with Id 1345");
$query = <<<QUERY
mutation {
updateCustomerAddress(id: "%s", input: {
custom_attributesV2: [
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
custom_attributesV2 {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
value
label
}
}
}
}
}
QUERY;
$this->graphQlMutation(
sprintf(
$query,
$this->customerAddress->getId(),
$this->multiselect_attribute->getAttributeCode(),
"1345"
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
}
/**
* @return void
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testAttemptToUpdateCustomerAddressPassingSelectedOptionsToDeprecatedCustomAttributes()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
"Field \"selected_options\" is not defined by type \"CustomerAddressAttributeInput\""
);
$query = <<<QUERY
mutation {
updateCustomerAddress(id: "%s", input: {
custom_attributes: [
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}) {
custom_attributes {
attribute_code
value
selected_options {
value
label
}
}
}
}
QUERY;
$this->graphQlMutation(
sprintf(
$query,
$this->customerAddress->getId(),
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
}
/**
* @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,171 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\CustomerGraphQl\Model\Customer\UpdateCustomerAccount;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for update customer's email
*/
class UpdateCustomerEmailTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var UpdateCustomerAccount
*/
private $updateCustomerAccount;
/**
* @var StoreRepositoryInterface
*/
private $storeRepository;
/**
* Setting up tests
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
$this->updateCustomerAccount = Bootstrap::getObjectManager()->get(UpdateCustomerAccount::class);
$this->storeRepository = Bootstrap::getObjectManager()->get(StoreRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerEmail(): void
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newEmail = 'newcustomer@example.com';
$query = <<<QUERY
mutation {
updateCustomerEmail(
email: "{$newEmail}"
password: "{$currentPassword}"
) {
customer {
email
}
}
}
QUERY;
$response = $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
$this->assertEquals($newEmail, $response['updateCustomerEmail']['customer']['email']);
/* $this->updateCustomerAccount->execute(
$this->customerRepository->get($newEmail),
['email' => $currentEmail, 'password' => $currentPassword],
$this->storeRepository->getById(1)
);*/
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerEmailIfPasswordIsWrong(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid login or password.');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newEmail = 'newcustomer@example.com';
$wrongPassword = 'wrongpassword';
$query = <<<QUERY
mutation {
updateCustomerEmail(
email: "{$newEmail}"
password: "{$wrongPassword}"
) {
customer {
email
}
}
}
QUERY;
$this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/two_customers.php
*/
public function testUpdateEmailIfEmailAlreadyExists()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'A customer with the same email address already exists in an associated website.'
);
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$existedEmail = 'customer_two@example.com';
$query = <<<QUERY
mutation {
updateCustomerEmail(
email: "{$existedEmail}"
password: "{$currentPassword}"
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* Get customer authorization 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,435 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Model\CustomerAuthUpdate;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for update customer
*/
class UpdateCustomerTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CustomerAuthUpdate
*/
private $customerAuthUpdate;
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->customerAuthUpdate = Bootstrap::getObjectManager()->get(CustomerAuthUpdate::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomer()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newPrefix = 'Dr';
$newFirstname = 'Richard';
$newMiddlename = 'Riley';
$newLastname = 'Rowe';
$newSuffix = 'III';
$newDob = '3/11/1972';
$newTaxVat = 'GQL1234567';
$newGender = 2;
$newEmail = 'customer_updated@example.com';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
prefix: "{$newPrefix}"
firstname: "{$newFirstname}"
middlename: "{$newMiddlename}"
lastname: "{$newLastname}"
suffix: "{$newSuffix}"
date_of_birth: "{$newDob}"
taxvat: "{$newTaxVat}"
email: "{$newEmail}"
password: "{$currentPassword}"
gender: {$newGender}
}
) {
customer {
prefix
firstname
middlename
lastname
suffix
date_of_birth
taxvat
email
gender
}
}
}
QUERY;
$response = $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
$this->assertEquals($newPrefix, $response['updateCustomer']['customer']['prefix']);
$this->assertEquals($newFirstname, $response['updateCustomer']['customer']['firstname']);
$this->assertEquals($newMiddlename, $response['updateCustomer']['customer']['middlename']);
$this->assertEquals($newLastname, $response['updateCustomer']['customer']['lastname']);
$this->assertEquals($newSuffix, $response['updateCustomer']['customer']['suffix']);
$this->assertEquals($newDob, $response['updateCustomer']['customer']['date_of_birth']);
$this->assertEquals($newTaxVat, $response['updateCustomer']['customer']['taxvat']);
$this->assertEquals($newEmail, $response['updateCustomer']['customer']['email']);
$this->assertEquals($newGender, $response['updateCustomer']['customer']['gender']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfInputDataIsEmpty()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('"input" value should be specified');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
*/
public function testUpdateCustomerIfUserIsNotAuthorized()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$newFirstname = 'Richard';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
firstname: "{$newFirstname}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfAccountIsLocked()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The account is locked.');
$this->lockCustomer->execute(1);
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newFirstname = 'Richard';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
firstname: "{$newFirstname}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateEmailIfPasswordIsMissed()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Provide the current "password" to change "email".');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newEmail = 'customer_updated@example.com';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
email: "{$newEmail}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateEmailIfPasswordIsInvalid()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid login or password.');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$invalidPassword = 'invalid_password';
$newEmail = 'customer_updated@example.com';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
email: "{$newEmail}"
password: "{$invalidPassword}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/two_customers.php
*/
public function testUpdateEmailIfEmailAlreadyExists()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
'A customer with the same email address already exists in an associated website.'
);
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$existedEmail = 'customer_two@example.com';
$firstname = 'Richard';
$lastname = 'Rowe';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
email: "{$existedEmail}"
password: "{$currentPassword}"
firstname: "{$firstname}"
lastname: "{$lastname}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateEmailIfEmailIsInvalid()
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$invalidEmail = 'customer.example.com';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
email: "{$invalidEmail}"
password: "{$currentPassword}"
}
) {
customer {
email
}
}
}
QUERY;
$this->expectException(Exception::class);
$this->expectExceptionMessage('"' . $invalidEmail . '" is not a valid email address.');
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testEmptyCustomerName()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Required parameters are missing: First Name');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
email: "{$currentEmail}"
password: "{$currentPassword}"
firstname: ""
}
) {
customer {
email
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testEmptyCustomerLastName()
{
$query = <<<QUERY
mutation {
updateCustomer(
input: {
lastname: ""
}
) {
customer {
lastname
}
}
}
QUERY;
$this->expectException(Exception::class);
$this->expectExceptionMessage('Required parameters are missing: Last Name');
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders('customer@example.com', 'password'));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerWithIncorrectGender()
{
$gender = 5;
$this->expectException(Exception::class);
$this->expectExceptionMessage('"' . $gender . '" is not a valid gender value.');
$query = <<<QUERY
mutation {
updateCustomer(
input: {
gender: {$gender}
}
) {
customer {
gender
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders('customer@example.com', 'password'));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfDobIsInvalid()
{
$invalidDob = 'bla-bla-bla';
$query = <<<QUERY
mutation {
updateCustomer(
input: {
date_of_birth: "{$invalidDob}"
}
) {
customer {
date_of_birth
}
}
}
QUERY;
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid date');
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders('customer@example.com', 'password'));
}
/**
* @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,273 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for new update customer endpoint
*/
class UpdateCustomerV2Test extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var LockCustomer
*/
private $lockCustomer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->lockCustomer = Bootstrap::getObjectManager()->get(LockCustomer::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomer(): void
{
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newPrefix = 'Dr';
$newFirstname = 'Richard';
$newMiddlename = 'Riley';
$newLastname = 'Rowe';
$newSuffix = 'III';
$newDob = '3/11/1972';
$newTaxVat = 'GQL1234567';
$newGender = 2;
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
prefix: "{$newPrefix}"
firstname: "{$newFirstname}"
middlename: "{$newMiddlename}"
lastname: "{$newLastname}"
suffix: "{$newSuffix}"
date_of_birth: "{$newDob}"
taxvat: "{$newTaxVat}"
gender: {$newGender}
}
) {
customer {
prefix
firstname
middlename
lastname
suffix
date_of_birth
taxvat
email
gender
}
}
}
QUERY;
$response = $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders($currentEmail, $currentPassword)
);
$this->assertEquals($newPrefix, $response['updateCustomerV2']['customer']['prefix']);
$this->assertEquals($newFirstname, $response['updateCustomerV2']['customer']['firstname']);
$this->assertEquals($newMiddlename, $response['updateCustomerV2']['customer']['middlename']);
$this->assertEquals($newLastname, $response['updateCustomerV2']['customer']['lastname']);
$this->assertEquals($newSuffix, $response['updateCustomerV2']['customer']['suffix']);
$this->assertEquals($newDob, $response['updateCustomerV2']['customer']['date_of_birth']);
$this->assertEquals($newTaxVat, $response['updateCustomerV2']['customer']['taxvat']);
$this->assertEquals($newGender, $response['updateCustomerV2']['customer']['gender']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfInputDataIsEmpty(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('"input" value should be specified');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
*/
public function testUpdateCustomerIfUserIsNotAuthorized(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$newFirstname = 'Richard';
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
firstname: "{$newFirstname}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfAccountIsLocked(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The account is locked.');
$this->lockCustomer->execute(1);
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$newFirstname = 'Richard';
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
firstname: "{$newFirstname}"
}
) {
customer {
firstname
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testEmptyCustomerName(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Required parameters are missing: First Name');
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
firstname: ""
}
) {
customer {
email
}
}
}
QUERY;
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testEmptyCustomerLastName(): void
{
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
lastname: ""
}
) {
customer {
lastname
}
}
}
QUERY;
$this->expectException(Exception::class);
$this->expectExceptionMessage('Required parameters are missing: Last Name');
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders('customer@example.com', 'password'));
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testUpdateCustomerIfDobIsInvalid(): void
{
$invalidDob = 'bla-bla-bla';
$query = <<<QUERY
mutation {
updateCustomerV2(
input: {
date_of_birth: "{$invalidDob}"
}
) {
customer {
date_of_birth
}
}
}
QUERY;
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid date');
$this->graphQlMutation($query, [], '', $this->getCustomerAuthHeaders('customer@example.com', 'password'));
}
/**
* @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,529 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Customer;
use Exception;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Fixture\CustomerAttribute;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
use Magento\Eav\Test\Fixture\AttributeOption as AttributeOptionFixture;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Tests for update customer V2
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'attribute_code' => 'random_attribute',
'sort_order' => 2
],
'random_attribute',
),
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'source_model' => Table::class,
'backend_model' => ArrayBackend::class,
'attribute_code' => 'multiselect_attribute',
'frontend_input' => 'multiselect',
'sort_order' => 1
],
'multiselect_attribute',
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'line 1',
'sort_order' => 20
],
'multiselect_attribute_option1'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'option 2',
'sort_order' => 30
],
'multiselect_attribute_option2'
),
DataFixture(
AttributeOptionFixture::class,
[
'entity_type' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_code' => '$multiselect_attribute.attribute_code$',
'label' => 'option 3',
'sort_order' => 10
],
'multiselect_attribute_option3'
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
'custom_attributes' => [
[
'attribute_code' => '$random_attribute.attribute_code$',
'value' => 'value_one'
],
[
'attribute_code' => '$multiselect_attribute.attribute_code$',
'selected_options' => [
[
'value' => '$multiselect_attribute_option1.value$'
],
[
'value' => '$multiselect_attribute_option2.value$'
]
]
]
]
],
'customer'
)
]
class UpdateCustomerV2WithCustomAttributesTest extends GraphQlAbstract
{
/**
* @var string
*/
private $simpleQuery = <<<QUERY
mutation {
updateCustomerV2(
input: {
custom_attributes: [
{
attribute_code: "%s",
value: "%s"
}
]
}
) {
customer {
email
custom_attributes {
code
... on AttributeValue {
value
}
}
}
}
}
QUERY;
/**
* @var string
*/
private $query = <<<QUERY
mutation {
updateCustomerV2(
input: {
custom_attributes: [
{
attribute_code: "%s",
value: "%s"
}
{
attribute_code: "%s"
value: "%s"
selected_options: []
}
]
}
) {
customer {
email
custom_attributes {
code
... on AttributeValue {
value
}
... on AttributeSelectedOptions {
selected_options {
label
value
}
}
}
}
}
}
QUERY;
/**
* @var string
*/
private $currentPassword = 'password';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var AttributeMetadataInterface|null
*/
private $random_attribute;
/**
* @var AttributeMetadataInterface|null
*/
private $multiselect_attribute;
/**
* @var AttributeOptionInterface|null
*/
private $option2;
/**
* @var AttributeOptionInterface|null
*/
private $option3;
/**
* @var CustomerInterface|null
*/
private $customer;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
$this->random_attribute = DataFixtureStorageManager::getStorage()->get('random_attribute');
$this->multiselect_attribute = DataFixtureStorageManager::getStorage()->get('multiselect_attribute');
$this->option2 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option2');
$this->option3 = DataFixtureStorageManager::getStorage()->get('multiselect_attribute_option3');
$this->customer = DataFixtureStorageManager::getStorage()->get('customer');
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
*/
public function testUpdateCustomerWithCorrectCustomerAttribute(): void
{
$response = $this->graphQlMutation(
sprintf(
$this->query,
$this->random_attribute->getAttributeCode(),
'new_value_for_attribute',
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($this->customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'updateCustomerV2' =>
[
'customer' =>
[
'email' => 'customer@example.com',
'custom_attributes' =>
[
0 =>
[
'code' => $this->multiselect_attribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->option3->getLabel(),
'value' => $this->option3->getValue()
],
[
'label' => $this->option2->getLabel(),
'value' => $this->option2->getValue()
]
]
],
1 =>
[
'code' => $this->random_attribute->getAttributeCode(),
'value' => 'new_value_for_attribute'
]
],
],
],
],
$response
);
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
*/
public function testAttemptToUpdateCustomerPassingNonExistingCustomerAttribute(): void
{
/** @var CustomerInterface $customer */
$customer = DataFixtureStorageManager::getStorage()->get('customer');
$response = $this->graphQlMutation(
sprintf(
$this->query,
'non_existing_custom_attribute',
'new_value_for_attribute',
$this->multiselect_attribute->getAttributeCode(),
$this->option2->getValue() . "," . $this->option3->getValue()
),
[],
'',
$this->getCustomerAuthHeaders($customer->getEmail(), $this->currentPassword)
);
$this->assertEquals(
[
'updateCustomerV2' =>
[
'customer' =>
[
'email' => 'customer@example.com',
'custom_attributes' =>
[
0 =>
[
'code' => $this->multiselect_attribute->getAttributeCode(),
'selected_options' => [
[
'label' => $this->option3->getLabel(),
'value' => $this->option3->getValue()
],
[
'label' => $this->option2->getLabel(),
'value' => $this->option2->getValue()
]
]
],
1 =>
[
'code' => $this->random_attribute->getAttributeCode(),
'value' => 'value_one'
]
],
],
],
],
$response
);
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
* @throws Exception
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'sort_order' => 1,
'attribute_code' => 'date_attribute',
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'frontend_input' => 'date',
'backend_type' => 'datetime',
'input_filter' => 'date',
],
'date_attribute',
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
'custom_attributes' => [
[
'attribute_code' => '$date_attribute.attribute_code$',
'value' => '2023-03-22 00:00:00'
]
]
],
'customer'
)
]
public function testAttemptToUpdateCustomerAttributeWithInvalidDataType(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid date");
/** @var CustomerInterface $customer */
$customer = DataFixtureStorageManager::getStorage()->get('customer');
/** @var AttributeMetadataInterface $date_attribute */
$date_attribute = DataFixtureStorageManager::getStorage()->get('date_attribute');
$this->graphQlMutation(
sprintf(
$this->simpleQuery,
$date_attribute->getAttributeCode(),
'this_is_an_invalid_value_for_dates'
),
[],
'',
$this->getCustomerAuthHeaders($customer->getEmail(), $this->currentPassword)
);
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'attribute_code' => 'date_range_attribute',
'frontend_input' => 'date',
'frontend_class' => 'Magento\Eav\Model\Entity\Attribute\Frontend\Datetime',
'backend_model' => 'Magento\Eav\Model\Entity\Attribute\Backend\Datetime',
'backend_type' => 'datetime',
'input_filter' => 'date',
'validate_rules' =>
'{"date_range_min":1679443200,"date_range_max":1679875200,"input_validation":"date"}'
],
'date_range_attribute',
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
'custom_attributes' => [
[
'attribute_code' => '$date_range_attribute.attribute_code$',
'value' => '1679443200'
]
]
],
'customer'
)
]
public function testAttemptToUpdateCustomerAttributeWithInvalidValue(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Please enter a valid date between 22/03/2023 and 27/03/2023");
/** @var CustomerInterface $customer */
$customer = DataFixtureStorageManager::getStorage()->get('customer');
/** @var AttributeMetadataInterface $date_range */
$date_range = DataFixtureStorageManager::getStorage()->get('date_range_attribute');
$this->graphQlMutation(
sprintf(
$this->simpleQuery,
$date_range->getAttributeCode(),
'1769443200'
),
[],
'',
$this->getCustomerAuthHeaders($customer->getEmail(), $this->currentPassword)
);
}
/**
* @return void
* @throws AuthenticationException
* @throws LocalizedException
*/
#[
DataFixture(
CustomerAttribute::class,
[
'entity_type_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'sort_order' => 1,
'attribute_code' => 'boolean_attribute',
'attribute_set_id' => CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
'attribute_group_id' => 1,
'frontend_input' => 'boolean',
'source_model' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean'
],
'boolean_attribute',
),
DataFixture(
Customer::class,
[
'email' => 'customer@example.com',
'custom_attributes' => [
[
'attribute_code' => '$boolean_attribute.attribute_code$',
'value' => '1'
]
]
],
'customer'
)
]
public function testAttemptToUpdateBooleanCustomerAttributeWithInvalidValue(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Attribute boolean_attribute does not contain option with Id 3");
/** @var CustomerInterface $customer */
$customer = DataFixtureStorageManager::getStorage()->get('customer');
/** @var AttributeMetadataInterface $date_attribute */
$date_attribute = DataFixtureStorageManager::getStorage()->get('boolean_attribute');
$this->graphQlMutation(
sprintf(
$this->simpleQuery,
$date_attribute->getAttributeCode(),
"3"
),
[],
'',
$this->getCustomerAuthHeaders($customer->getEmail(), $this->currentPassword)
);
}
/**
* @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];
}
}