ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,238 @@
<?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']);
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
}
}
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,866 @@
<?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' => 'UA',
'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']}
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,388 @@
<?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);
}
/**
* @throws \Exception
*/
public function testCreateCustomerAccountWithPassword()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomer(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
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($newEmail, $response['createCustomer']['customer']['email']);
$this->assertTrue($response['createCustomer']['customer']['is_subscribed']);
}
/**
* @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'],
['jØrgen@somedomain.com'],
['#@%^%#$@#$@#.com'],
['@example.com'],
['Joe Smith <email@example.com>'],
['email.example.com'],
['email@example@example.com'],
['email@example.com (Joe Smith)'],
['email@example'],
['“email”@example.com'],
];
}
/**
*/
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,388 @@
<?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);
}
/**
* @throws \Exception
*/
public function testCreateCustomerAccountWithPassword()
{
$newFirstname = 'Richard';
$newLastname = 'Rowe';
$currentPassword = 'test123#';
$newEmail = 'new_customer@example.com';
$query = <<<QUERY
mutation {
createCustomerV2(
input: {
firstname: "{$newFirstname}"
lastname: "{$newLastname}"
email: "{$newEmail}"
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($newEmail, $response['createCustomerV2']['customer']['email']);
$this->assertTrue($response['createCustomerV2']['customer']['is_subscribed']);
}
/**
* @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'],
['jØrgen@somedomain.com'],
['#@%^%#$@#$@#.com'],
['@example.com'],
['Joe Smith <email@example.com>'],
['email.example.com'],
['email@example@example.com'],
['email@example.com (Joe Smith)'],
['email@example'],
['“email”@example.com'],
];
}
/**
*/
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,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,226 @@
<?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\ObjectManagerInterface;
use Magento\Integration\Api\AdminTokenServiceInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Bootstrap as TestBootstrap;
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
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* @param int $customerId
* @return void
*/
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,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,38 @@
<?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\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']);
}
}
@@ -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,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];
}
}