This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,352 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Account;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Delegation\Storage as DelegatedStorage;
use Magento\Framework\App\Http;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\UrlInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item as OrderItem;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\Request;
use Magento\TestFramework\TestCase\AbstractController;
use Magento\Theme\Controller\Result\MessagePlugin;
/**
* Tests from customer account create post action.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CreatePostTest extends AbstractController
{
/**
* @var TransportBuilderMock
*/
private $transportBuilderMock;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var CookieManagerInterface
*/
private $cookieManager;
/**
* @var UrlInterface
*/
private $urlBuilder;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilderMock = $this->_objectManager->get(TransportBuilderMock::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$this->cookieManager = $this->_objectManager->get(CookieManagerInterface::class);
$this->urlBuilder = $this->_objectManager->get(UrlInterface::class);
}
/**
* Tests that without form key user account won't be created
* and user will be redirected on account creation page again.
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @return void
*/
public function testNoFormKeyCreatePostAction(): void
{
$this->fillRequestWithAccountData('test1@email.com');
$this->getRequest()->setPostValue('form_key', null);
$this->dispatch('customer/account/createPost');
$this->assertCustomerNotExists('test1@email.com');
$this->assertRedirect($this->stringEndsWith('customer/account/create/'));
$this->assertSessionMessages(
$this->stringContains((string)__('Invalid Form Key. Please refresh the page.')),
MessageInterface::TYPE_ERROR
);
}
/**
* Check that DateTime option is NOT changed after creating Customer account for which guest order was placed.
*
* @return void
* @magentoDataFixture Magento/Sales/_files/guest_order_with_product_and_custom_options.php
*/
public function testCreateCustomerAccountAfterIssuingGuestOrder(): void
{
/** @var Order $order */
$order = $this->_objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
/** @var CustomerInterface $customer */
$customer = $this->_objectManager->create(CustomerInterface::class);
/** @var DelegatedStorage $delegatedStorage */
$delegatedStorage = $this->_objectManager->get(DelegatedStorage::class);
$delegatedStorage->storeNewOperation($customer, ['__sales_assign_order_id' => $order->getId()]);
$this->fillRequestWithAccountData('customer@example.com');
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringEndsWith('customer/account/'));
$this->assertSessionMessages(
$this->containsEqual(
(string)__('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName())
),
MessageInterface::TYPE_SUCCESS
);
$expectedResult = [
'year' => '2021',
'month' => '9',
'day' => '9',
'hour' => '2',
'minute' => '2',
'day_part' => 'am',
'date_internal' => '2021-09-09 02:02:00',
];
/** @var OrderItem $orderItem */
$orderItem = $order->getItemsCollection()->getFirstItem();
$actualResult = current($orderItem->getBuyRequest()->getOptions());
$this->assertIsArray($actualResult);
$this->assertEquals($expectedResult, $actualResult);
}
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoConfigFixture current_website customer/create_account/confirm 0
* @magentoConfigFixture current_store customer/create_account/default_group 1
* @magentoConfigFixture current_store customer/create_account/generate_human_friendly_id 0
*
* @return void
*/
public function testNoConfirmCreatePostAction(): void
{
$this->fillRequestWithAccountData('test1@email.com');
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringEndsWith('customer/account/'));
$this->assertSessionMessages(
$this->containsEqual(
(string)__('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName())
),
MessageInterface::TYPE_SUCCESS
);
$customer = $this->customerRegistry->retrieveByEmail('test1@email.com');
//Assert customer group
$this->assertEquals(1, $customer->getDataModel()->getGroupId());
//Assert customer increment id generation
$this->assertNull($customer->getData('increment_id'));
}
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoConfigFixture current_website customer/create_account/confirm 0
* @magentoConfigFixture current_store customer/create_account/default_group 2
* @magentoConfigFixture current_store customer/create_account/generate_human_friendly_id 1
* @return void
*/
public function testCreatePostWithCustomConfiguration(): void
{
$this->fillRequestWithAccountData('test@email.com');
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringEndsWith('customer/account/'));
$this->assertSessionMessages(
$this->containsEqual(
(string)__('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName())
),
MessageInterface::TYPE_SUCCESS
);
$customer = $this->customerRegistry->retrieveByEmail('test@email.com');
//Assert customer group
$this->assertEquals(2, $customer->getDataModel()->getGroupId());
//Assert customer increment id generation
$this->assertNotNull($customer->getData('increment_id'));
$this->assertMatchesRegularExpression('/\d{8}/', $customer->getData('increment_id'));
}
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoConfigFixture current_website customer/create_account/confirm 1
*
* @return void
*/
public function testWithConfirmCreatePostAction(): void
{
$email = 'test2@email.com';
$this->fillRequestWithAccountData($email);
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringContains('customer/account/index/'));
$message = 'You must confirm your account.'
. ' Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.';
$url = $this->urlBuilder->getUrl('customer/account/confirmation', ['_query' => ['email' => $email]]);
$this->assertSessionMessages(
$this->containsEqual((string)__($message, $url)),
MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testExistingEmailCreatePostAction(): void
{
$this->fillRequestWithAccountData('customer@example.com');
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringContains('customer/account/create/'));
$message = 'There is already an account with this email address.'
. ' If you are sure that it is your email address, <a href="%1">click here</a> '
. 'to get your password and access your account.';
$url = $this->urlBuilder->getUrl('customer/account/forgotpassword');
$this->assertSessionMessages($this->containsEqual((string)__($message, $url)), MessageInterface::TYPE_ERROR);
}
/**
* Register Customer with email confirmation.
*
* @magentoAppArea frontend
* @magentoConfigFixture current_website customer/create_account/confirm 1
*
* @return void
*/
public function testRegisterCustomerWithEmailConfirmation(): void
{
$email = 'test_example@email.com';
$this->fillRequestWithAccountData($email);
$this->dispatch('customer/account/createPost');
$this->assertRedirect($this->stringContains('customer/account/index/'));
$message = 'You must confirm your account.'
. ' Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.';
$url = $this->urlBuilder->getUrl('customer/account/confirmation', ['_query' => ['email' => $email]]);
$this->assertSessionMessages($this->containsEqual((string)__($message, $url)), MessageInterface::TYPE_SUCCESS);
/** @var CustomerInterface $customer */
$customer = $this->customerRepository->get($email);
$confirmation = $customer->getConfirmation();
$sendMessage = $this->transportBuilderMock->getSentMessage();
$this->assertNotNull($sendMessage);
$rawMessage = $sendMessage->getBody()->getParts()[0]->getRawContent();
$this->assertStringContainsString(
(string)__(
'You must confirm your %customer_email email before you can sign in (link is only valid once):',
['customer_email' => $email]
),
$rawMessage
);
$this->assertStringContainsString(
sprintf('customer/account/confirm/?id=%s&amp;key=%s', $customer->getId(), $confirmation),
$rawMessage
);
$this->resetRequest();
$this->getRequest()
->setParam('id', $customer->getId())
->setParam('key', $confirmation);
$this->dispatch('customer/account/confirm');
$this->assertRedirect($this->stringContains('customer/account/index/'));
$this->assertSessionMessages(
$this->containsEqual(
(string)__('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName())
),
MessageInterface::TYPE_SUCCESS
);
$this->assertEmpty($this->customerRepository->get($email)->getConfirmation());
}
/**
* Fills request with customer data.
*
* @param string $email
* @return void
*/
private function fillRequestWithAccountData(string $email): void
{
$this->getRequest()
->setMethod(HttpRequest::METHOD_POST)
->setParam(CustomerInterface::FIRSTNAME, 'firstname1')
->setParam(CustomerInterface::LASTNAME, 'lastname1')
->setParam(CustomerInterface::EMAIL, $email)
->setParam('password', '_Password1')
->setParam('password_confirmation', '_Password1')
->setParam('telephone', '5123334444')
->setParam('street', ['1234 fake street', ''])
->setParam('city', 'Austin')
->setParam('postcode', '78701')
->setParam('country_id', 'US')
->setParam('default_billing', '1')
->setParam('default_shipping', '1')
->setParam('is_subscribed', '0')
->setPostValue('create_address', true);
}
/**
* Asserts that customer does not exists.
*
* @param string $email
* @return void
*/
private function assertCustomerNotExists(string $email): void
{
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage(
(string)__(
'No such entity with %fieldName = %fieldValue, %field2Name = %field2Value',
[
'fieldName' => 'email',
'fieldValue' => $email,
'field2Name' => 'websiteId',
'field2Value' => 1
]
)
);
$this->assertNull($this->customerRepository->get($email));
}
/**
* Clears request.
*
* @return void
*/
protected function resetRequest(): void
{
parent::resetRequest();
$this->cookieManager->deleteCookie(MessagePlugin::MESSAGES_COOKIES_NAME);
$this->_objectManager->removeSharedInstance(Http::class);
$this->_objectManager->removeSharedInstance(Request::class);
}
}
@@ -0,0 +1,204 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Account;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Mail\EmailMessage;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Set of tests to verify e-mail templates delivered to Customers
*
* @magentoAppArea frontend
*/
class EmailTemplateTest extends AbstractController
{
private const FIXTURE_CUSTOMER_EMAIL = 'customer@example.com';
private const FIXTURE_CUSTOMER_FIRSTNAME = 'John';
private const FIXTURE_CUSTOMER_LASTNAME = 'Smith';
private const FIXTURE_CUSTOMER_ID = 1;
private const FIXTURE_CUSTOMER_PASSWORD = 'password';
private const EXPECTED_GREETING = self::FIXTURE_CUSTOMER_FIRSTNAME . ' ' . self::FIXTURE_CUSTOMER_LASTNAME . ',';
/**
* @var TransportBuilderMock
*/
private $transportBuilderMock;
/**
* @var Session
*/
private $session;
/**
* @var FormKey
*/
private $formKey;
protected function setUp(): void
{
parent::setUp();
$this->transportBuilderMock = $this->_objectManager->get(TransportBuilderMock::class);
$this->session = $this->_objectManager->get(Session::class);
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture current_store customer/captcha/enable 0
*/
public function testForgotPasswordEmailTemplateGreeting()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST)
->setPostValue(['email' => self::FIXTURE_CUSTOMER_EMAIL]);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage());
}
/**
* Covers Magento_Customer::view/frontend/email/change_email.html
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture current_store customer/captcha/enable 0
*/
public function testCustomerEmailChangeNotificationTemplateGreeting()
{
$this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID);
$this->sendAccountEditRequest([
'email' => 'new.email@example.com',
'change_email' => 1,
]);
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['You saved the account information.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage());
}
/**
* Covers Magento_Customer::view/frontend/email/change_email_and_password.html
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture current_store customer/captcha/enable 0
*/
public function testCustomerEmailAndPasswordChangeNotificationTemplateGreeting()
{
$this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID);
$this->sendAccountEditRequest([
'email' => 'new.email@example.com',
'change_email' => 1,
'change_password' => 1,
'password' => 'new-Password1',
'password_confirmation' => 'new-Password1',
]);
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['You saved the account information.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage());
}
/**
* Covers Magento_Customer::view/frontend/email/change_password.html
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture current_store customer/captcha/enable 0
*/
public function testCustomerPasswordChangeNotificationTemplateGreeting()
{
$this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID);
$this->sendAccountEditRequest([
'change_password' => 1,
'password' => 'new-Password1',
'password_confirmation' => 'new-Password1',
]);
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['You saved the account information.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage());
}
/**
* Wraps Customer Edit POST request
*
* @param array $customData
*/
private function sendAccountEditRequest(array $customData): void
{
$basicData = [
'form_key' => $this->formKey->getFormKey(),
'firstname' => self::FIXTURE_CUSTOMER_FIRSTNAME,
'lastname' => self::FIXTURE_CUSTOMER_LASTNAME,
'current_password' => self::FIXTURE_CUSTOMER_PASSWORD
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST)
->setPostValue(array_merge($basicData, $customData));
$this->dispatch('customer/account/editPost');
}
/**
* Verifies if `<p class="greeting"/>` text contents equals the expected one.
*
* @param string $expectedGreeting
* @param EmailMessage $message
*/
private function assertSameGreeting(string $expectedGreeting, EmailMessage $message)
{
$messageContent = $this->getMessageRawContent($message);
$emailDom = new \DOMDocument();
$emailDom->loadHTML($messageContent);
$emailXpath = new \DOMXPath($emailDom);
$greeting = $emailXpath->query('//p[@class="greeting"]');
$this->assertSame(1, $greeting->length);
$this->assertSame($expectedGreeting, $greeting->item(0)->textContent);
}
/**
* Returns raw content of provided message
*
* @param EmailMessage $message
* @return string
*/
private function getMessageRawContent(EmailMessage $message): string
{
$emailParts = $message->getBody()->getParts();
return current($emailParts)->getRawContent();
}
/**
* Performs Customer log in
*
* @param int $customerId
*/
private function loginByCustomerId(int $customerId): void
{
$this->session->loginById($customerId);
}
}
@@ -0,0 +1,266 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Account;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Url;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Phrase;
use Magento\Framework\Session\Generic;
use Magento\Framework\Url\EncoderInterface;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Class checks customer login action
*
* @see \Magento\Customer\Controller\Account\LoginPost
*/
class LoginPostTest extends AbstractController
{
/** @var Session */
private $session;
/** @var EncoderInterface */
private $urlEncoder;
/**
* @var Url
*/
private $customerUrl;
/**
* @var Generic
*/
private $generic;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->session = $this->_objectManager->get(Session::class);
$this->urlEncoder = $this->_objectManager->get(EncoderInterface::class);
$this->customerUrl = $this->_objectManager->get(Url::class);
$this->generic = $this->_objectManager->get(Generic::class);
}
/**
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @dataProvider missingParametersDataProvider
*
* @param string|null $email
* @param string|null $password
* @param string $expectedErrorMessage
* @return void
*/
public function testLoginIncorrectParameters(?string $email, ?string $password, string $expectedErrorMessage): void
{
$this->prepareRequest($email, $password);
$this->dispatch('customer/account/loginPost');
$this->assertSessionMessages(
$this->equalTo([(string)__($expectedErrorMessage)]),
MessageInterface::TYPE_ERROR
);
}
/**
* @return array
*/
public function missingParametersDataProvider(): array
{
return [
'missing_email' => [
'email' => null,
'password' => 'password',
'expected_error_message' => 'A login and a password are required.',
],
'missing_password' => [
'email' => 'customer@example.com',
'password' => null,
'expected_error_message' => 'A login and a password are required.',
],
'missing_both_parameters' => [
'email' => null,
'password' => null,
'expected_error_message' => 'A login and a password are required.',
],
'wrong_email' => [
'email' => 'wrongemail@example.com',
'password' => 'password',
'expected_error_message' => 'The account sign-in was incorrect or your account is disabled temporarily.'
. ' Please wait and try again later.',
],
'wrong_password' => [
'email' => 'customer@example.com',
'password' => 'wrongpassword',
'expected_error_message' => 'The account sign-in was incorrect or your account is disabled temporarily.'
. ' Please wait and try again later.',
],
];
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_confirmation_config_enable.php
* @magentoDataFixture Magento/Customer/_files/unconfirmed_customer.php
*
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @return void
*/
public function testLoginWithUnconfirmedPassword(): void
{
$email = 'unconfirmedcustomer@example.com';
$this->prepareRequest($email, 'Qwert12345');
$this->dispatch('customer/account/loginPost');
$this->assertEquals($email, $this->session->getUsername());
$message = __(
'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
$this->customerUrl->getEmailConfirmationUrl($this->session->getUsername())
);
$this->assertSessionMessages(
$this->equalTo([(string)$message]),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 0
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testLoginWithRedirectToDashboardDisabled(): void
{
$this->prepareRequest('customer@example.com', 'password');
$this->getRequest()->setParam(Url::REFERER_QUERY_PARAM_NAME, $this->urlEncoder->encode('test_redirect'));
$this->dispatch('customer/account/loginPost');
$this->assertTrue($this->session->isLoggedIn());
$this->assertRedirect($this->stringContains('test_redirect'));
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 0
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testLoginFailureWithRedirectToDashboardDisabled(): void
{
$this->prepareRequest('customer@example.com', 'incorrect');
$this->dispatch('customer/account/loginPost');
$this->assertFalse($this->session->isLoggedIn());
$this->assertRedirect($this->logicalAnd(
$this->stringContains('customer/account/login'),
$this->logicalnot($this->stringContains('referer'))
));
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 0
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testLoginToDashboardWithIncorrectReferrer(): void
{
$redirectUrl = 'https:support.magento.com';
$this->prepareRequest('customer@example.com', 'password');
$this->getRequest()->setParam(Url::REFERER_QUERY_PARAM_NAME, $this->urlEncoder->encode($redirectUrl));
$this->dispatch('customer/account/loginPost');
$this->assertTrue($this->session->isLoggedIn());
$this->assertRedirect($this->stringContains('customer/account/'));
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 1
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testLoginWithRedirectToDashboard(): void
{
$this->prepareRequest('customer@example.com', 'password');
$this->getRequest()->setParam(Url::REFERER_QUERY_PARAM_NAME, $this->urlEncoder->encode('test_redirect'));
$this->dispatch('customer/account/loginPost');
$this->assertTrue($this->session->isLoggedIn());
$this->assertRedirect($this->stringContains('customer/account/'));
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 1
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testNoFormKeyLoginPostAction(): void
{
$this->prepareRequest('customer@example.com', 'password');
$this->getRequest()->setPostValue('form_key', null);
$this->getRequest()->setParam(Url::REFERER_QUERY_PARAM_NAME, $this->urlEncoder->encode('test_redirect'));
$this->dispatch('customer/account/loginPost');
$this->assertFalse($this->session->isLoggedIn());
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo([new Phrase('Invalid Form Key. Please refresh the page.')]),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoConfigFixture current_store customer/startup/redirect_dashboard 1
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testVisitorForCustomerLoginPostAction(): void
{
$this->assertEmpty($this->generic->getVisitorData());
$this->prepareRequest('customer@example.com', 'password');
$this->dispatch('customer/account/loginPost');
$this->assertTrue($this->session->isLoggedIn());
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertNotEmpty($this->generic->getVisitorData()['visitor_id']);
$this->assertNotEmpty($this->generic->getVisitorData()['customer_id']);
}
/**
* Prepare request
*
* @param string|null $email
* @param string|null $password
* @return void
*/
private function prepareRequest(?string $email, ?string $password): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue([
'login' => [
'username' => $email,
'password' => $password,
],
]);
}
}
@@ -0,0 +1,780 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Http;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Store\Model\StoreManager;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\Request;
use Magento\TestFramework\TestCase\AbstractController;
use Magento\Theme\Controller\Result\MessagePlugin;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Test class for account controller
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AccountTest extends AbstractController
{
/**
* @var TransportBuilderMock
*/
private $transportBuilderMock;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilderMock = $this->_objectManager->get(TransportBuilderMock::class);
}
/**
* Login the user
*
* @param string $customerId Customer to mark as logged in for the session
* @return void
*/
protected function login($customerId)
{
/** @var Session $session */
$session = Bootstrap::getObjectManager()->get(Session::class);
$session->loginById($customerId);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testIndexAction()
{
$this->login(1);
$this->dispatch('customer/account/index');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('Green str, 67', $body);
}
/**
* Test sign up form displaying.
*/
public function testCreateAction()
{
$this->dispatch('customer/account/create');
$body = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression('~<input type="text"[^>]*id="firstname"~', $body);
$this->assertMatchesRegularExpression('~<input type="text"[^>]*id="lastname"~', $body);
$this->assertMatchesRegularExpression('~<input type="checkbox"[^>]*id="is_subscribed"~', $body);
$this->assertMatchesRegularExpression('~<input type="email"[^>]*id="email_address"~', $body);
$this->assertMatchesRegularExpression('~<input type="password"[^>]*id="password"~', $body);
$this->assertMatchesRegularExpression('~<input type="password"[^>]*id="password-confirmation"~', $body);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testLogoutAction()
{
$this->login(1);
$this->dispatch('customer/account/logout');
$this->assertRedirect($this->stringContains('customer/account/logoutSuccess'));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCreatepasswordActionWithDirectLink()
{
/** @var \Magento\Customer\Model\Customer $customer */
$customer = Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class)->load(1);
$token = Bootstrap::getObjectManager()->get(\Magento\Framework\Math\Random::class)
->getUniqueHash();
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$customer->save();
$this->getRequest()->setParam('token', $token);
$this->getRequest()->setParam('id', 1);
$this->dispatch('customer/account/createPassword');
$response = $this->getResponse();
$this->assertEquals(302, $response->getHttpResponseCode());
$text = $response->getBody();
$this->assertFalse((bool)preg_match('/' . $token . '/m', $text));
$this->assertRedirect(
$this->stringContains('customer/account/createpassword')
);
/** @var Session $customer */
$session = Bootstrap::getObjectManager()->get(Session::class);
$this->assertEquals($token, $session->getRpToken());
$this->assertStringNotContainsString($token, $response->getHeader('Location')->getFieldValue());
$this->assertCustomerConfirmationEquals(1, null);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCreatepasswordActionWithSession()
{
/** @var \Magento\Customer\Model\Customer $customer */
$customer = Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class)->load(1);
$token = Bootstrap::getObjectManager()->get(\Magento\Framework\Math\Random::class)
->getUniqueHash();
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$customer->save();
/** @var Session $customer */
$session = Bootstrap::getObjectManager()->get(Session::class);
$session->setRpToken($token);
$session->setRpCustomerId($customer->getId());
$this->dispatch('customer/account/createPassword');
$response = $this->getResponse();
$text = $response->getBody();
$this->assertTrue((bool)preg_match('/' . $token . '/m', $text));
$this->assertCustomerConfirmationEquals(1, null);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCreatepasswordActionInvalidToken()
{
/** @var \Magento\Customer\Model\Customer $customer */
$customer = Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class)->load(1);
$token = Bootstrap::getObjectManager()->get(\Magento\Framework\Math\Random::class)
->getUniqueHash();
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$customer->save();
$this->getRequest()->setParam('token', 'INVALIDTOKEN');
$this->getRequest()->setParam('id', $customer->getId());
$this->dispatch('customer/account/createPassword');
// should be redirected to forgotpassword page
$response = $this->getResponse();
$this->assertEquals(302, $response->getHttpResponseCode());
$this->assertStringContainsString(
'customer/account/forgotpassword',
$response->getHeader('Location')->getFieldValue()
);
$this->assertCustomerConfirmationEquals(1, 'confirmation');
}
/**
* @param int $customerId
* @param string|null $confirmation
*/
private function assertCustomerConfirmationEquals(int $customerId, string $confirmation = null)
{
/** @var \Magento\Customer\Model\Customer $customer */
$customer = Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class)->load($customerId);
$this->assertEquals($confirmation, $customer->getConfirmation());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testConfirmActionAlreadyActive()
{
/** @var \Magento\Customer\Model\Customer $customer */
$customer = Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class)->load(1);
$this->getRequest()->setParam('key', 'abc');
$this->getRequest()->setParam('id', $customer->getId());
$this->dispatch('customer/account/confirm');
$this->getResponse()->getBody();
}
/**
* @magentoDataFixture Magento/Customer/_files/inactive_customer.php
*/
public function testInactiveUserConfirmationAction()
{
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'email' => 'customer@needAconfirmation.com',
]
);
$this->dispatch('customer/account/confirmation');
$this->assertRedirect($this->stringContains('customer/account/index'));
$this->assertSessionMessages(
$this->equalTo(['Please check your email for confirmation key.']),
MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testActiveUserConfirmationAction()
{
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'email' => 'customer@example.com',
]
);
$this->dispatch('customer/account/confirmation');
$this->assertRedirect($this->stringContains('customer/account/index'));
$this->assertSessionMessages(
$this->equalTo(
[
'This email does not require confirmation.',
]
),
MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordPostNoEmail()
{
$this->getRequest()
->setParam('id', 1)
->setParam('token', '8ed8677e6c79e68b94e61658bd756ea5')
->setMethod('POST')
->setPostValue(
[
'password' => 'new-password',
'password_confirmation' => 'new-password',
]
);
$this->dispatch('customer/account/resetPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['&quot;email&quot; is required. Enter and try again.']),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_rp_token.php
* @magentoConfigFixture customer/password/reset_link_expiration_period 10
*/
public function testResetPasswordPostAction()
{
$this->getRequest()
->setQueryValue('id', 1)
->setQueryValue('token', '8ed8677e6c79e68b94e61658bd756ea5')
->setMethod('POST')
->setPostValue(
[
'password' => 'new-Password1',
'password_confirmation' => 'new-Password1',
]
);
$this->dispatch('customer/account/resetPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/login'));
$this->assertSessionMessages(
$this->equalTo(['You updated your password.']),
MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testEditAction()
{
$this->login(1);
$this->dispatch('customer/account/edit');
$body = $this->getResponse()->getBody();
$this->assertEquals(200, $this->getResponse()->getHttpResponseCode(), $body);
$this->assertStringContainsString('<div class="field field-name-firstname required">', $body);
// Verify the password check box is not checked
$checkboxXpath = '//input[@type="checkbox"][@name="change_password"][@id="change-password"][not (@checked)]' .
'[@data-role="change-password"][@value="1"][@title="Change Password"][@class="checkbox"]';
$this->assertEquals(1, Xpath::getElementsCountForXpath($checkboxXpath, $body));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testChangePasswordEditAction(): void
{
$this->login(1);
$this->dispatch('customer/account/edit/changepass/1');
$body = $this->getResponse()->getBody();
$this->assertEquals(200, $this->getResponse()->getHttpResponseCode(), $body);
$this->assertStringContainsString('<div class="field field-name-firstname required">', $body);
// Verify the password check box is checked
$checkboxXpath = '//input[@type="checkbox"][@name="change_password"][@id="change-password"]' .
'[@data-role="change-password"][@value="1"][@title="Change Password"][@checked="checked"]' .
'[@class="checkbox"]';
$this->assertEquals(1, Xpath::getElementsCountForXpath($checkboxXpath, $body));
}
/**
* @codingStandardsIgnoreStart
* @magentoConfigFixture current_store customer/account_information/change_email_template customer_account_information_change_email_and_password_template
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoDataFixture Magento/Customer/_files/customer.php
* @codingStandardsIgnoreEnd
*/
public function testEditPostAction()
{
/** @var $customerRepository CustomerRepositoryInterface */
$customerRepository = Bootstrap::getObjectManager()
->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->getById(1);
$this->assertEquals('John', $customer->getFirstname());
$this->assertEquals('Smith', $customer->getLastname());
$this->assertEquals('customer@example.com', $customer->getEmail());
$this->login(1);
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(),
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'johndoe@email.com',
'change_email' => 1,
'current_password' => 'password'
]
);
$this->dispatch('customer/account/editPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['You saved the account information.']),
MessageInterface::TYPE_SUCCESS
);
$customer = $customerRepository->getById(1);
$this->assertEquals('John', $customer->getFirstname());
$this->assertEquals('Doe', $customer->getLastname());
$this->assertEquals('johndoe@email.com', $customer->getEmail());
}
/**
* @codingStandardsIgnoreStart
* @magentoConfigFixture current_store customer/account_information/change_email_and_password_template customer_account_information_change_email_and_password_template
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoDataFixture Magento/Customer/_files/customer.php
* @codingStandardsIgnoreEnd
*/
public function testChangePasswordEditPostAction()
{
/** @var $customerRepository CustomerRepositoryInterface */
$customerRepository = Bootstrap::getObjectManager()
->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->getById(1);
$this->assertEquals('John', $customer->getFirstname());
$this->assertEquals('Smith', $customer->getLastname());
$this->assertEquals('customer@example.com', $customer->getEmail());
$this->login(1);
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(),
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'johndoe@email.com',
'change_password' => 1,
'change_email' => 1,
'current_password' => 'password',
'password' => 'new-Password1',
'password_confirmation' => 'new-Password1',
]
);
$this->dispatch('customer/account/editPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(['You saved the account information.']),
MessageInterface::TYPE_SUCCESS
);
$customer = $customerRepository->getById(1);
$this->assertEquals('John', $customer->getFirstname());
$this->assertEquals('Doe', $customer->getLastname());
$this->assertEquals('johndoe@email.com', $customer->getEmail());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testMissingDataEditPostAction()
{
$this->login(1);
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(),
'firstname' => 'John',
'lastname' => 'Doe',
'change_email' => 1,
'current_password' => 'password',
'email' => 'bad-email',
]
);
$this->dispatch('customer/account/editPost');
$this->assertRedirect($this->stringContains('customer/account/edit/'));
$this->assertSessionMessages(
$this->equalTo(['&quot;Email&quot; is not a valid email address.']),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testWrongPasswordEditPostAction()
{
$this->login(1);
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(),
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'johndoe@email.com',
'change_password' => 1,
'current_password' => 'wrong-password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
]
);
$this->dispatch('customer/account/editPost');
$this->assertRedirect($this->stringContains('customer/account/edit/'));
// Not sure if its the most secure message. Not changing the behavior for now in the new AccountManagement APIs.
$this->assertSessionMessages(
$this->equalTo(["The password doesn&#039;t match this account. Verify the password and try again."]),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testWrongConfirmationEditPostAction()
{
$this->login(1);
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(),
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'johndoe@email.com',
'change_password' => 1,
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'new-password-no-match',
]
);
$this->dispatch('customer/account/editPost');
$this->assertRedirect($this->stringContains('customer/account/edit/'));
$this->assertSessionMessages(
$this->equalTo(['Password confirmation doesn&#039;t match entered password.']),
MessageInterface::TYPE_ERROR
);
}
/**
* Test that confirmation email address displays special characters correctly.
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Customer/_files/customer_confirmation_email_address_with_special_chars.php
*
* @return void
*/
public function testConfirmationEmailWithSpecialCharacters(): void
{
$email = 'customer+confirmation@example.com';
$this->dispatch('customer/account/confirmation/email/customer%2Bconfirmation%40email.com');
$this->getRequest()->setPostValue('email', $email);
$this->dispatch('customer/account/confirmation/email/customer%2Bconfirmation%40email.com');
$this->assertRedirect($this->stringContains('customer/account/index'));
$this->assertSessionMessages(
$this->equalTo(['Please check your email for confirmation key.']),
MessageInterface::TYPE_SUCCESS
);
/** @var $message \Magento\Framework\Mail\Message */
$message = $this->transportBuilderMock->getSentMessage();
$rawMessage = $message->getRawMessage();
/** @var \Laminas\Mime\Part $messageBodyPart */
$messageBodyParts = $message->getBody()->getParts();
$messageBodyPart = reset($messageBodyParts);
$messageEncoding = $messageBodyPart->getCharset();
$name = 'John Smith';
if (strtoupper($messageEncoding) !== 'ASCII') {
$name = \Laminas\Mail\Header\HeaderWrap::mimeEncodeValue($name, $messageEncoding);
}
$nameEmail = sprintf('%s <%s>', $name, $email);
$this->assertStringContainsString('To: ' . $nameEmail, $rawMessage);
$content = $messageBodyPart->getRawContent();
$confirmationUrl = $this->getConfirmationUrlFromMessageContent($content);
$this->setRequestInfo($confirmationUrl, 'confirm');
$this->clearCookieMessagesList();
$this->dispatch($confirmationUrl);
$this->assertRedirect($this->stringContains('customer/account/index'));
$this->assertSessionMessages(
$this->equalTo(['Thank you for registering with Main Website Store.']),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Check that Customer which change email can't log in with old email.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @return void
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\State\InputMismatchException
*/
public function testResetPasswordWhenEmailChanged(): void
{
$email = 'customer@example.com';
$newEmail = 'new_customer@example.com';
/* Reset password and check mail with token */
$this->getRequest()->setPostValue(['email' => $email]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSessionMessages(
$this->equalTo(
[
"If there is an account associated with {$email} you will receive an email with a link "
. "to reset your password."
]
),
MessageInterface::TYPE_SUCCESS
);
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$customerData = $customerRegistry->retrieveByEmail($email);
$token = $customerData->getRpToken();
$customerId = $customerData->getId();
$this->assertForgotPasswordEmailContent($token, $customerId);
/* Set new email */
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->_objectManager->create(CustomerRepositoryInterface::class);
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $customerRepository->getById($customerData->getId());
$customer->setEmail($newEmail);
$customerRepository->save($customer);
$this->resetRequest();
/* Goes through the link in a mail */
$this->getRequest()
->setParam('token', $token)
->setParam('id', $customerData->getId());
$this->dispatch('customer/account/createPassword');
$this->assertRedirect($this->stringContains('customer/account/forgotpassword'));
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
MessageInterface::TYPE_ERROR
);
/* Trying to log in with old email */
$this->resetRequest();
$this->clearCookieMessagesList();
$customerRegistry->removeByEmail($email);
$this->dispatchLoginPostAction($email, 'password');
$this->assertSessionMessages(
$this->equalTo(
[
'The account sign-in was incorrect or your account is disabled temporarily. '
. 'Please wait and try again later.'
]
),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('customer/account/login'));
/** @var Session $session */
$session = $this->_objectManager->get(Session::class);
$this->assertFalse($session->isLoggedIn());
/* Trying to log in with correct(new) email */
$this->resetRequest();
$this->dispatchLoginPostAction($newEmail, 'password');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertTrue($session->isLoggedIn());
$session->logout();
}
/**
* Set needed parameters and dispatch Customer loginPost action.
*
* @param string $email
* @param string $password
* @return void
*/
private function dispatchLoginPostAction(string $email, string $password): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'login' => [
'username' => $email,
'password' => $password,
],
]
);
$this->dispatch('customer/account/loginPost');
}
/**
* Check that 'Forgot password' email contains correct data.
*
* @param string $token
* @return void
*/
private function assertForgotPasswordEmailContent(string $token, int $customerId): void
{
$message = $this->transportBuilderMock->getSentMessage();
//phpcs:ignore
$pattern = "/<a.+customer\/account\/createPassword\/\?id={$customerId}&amp;token={$token}.+Set\s+a\s+New\s+Password<\/a\>/";
$rawMessage = $message->getBody()->getParts()[0]->getRawContent();
$messageConstraint = $this->logicalAnd(
new StringContains('There was recently a request to change the password for your account.'),
$this->matchesRegularExpression($pattern)
);
$this->assertThat($rawMessage, $messageConstraint);
}
/**
* @inheritDoc
*/
protected function resetRequest(): void
{
$this->_objectManager->removeSharedInstance(Http::class);
$this->_objectManager->removeSharedInstance(Request::class);
parent::resetRequest();
}
/**
* Add new request info (request uri, path info, action name).
*
* @param string $uri
* @param string $actionName
* @return void
*/
private function setRequestInfo(string $uri, string $actionName): void
{
$this->getRequest()
->setRequestUri($uri)
->setPathInfo()
->setActionName($actionName);
}
/**
* Clear cookie messages list.
*
* @return void
*/
private function clearCookieMessagesList(): void
{
$cookieManager = $this->_objectManager->get(CookieManagerInterface::class);
$jsonSerializer = $this->_objectManager->get(Json::class);
$cookieManager->setPublicCookie(
MessagePlugin::MESSAGES_COOKIES_NAME,
$jsonSerializer->serialize([])
);
}
/**
* Get confirmation URL from message content.
*
* @param string $content
* @return string
*/
private function getConfirmationUrlFromMessageContent(string $content): string
{
$confirmationUrl = '';
if (preg_match('<a\s*href="(?<url>.*?)".*>', $content, $matches)) {
$confirmationUrl = $matches['url'];
$confirmationUrl = str_replace('http://localhost/index.php/', '', $confirmationUrl);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$confirmationUrl = html_entity_decode($confirmationUrl);
}
return $confirmationUrl;
}
}
@@ -0,0 +1,217 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Address\Delete;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test cases related to check that customer address correctly deleted on frontend
* or wasn't deleted and proper error message appears.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*
* @see \Magento\Customer\Controller\Address\Delete::execute
*/
class DeleteAddressTest extends AbstractController
{
/**
* @var Escaper
*/
private $escaper;
/**
* @var Session
*/
private $customerSession;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->customerSession = $this->_objectManager->get(Session::class);
$this->addressRepository = $this->_objectManager->get(AddressRepositoryInterface::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
}
/**
* Assert that customer address deleted successfully.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @return void
*/
public function testSuccessDeleteExistCustomerAddress(): void
{
$customer = $this->customerRepository->get('customer@example.com');
$customerAddresses = $customer->getAddresses() ?? [];
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $currentCustomerAddress */
$currentCustomerAddress = reset($customerAddresses);
$this->customerSession->setCustomerId($customer->getId());
$this->performAddressDeleteRequest((int)$currentCustomerAddress->getId());
$this->checkRequestPerformedSuccessfully();
$customer = $this->customerRepository->get('customer@example.com');
$this->assertCount(0, $customer->getAddresses() ?? []);
try {
$this->addressRepository->getById((int)$currentCustomerAddress->getId());
$this->fail('Customer address is not deleted.');
} catch (LocalizedException $e) {
//Do nothing, this block mean that address deleted successfully from DB.
}
}
/**
* Check that customer address will not be deleted if we don't pass address ID parameter.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @return void
*/
public function testDeleteWithoutParam(): void
{
$customer = $this->customerRepository->get('customer@example.com');
$customerAddresses = $customer->getAddresses() ?? [];
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $currentCustomerAddress */
$currentCustomerAddress = reset($customerAddresses);
$this->customerSession->setCustomerId($customer->getId());
$this->performAddressDeleteRequest();
$this->assertRedirect($this->stringContains('customer/address/index'));
$customer = $this->customerRepository->get('customer@example.com');
$this->assertCount(1, $customer->getAddresses() ?? []);
$this->checkAddressWasntDeleted((int)$currentCustomerAddress->getId());
}
/**
* Check that customer address will not be deleted if customer id in address and in session are not equals.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_with_uk_address.php
*
* @return void
*/
public function testDeleteDifferentCustomerAddress(): void
{
$firstCustomer = $this->customerRepository->get('customer@example.com');
$customerAddresses = $firstCustomer->getAddresses() ?? [];
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $currentCustomerAddress */
$currentCustomerAddress = reset($customerAddresses);
$this->customerSession->setCustomerId('1');
$secondCustomer = $this->customerRepository->get('customer_uk_address@test.com');
$secondCustomerAddresses = $secondCustomer->getAddresses() ?? [];
/** @var AddressInterface $secondCustomerAddress */
$secondCustomerAddress = reset($secondCustomerAddresses);
$this->performAddressDeleteRequest((int)$secondCustomerAddress->getId());
$this->checkRequestPerformedWithError(true);
$firstCustomer = $this->customerRepository->get('customer@example.com');
$this->assertCount(1, $firstCustomer->getAddresses() ?? []);
$this->checkAddressWasntDeleted((int)$currentCustomerAddress->getId());
}
/**
* Check that error message appear if we try to delete non-exits address.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testDeleteNonExistAddress(): void
{
$customer = $this->customerRepository->get('customer@example.com');
$this->customerSession->setCustomerId($customer->getId());
$this->performAddressDeleteRequest(999);
$this->checkRequestPerformedWithError();
}
/**
* Perform delete request by provided address id.
*
* @param int|null $processAddressId
* @return void
*/
private function performAddressDeleteRequest(?int $processAddressId = null): void
{
$this->getRequest()->setMethod(Http::METHOD_POST);
if (null !== $processAddressId) {
$this->getRequest()->setPostValue(['id' => $processAddressId]);
}
$this->dispatch('customer/address/delete');
}
/**
* Check that delete address request performed successfully
* (proper success message and redirect to customer/address/index are appear).
*
* @return void
*/
private function checkRequestPerformedSuccessfully(): void
{
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__('You deleted the address.')]),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Check that delete address request performed with error.
* (proper error messages and redirect to customer/address/edit are appear).
*
* @param bool $isNeedEscapeMessage
* @return void
*/
private function checkRequestPerformedWithError(bool $isNeedEscapeMessage = false): void
{
$message = (string)__("We can't delete the address right now.");
if ($isNeedEscapeMessage) {
$message = $this->escaper->escapeHtml($message);
}
$this->assertSessionMessages($this->containsEqual($message), MessageInterface::TYPE_ERROR);
}
/**
* Assert that customer address wasn't deleted.
*
* @param int $addressId
* @return void
*/
private function checkAddressWasntDeleted(int $addressId): void
{
try {
$this->addressRepository->getById($addressId);
} catch (LocalizedException $e) {
$this->fail('Expects that customer address will not be deleted.');
}
}
}
@@ -0,0 +1,391 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Address\FormPost;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\RegionInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Directory\Model\GetRegionIdByName;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test cases related to check that customer address correctly created from
* customer account page on frontend or wasn't create and proper error message appears.
*
* @magentoDataFixture Magento/Customer/_files/customer_no_address.php
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*
* @see \Magento\Customer\Controller\Address\FormPost::execute
*/
class CreateAddressTest extends AbstractController
{
/**
* POST static data for create customer address via controller on frontend.
*/
private const STATIC_POST_ADDRESS_DATA = [
AddressInterface::TELEPHONE => '+380505282812',
AddressInterface::POSTCODE => 75477,
AddressInterface::COUNTRY_ID => 'US',
'custom_region_name' => 'Alabama',
AddressInterface::CITY => 'CityM',
AddressInterface::STREET => [
'Green str, 67',
],
AddressInterface::FIRSTNAME => 'John',
AddressInterface::LASTNAME => 'Smith',
];
/**
* @var Escaper
*/
private $escaper;
/**
* @var Session
*/
private $customerSession;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var GetRegionIdByName
*/
private $getRegionIdByName;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->customerSession = $this->_objectManager->get(Session::class);
$this->customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$this->getRegionIdByName = $this->_objectManager->get(GetRegionIdByName::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->customerSession->setCustomerId('5');
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerSession->setCustomerId(null);
$this->customerRegistry->removeByEmail('customer5@example.com');
parent::tearDown();
}
/**
* Assert that default or non-default customer address successfully created via controller on frontend.
*
* @dataProvider postDataForSuccessCreateDefaultAddressDataProvider
*
* @param array $postData
* @param bool $isShippingDefault
* @param bool $isBillingDefault
* @return void
*/
public function testAddressSuccessfullyCreatedAsDefaultForCustomer(
array $postData,
bool $isShippingDefault,
bool $isBillingDefault
): void {
$customer = $this->customerRepository->get('customer5@example.com');
$this->assertNull($customer->getDefaultShipping(), 'Customer already have default shipping address');
$this->assertNull($customer->getDefaultBilling(), 'Customer already have default billing address');
$this->assertEmpty($customer->getAddresses(), 'Customer already has address');
$this->performRequestWithData($postData);
$this->checkRequestPerformedSuccessfully();
$customer = $this->customerRepository->get('customer5@example.com');
$customerAddresses = $customer->getAddresses();
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $address */
$address = reset($customerAddresses);
$expectedShippingId = $isShippingDefault ? $address->getId() : null;
$expectedBillingId = $isBillingDefault ? $address->getId() : null;
$this->assertEquals($expectedShippingId, $customer->getDefaultShipping());
$this->assertEquals($expectedBillingId, $customer->getDefaultBilling());
}
/**
* Data provider which contain proper POST data for create default or non-default customer address.
*
* @return array
*/
public function postDataForSuccessCreateDefaultAddressDataProvider(): array
{
return [
'any_addresses_are_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 0, AddressInterface::DEFAULT_BILLING => 0]
),
false,
false,
],
'shipping_address_is_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 1, AddressInterface::DEFAULT_BILLING => 0]
),
true,
false,
],
'billing_address_is_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 0, AddressInterface::DEFAULT_BILLING => 1]
),
false,
true,
],
'all_addresses_are_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 1, AddressInterface::DEFAULT_BILLING => 1]
),
true,
true,
],
];
}
/**
* Assert that customer address successfully created via controller on frontend.
*
* @dataProvider postDataForSuccessCreateAddressDataProvider
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testAddressSuccessfullyCreatedForCustomer(array $postData, array $expectedData): void
{
if (isset($expectedData['custom_region_name'])) {
$expectedData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute(
$expectedData['custom_region_name'],
$expectedData[AddressInterface::COUNTRY_ID]
);
unset($expectedData['custom_region_name']);
}
$this->performRequestWithData($postData);
$this->checkRequestPerformedSuccessfully();
$customer = $this->customerRepository->get('customer5@example.com');
$customerAddresses = $customer->getAddresses();
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $address */
$address = reset($customerAddresses);
$createdAddressData = $address->__toArray();
foreach ($expectedData as $fieldCode => $expectedValue) {
$this->assertArrayHasKey($fieldCode, $createdAddressData, "Field $fieldCode wasn't found.");
$this->assertEquals($expectedValue, $createdAddressData[$fieldCode]);
}
}
/**
* Data provider which contain proper POST data for create customer address.
*
* @return array
*/
public function postDataForSuccessCreateAddressDataProvider(): array
{
return [
'required_fields_valid_data' => [
self::STATIC_POST_ADDRESS_DATA,
[
AddressInterface::TELEPHONE => '+380505282812',
AddressInterface::COUNTRY_ID => 'US',
AddressInterface::POSTCODE => 75477,
'custom_region_name' => 'Alabama',
AddressInterface::FIRSTNAME => 'John',
AddressInterface::LASTNAME => 'Smith',
AddressInterface::STREET => ['Green str, 67'],
AddressInterface::CITY => 'CityM',
],
],
'required_field_empty_postcode_for_uk' => [
array_replace(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::POSTCODE => '', AddressInterface::COUNTRY_ID => 'GB']
),
[
AddressInterface::COUNTRY_ID => 'GB',
AddressInterface::POSTCODE => null,
],
],
'required_field_empty_region_id_for_ua' => [
array_replace(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::REGION_ID => '', AddressInterface::COUNTRY_ID => 'UA']
),
[
AddressInterface::COUNTRY_ID => 'UA',
AddressInterface::REGION => [
RegionInterface::REGION => null,
RegionInterface::REGION_CODE => null,
RegionInterface::REGION_ID => 0,
],
],
],
'required_field_street_as_array' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => ['', 'Green str, 67']]),
[AddressInterface::STREET => ['Green str, 67']],
],
'field_company_name' => [
array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::COMPANY => 'My company']),
[AddressInterface::COMPANY => 'My company'],
],
'field_vat_number' => [
array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::VAT_ID => 'My VAT number']),
[AddressInterface::VAT_ID => 'My VAT number'],
],
];
}
/**
* Assert that customer address wasn't created via controller on frontend
* when POST data broken.
*
* @dataProvider postDataForCreateAddressWithErrorDataProvider
*
* @param array $postData
* @param array $expectedSessionMessages
* @return void
*/
public function testAddressWasntCreatedForCustomer(array $postData, array $expectedSessionMessages): void
{
$this->performRequestWithData($postData);
$this->checkRequestPerformedWithInputValidationErrors($expectedSessionMessages);
}
/**
* Data provider which contain broken POST data for create customer address with error.
*
* @return array
*/
public function postDataForCreateAddressWithErrorDataProvider(): array
{
return [
'empty_post_data' => [
[],
[
'One or more input exceptions have occurred.',
'"firstname" is required. Enter and try again.',
'"lastname" is required. Enter and try again.',
'"street" is required. Enter and try again.',
'"city" is required. Enter and try again.',
'"telephone" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
'"countryId" is required. Enter and try again.',
]
],
'required_field_empty_telephone' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::TELEPHONE => '']),
['"telephone" is required. Enter and try again.'],
],
'required_field_empty_postcode_for_us' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::POSTCODE => '']),
['"postcode" is required. Enter and try again.'],
],
// TODO: Uncomment this variation after fix issue https://jira.corp.magento.com/browse/MC-31031
// 'required_field_empty_region_id_for_us' => [
// array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::REGION_ID => '']),
// ['"regionId" is required. Enter and try again.'],
// ],
'required_field_empty_firstname' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::FIRSTNAME => '']),
['"firstname" is required. Enter and try again.'],
],
'required_field_empty_lastname' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::LASTNAME => '']),
['"lastname" is required. Enter and try again.'],
],
'required_field_empty_street_as_string' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => '']),
['"street" is required. Enter and try again.'],
],
'required_field_empty_street_as_array' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => []]),
['"street" is required. Enter and try again.'],
],
'required_field_empty_city' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::CITY => '']),
['"city" is required. Enter and try again.'],
],
];
}
/**
* Perform request with provided POST data.
*
* @param array $postData
* @return void
*/
private function performRequestWithData(array $postData): void
{
if (isset($postData['custom_region_name'])) {
$postData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute(
$postData['custom_region_name'],
$postData[AddressInterface::COUNTRY_ID]
);
unset($postData['custom_region_name']);
}
$this->getRequest()->setPostValue($postData)->setMethod(Http::METHOD_POST);
$this->dispatch('customer/address/formPost');
}
/**
* Check that save address request performed successfully
* (proper success message and redirect to customer/address/index are appear).
*
* @return void
*/
private function checkRequestPerformedSuccessfully(): void
{
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the address.')]),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Check that save address request performed with input validation errors
* (proper error messages and redirect to customer/address/edit are appear).
*
* @param array $expectedSessionMessages
* @return void
*/
private function checkRequestPerformedWithInputValidationErrors(array $expectedSessionMessages): void
{
$this->assertRedirect($this->stringContains('customer/address/edit'));
foreach ($expectedSessionMessages as $expectedMessage) {
$this->assertSessionMessages(
$this->containsEqual($this->escaper->escapeHtml((string)__($expectedMessage))),
MessageInterface::TYPE_ERROR
);
}
}
}
@@ -0,0 +1,403 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Address\FormPost;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\RegionInterface;
use Magento\Customer\Model\AddressRegistry;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Directory\Model\GetRegionIdByName;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test cases related to check that customer address correctly updated from
* customer account page on frontend or wasn't updated and proper error message appears.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*
* @see \Magento\Customer\Controller\Address\FormPost::execute
*/
class UpdateAddressTest extends AbstractController
{
/**
* POST static data for update customer address via controller on frontend.
*/
private const STATIC_POST_ADDRESS_DATA = [
AddressInterface::TELEPHONE => 9548642,
AddressInterface::POSTCODE => 95556,
AddressInterface::COUNTRY_ID => 'US',
'custom_region_name' => 'Arkansas',
AddressInterface::CITY => 'Mukachevo',
AddressInterface::STREET => [
'Yellow str, 228',
],
AddressInterface::FIRSTNAME => 'Foma',
AddressInterface::LASTNAME => 'Kiniaev',
];
/**
* @var Escaper
*/
private $escaper;
/**
* @var Session
*/
private $customerSession;
/**
* @var AddressRegistry
*/
private $addressRegistry;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var GetRegionIdByName
*/
private $getRegionIdByName;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var array
*/
private $processedAddressesIds = [];
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->customerSession = $this->_objectManager->get(Session::class);
$this->addressRegistry = $this->_objectManager->get(AddressRegistry::class);
$this->customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$this->getRegionIdByName = $this->_objectManager->get(GetRegionIdByName::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->customerSession->setCustomerId('1');
$this->processedAddressesIds[] = 1;
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerSession->setCustomerId(null);
$this->customerRegistry->removeByEmail('customer@example.com');
foreach ($this->processedAddressesIds as $addressesId) {
$this->addressRegistry->remove($addressesId);
}
parent::tearDown();
}
/**
* Assert that default customer address successfully changed via controller on frontend.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*
* @dataProvider postDataForSuccessCreateDefaultAddressDataProvider
*
* @param array $postData
* @param int $expectedShippingId
* @param int $expectedBillingId
* @return void
*/
public function testAddressSuccessfullyCreatedAsDefaultForCustomer(
array $postData,
int $expectedShippingId,
int $expectedBillingId
): void {
$this->processedAddressesIds = [1, 2];
$customer = $this->customerRepository->get('customer@example.com');
$this->assertEquals(1, $customer->getDefaultShipping(), "Customer doesn't have shipping address");
$this->assertEquals(1, $customer->getDefaultBilling(), "Customer doesn't have billing address");
$this->performRequestWithData($postData, 2);
$this->checkRequestPerformedSuccessfully();
$customer = $this->customerRepository->get('customer@example.com');
$this->assertEquals($expectedShippingId, $customer->getDefaultShipping());
$this->assertEquals($expectedBillingId, $customer->getDefaultBilling());
}
/**
* Data provider which contain proper POST data for change default customer address.
*
* @return array
*/
public function postDataForSuccessCreateDefaultAddressDataProvider(): array
{
return [
'any_addresses_are_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 2, AddressInterface::DEFAULT_BILLING => 2]
),
2,
2,
],
'shipping_address_is_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_BILLING => 2]
),
1,
2,
],
'billing_address_is_default' => [
array_merge(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::DEFAULT_SHIPPING => 2]
),
2,
1,
],
];
}
/**
* Assert that customer address successfully updated via controller on frontend.
*
* @dataProvider postDataForSuccessUpdateAddressDataProvider
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testAddressSuccessfullyUpdatedForCustomer(array $postData, array $expectedData): void
{
if (isset($expectedData['custom_region_name'])) {
$expectedData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute(
$expectedData['custom_region_name'],
$expectedData[AddressInterface::COUNTRY_ID]
);
unset($expectedData['custom_region_name']);
}
$this->performRequestWithData($postData, 1);
$this->checkRequestPerformedSuccessfully();
$customer = $this->customerRepository->get('customer@example.com');
$customerAddresses = $customer->getAddresses();
$this->assertCount(1, $customerAddresses);
/** @var AddressInterface $address */
$address = reset($customerAddresses);
$createdAddressData = $address->__toArray();
foreach ($expectedData as $fieldCode => $expectedValue) {
if (null === $expectedValue) {
$this->assertArrayNotHasKey($fieldCode, $createdAddressData);
continue;
}
$this->assertArrayHasKey($fieldCode, $createdAddressData, "Field $fieldCode wasn't found.");
$this->assertEquals($expectedValue, $createdAddressData[$fieldCode]);
}
}
/**
* Data provider which contain proper POST data for update customer address.
*
* @return array
*/
public function postDataForSuccessUpdateAddressDataProvider(): array
{
return [
'required_fields_valid_data' => [
self::STATIC_POST_ADDRESS_DATA,
[
AddressInterface::TELEPHONE => 9548642,
AddressInterface::COUNTRY_ID => 'US',
AddressInterface::POSTCODE => 95556,
'custom_region_name' => 'Arkansas',
AddressInterface::FIRSTNAME => 'Foma',
AddressInterface::LASTNAME => 'Kiniaev',
AddressInterface::STREET => ['Yellow str, 228'],
AddressInterface::CITY => 'Mukachevo',
],
],
'required_field_empty_postcode_for_uk' => [
array_replace(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::POSTCODE => '', AddressInterface::COUNTRY_ID => 'GB']
),
[
AddressInterface::COUNTRY_ID => 'GB',
AddressInterface::POSTCODE => null,
],
],
'required_field_empty_region_id_for_ua' => [
array_replace(
self::STATIC_POST_ADDRESS_DATA,
[AddressInterface::REGION_ID => '', AddressInterface::COUNTRY_ID => 'UA']
),
[
AddressInterface::COUNTRY_ID => 'UA',
AddressInterface::REGION => [
RegionInterface::REGION => null,
RegionInterface::REGION_CODE => null,
RegionInterface::REGION_ID => 0,
],
],
],
'required_field_street_as_array' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => ['', 'Green str, 67']]),
[AddressInterface::STREET => ['Green str, 67']],
],
'field_company_name' => [
array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::COMPANY => 'My company']),
[AddressInterface::COMPANY => 'My company'],
],
'field_vat_number' => [
array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::VAT_ID => 'My VAT number']),
[AddressInterface::VAT_ID => 'My VAT number'],
],
];
}
/**
* Assert that customer address wasn't updated via controller on frontend
* when POST data broken.
*
* @dataProvider postDataForUpdateAddressWithErrorDataProvider
*
* @param array $postData
* @param array $expectedSessionMessages
* @return void
*/
public function testAddressWasntUpdatedForCustomer(array $postData, array $expectedSessionMessages): void
{
$this->performRequestWithData($postData, 1);
$this->checkRequestPerformedWithInputValidationErrors($expectedSessionMessages);
}
/**
* Data provider which contain broken POST data for update customer address with error.
*
* @return array
*/
public function postDataForUpdateAddressWithErrorDataProvider(): array
{
return [
'empty_post_data' => [
[],
[
'One or more input exceptions have occurred.',
'"firstname" is required. Enter and try again.',
'"lastname" is required. Enter and try again.',
'"street" is required. Enter and try again.',
'"city" is required. Enter and try again.',
'"telephone" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
'"countryId" is required. Enter and try again.',
]
],
'required_field_empty_telephone' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::TELEPHONE => '']),
['"telephone" is required. Enter and try again.'],
],
'required_field_empty_postcode_for_us' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::POSTCODE => '']),
['"postcode" is required. Enter and try again.'],
],
// TODO: Uncomment this variation after fix issue https://jira.corp.magento.com/browse/MC-31031
// 'required_field_empty_region_id_for_us' => [
// array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::REGION_ID => '']),
// ['"regionId" is required. Enter and try again.'],
// ],
'required_field_empty_firstname' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::FIRSTNAME => '']),
['"firstname" is required. Enter and try again.'],
],
'required_field_empty_lastname' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::LASTNAME => '']),
['"lastname" is required. Enter and try again.'],
],
'required_field_empty_street_as_string' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => '']),
['"street" is required. Enter and try again.'],
],
'required_field_empty_street_as_array' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => []]),
['"street" is required. Enter and try again.'],
],
'required_field_empty_city' => [
array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::CITY => '']),
['"city" is required. Enter and try again.'],
],
];
}
/**
* Perform request with provided POST data.
*
* @param array $postData
* @param int $processAddressId
* @return void
*/
private function performRequestWithData(array $postData, int $processAddressId): void
{
$postData[AddressInterface::ID] = $processAddressId;
if (isset($postData['custom_region_name'])) {
$postData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute(
$postData['custom_region_name'],
$postData[AddressInterface::COUNTRY_ID]
);
unset($postData['custom_region_name']);
}
$this->getRequest()->setPostValue($postData)->setMethod(Http::METHOD_POST);
$this->dispatch('customer/address/formPost');
}
/**
* Check that save address request performed successfully
* (proper success message and redirect to customer/address/index are appear).
*
* @return void
*/
private function checkRequestPerformedSuccessfully(): void
{
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the address.')]),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Check that save address request performed with input validation errors
* (proper error messages and redirect to customer/address/edit are appear).
*
* @param array $expectedSessionMessages
* @return void
*/
private function checkRequestPerformedWithInputValidationErrors(array $expectedSessionMessages): void
{
$this->assertRedirect($this->stringContains('customer/address/edit'));
foreach ($expectedSessionMessages as $expectedMessage) {
$this->assertSessionMessages(
$this->containsEqual($this->escaper->escapeHtml((string)__($expectedMessage))),
MessageInterface::TYPE_ERROR
);
}
}
}
@@ -0,0 +1,200 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Data\Form\FormKey;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\Request\Http as HttpRequest;
class AddressTest extends \Magento\TestFramework\TestCase\AbstractController
{
/** @var AccountManagementInterface */
private $accountManagement;
/** @var FormKey */
private $formKey;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$logger = $this->createMock(\Psr\Log\LoggerInterface::class);
$session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Customer\Model\Session::class,
[$logger]
);
$this->accountManagement = Bootstrap::getObjectManager()->create(AccountManagementInterface::class);
$this->formKey = Bootstrap::getObjectManager()->create(FormKey::class);
$customer = $this->accountManagement->authenticate('customer@example.com', 'password');
$session->setCustomerDataAsLoggedIn($customer);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testIndexAction()
{
$this->dispatch('customer/address/index');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('Default Billing Address', $body);
$this->assertStringContainsString('Default Shipping Address', $body);
$this->assertStringContainsString('Green str, 67', $body);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testFormAction()
{
$this->dispatch('customer/address/edit');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('value="John"', $body);
$this->assertStringContainsString('value="Smith"', $body);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testFormPostAction()
{
$this->getRequest()->setParam(
'id',
2
)->setMethod(
'POST'
)->setPostValue(
[
'form_key' => $this->_objectManager->get(\Magento\Framework\Data\Form\FormKey::class)->getFormKey(),
'firstname' => 'James',
'lastname' => 'Bond',
'company' => 'Magento Commerce Inc.',
'telephone' => '1112223333',
'fax' => '2223334444',
'street' => ['1234 Monterey Rd', 'Apt 13'],
'city' => 'Kyiv',
'region' => 'Kiev',
'postcode' => '55555',
'country_id' => 'UA',
'success_url' => '',
'error_url' => '',
'default_billing' => true,
'default_shipping' => true,
]
);
// we are overwriting the address coming from the fixture
$this->dispatch('customer/address/formPost');
$this->getCustomerRegistry()->remove(1);
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo(['You saved the address.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$address = $this->accountManagement->getDefaultBillingAddress(1);
$this->assertEquals('UA', $address->getCountryId());
$this->assertEquals('Kyiv', $address->getCity());
$this->assertEquals('Kiev', $address->getRegion()->getRegion());
$this->assertTrue($address->isDefaultBilling());
$this->assertTrue($address->isDefaultShipping());
}
/**
* @return CustomerRegistry
*/
private function getCustomerRegistry()
{
return $this->_objectManager->get(CustomerRegistry::class);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testFailedFormPostAction()
{
$this->getRequest()->setParam(
'id',
1
)->setMethod(
'POST'
)->setPostValue(
[
'form_key' => $this->_objectManager->get(\Magento\Framework\Data\Form\FormKey::class)->getFormKey(),
'firstname' => 'James',
'lastname' => 'Bond',
'company' => 'Magento Commerce Inc.',
'telephone' => '1112223333',
'fax' => '2223334444',
// omit street and city to fail validation
'region_id' => '12',
'region' => 'California',
'postcode' => '55555',
'country_id' => 'US',
'success_url' => '',
'error_url' => '',
]
);
// we are overwriting the address coming from the fixture
$this->dispatch('customer/address/formPost');
$this->getCustomerRegistry()->remove(1);
$this->assertRedirect($this->stringContains('customer/address/edit'));
$this->assertSessionMessages(
$this->equalTo(
[
'One or more input exceptions have occurred.',
'&quot;street&quot; is required. Enter and try again.',
'&quot;city&quot; is required. Enter and try again.',
]
),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testDeleteAction()
{
$this->getRequest()->setParam('id', 1);
$this->getRequest()->setParam('form_key', $this->formKey->getFormKey())->setMethod(HttpRequest::METHOD_POST);
// we are overwriting the address coming from the fixture
$this->dispatch('customer/address/delete');
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo(['You deleted the address.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testWrongAddressDeleteAction()
{
$this->getRequest()->setParam('id', 555);
$this->getRequest()->setParam('form_key', $this->formKey->getFormKey())->setMethod(HttpRequest::METHOD_POST);
// we are overwriting the address coming from the fixture
$this->dispatch('customer/address/delete');
$this->assertRedirect($this->stringContains('customer/address/index'));
$this->assertSessionMessages(
$this->equalTo(['We can\'t delete the address right now.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,195 @@
<?php
declare(strict_types=1);
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller\Adminhtml\Address;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\Request\Http as HttpRequest;
/**
* @magentoAppArea adminhtml
*/
class SaveTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var AccountManagementInterface */
private $accountManagement;
/** @var \Magento\TestFramework\ObjectManager */
private $objectManager;
/** @var \Magento\Customer\Controller\Adminhtml\Address\Save */
private $customerAddress;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = Bootstrap::getObjectManager()->get(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$this->accountManagement = Bootstrap::getObjectManager()->get(
\Magento\Customer\Api\AccountManagementInterface::class
);
$this->objectManager = Bootstrap::getObjectManager();
$this->customerAddress = $this->objectManager->get(\Magento\Customer\Controller\Adminhtml\Address\Save::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
/**
* Unset customer data
*/
Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session::class)->setCustomerData(null);
/**
* Unset messages
*/
Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session::class)->getMessages(true);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_no_address.php
*
* Check that customer id set and addresses saved
*/
public function testSaveActionWithValidAddressData()
{
$customer = $this->customerRepository->get('customer5@example.com');
$customerId = $customer->getId();
$post = [
'parent_id' => $customerId,
'firstname' => 'test firstname',
'lastname' => 'test lastname',
'street' => ['test street'],
'city' => 'test city',
'region_id' => 10,
'country_id' => 'US',
'postcode' => '01001',
'telephone' => '+7000000001',
];
$this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST);
$this->objectManager->get(\Magento\Backend\Model\Session::class)->setCustomerFormData($post);
$this->customerAddress->execute();
$this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
/** Check that customer data were cleaned after it was saved successfully*/
$this->assertEmpty($this->objectManager->get(\Magento\Backend\Model\Session::class)->getCustomerData());
$customer = $this->customerRepository->getById($customerId);
$this->assertEquals('Firstname', $customer->getFirstname());
$addresses = $customer->getAddresses();
$this->assertCount(1, $addresses);
$this->assertNull($this->accountManagement->getDefaultBillingAddress($customerId));
$this->assertNull($this->accountManagement->getDefaultShippingAddress($customerId));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_no_address.php
*
* Check that customer id set and addresses saved
*/
public function testSaveActionWithDefaultShippingAndBilling()
{
$customer = $this->customerRepository->get('customer5@example.com');
$customerId = $customer->getId();
$post = [
'parent_id' => $customerId,
'firstname' => 'test firstname',
'lastname' => 'test lastname',
'street' => ['test street'],
'city' => 'test city',
'region_id' => 10,
'country_id' => 'US',
'postcode' => '01001',
'telephone' => '+7000000001',
'default_billing' => true,
'default_shipping' => true
];
$this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST);
$this->objectManager->get(\Magento\Backend\Model\Session::class)->setCustomerFormData($post);
$this->customerAddress->execute();
/**
* Check that errors was generated and set to session
*/
$this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
/**
* Check that customer data were cleaned after it was saved successfully
*/
$this->assertEmpty($this->objectManager->get(\Magento\Backend\Model\Session::class)->getCustomerData());
/**
* Remove stored customer from registry
*/
$this->objectManager->get(\Magento\Customer\Model\CustomerRegistry::class)->remove($customerId);
$customer = $this->customerRepository->get('customer5@example.com');
$this->assertEquals('Firstname', $customer->getFirstname());
$addresses = $customer->getAddresses();
$this->assertCount(1, $addresses);
$this->assertNotNull($this->accountManagement->getDefaultBillingAddress($customerId));
$this->assertNotNull($this->accountManagement->getDefaultShippingAddress($customerId));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
*
* Check that customer id set and addresses saved
*/
public function testSaveActionWithExistingAdresses()
{
$customer = $this->customerRepository->get('customer@example.com');
$customerId = $customer->getId();
$post = [
'parent_id' => $customerId,
'firstname' => 'test firstname',
'lastname' => 'test lastname',
'street' => ['test street'],
'city' => 'test city',
'region_id' => 10,
'country_id' => 'US',
'postcode' => '01001',
'telephone' => '+7000000001',
];
$this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST);
$this->objectManager->get(\Magento\Backend\Model\Session::class)->setCustomerFormData($post);
$this->customerAddress->execute();
/**
* Check that errors was generated and set to session
*/
$this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
/**
* Check that customer data were cleaned after it was saved successfully
*/
$this->assertEmpty($this->objectManager->get(\Magento\Backend\Model\Session::class)->getCustomerData());
$customer = $this->customerRepository->getById($customerId);
$this->assertEquals('test firstname', $customer->getFirstname());
$addresses = $customer->getAddresses();
$this->assertCount(4, $addresses);
}
}
@@ -0,0 +1,140 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Cart\Product\Composite\Cart;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for configure quote item in customer shopping cart.
*
* @magentoAppArea adminhtml
*/
class ConfigureTest extends AbstractBackendController
{
/** @var CollectionFactory */
private $quoteItemCollectionFactory;
/** @var int */
private $baseWebsiteId;
/** @var SerializerInterface */
private $json;
/** @inheritdoc */
public function setUp(): void
{
parent::setUp();
$this->quoteItemCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
$this->baseWebsiteId = (int)$this->_objectManager->get(StoreManagerInterface::class)
->getWebsite('base')
->getId();
$this->json = $this->_objectManager->get(SerializerInterface::class);
}
/**
* @return void
*/
public function testConfigureActionNoCustomerId(): void
{
$this->dispatchCompositeCartConfigure();
$this->assertEquals(
[
'error' => true,
'message' => "The customer ID isn't defined.",
],
$this->json->unserialize($this->getResponse()->getBody())
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testConfigureNoQuoteId(): void
{
$this->dispatchCompositeCartConfigure([
'customer_id' => 1,
'website_id' => $this->baseWebsiteId,
]);
$this->assertEquals(
[
'error' => true,
'message' => "The quote items are incorrect. Verify the quote items and try again.",
],
$this->json->unserialize($this->getResponse()->getBody())
);
}
/**
* @dataProvider configureWithQuoteProvider
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/quote.php
* @param bool $hasQuoteItem
* @param string $expectedResponseBody
* @return void
*/
public function testConfigureWithQuote(bool $hasQuoteItem, string $expectedResponseBody): void
{
$itemsCollection = $this->quoteItemCollectionFactory->create();
$itemId = $itemsCollection->getFirstItem()->getId();
$this->assertNotEmpty($itemId);
if (!$hasQuoteItem) {
$itemId++;
}
$this->dispatchCompositeCartConfigure([
'customer_id' => 1,
'website_id' => $this->baseWebsiteId,
'id' => $itemId,
]);
$this->assertStringContainsString(
$expectedResponseBody,
$this->getResponse()->getBody()
);
}
/**
* Create configure with quote provider
*
* @return array
*/
public function configureWithQuoteProvider(): array
{
return [
'with_quote_item_id' => [
'has_quote_item' => true,
'expected_response_body' => '<input id="product_composite_configure_input_qty"'
. ' class="input-text admin__control-text qty" type="text" name="qty" value="1">',
],
'without_quote_item_id' => [
'has_quote_item' => false,
'expected_response_body' => '{"error":true,"message":"The quote items are incorrect.'
. ' Verify the quote items and try again."}',
],
];
}
/**
* Dispatch configure quote item in customer shopping cart
* using backend/customer/cart_product_composite_cart/configure action.
*
* @param array $params
* @param array $postValue
* @return void
*/
private function dispatchCompositeCartConfigure(array $params = [], array $postValue = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams($params);
$this->getRequest()->setPostValue($postValue);
$this->dispatch('backend/customer/cart_product_composite_cart/configure');
}
}
@@ -0,0 +1,407 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Cart\Product\Composite\Cart;
use Magento\Backend\Model\Session;
use Magento\Bundle\Model\Product\OptionList;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Option as ProductOption;
use Magento\Catalog\Model\Product\Option\Type\File\ValidatorInfo;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\DataObject;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use Magento\TestFramework\TestCase\AbstractBackendController;
use PHPUnit\Framework\MockObject\MockObject;
/**
* Tests for update quote item in customer shopping cart.
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class UpdateTest extends AbstractBackendController
{
/** @var CollectionFactory */
private $quoteItemCollectionFactory;
/** @var Session */
private $session;
/** @var SerializerInterface */
private $json;
/** @var CartRepositoryInterface */
private $quoteRepository;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var int */
private $baseWebsiteId;
/** @inheritdoc */
public function setUp(): void
{
parent::setUp();
$this->quoteItemCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
$this->session = $this->_objectManager->get(Session::class);
$this->json = $this->_objectManager->get(SerializerInterface::class);
$this->quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->baseWebsiteId = (int)$this->_objectManager->get(StoreManagerInterface::class)
->getWebsite('base')
->getId();
}
/**
* @return void
*/
public function testUpdateNoCustomerId(): void
{
$expectedUpdateResult = [
'error' => true,
'message' => (string)__("The customer ID isn't defined."),
'js_var_name' => null,
];
$this->dispatchCompositeCartUpdate();
/** @var DataObject $updateResult */
$updateResult = $this->session->getCompositeProductResult();
$this->assertEquals($expectedUpdateResult, $updateResult->getData());
$this->assertRedirect($this->stringContains('catalog/product/showUpdateResult'));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testUpdateNoQuoteId(): void
{
$expectedUpdateResult = [
'error' => true,
'message' => (string)__('The quote items are incorrect. Verify the quote items and try again.'),
'js_var_name' => 'iFrameResponse',
];
$this->dispatchCompositeCartUpdate([
'customer_id' => 1,
'website_id' => $this->baseWebsiteId,
'as_js_varname' => 'iFrameResponse',
]);
/** @var DataObject $updateResult */
$updateResult = $this->session->getCompositeProductResult();
$this->assertEquals($expectedUpdateResult, $updateResult->getData());
$this->assertRedirect($this->stringContains('catalog/product/showUpdateResult'));
}
/**
* @dataProvider updateWithQuoteProvider
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/quote.php
* @param bool $hasQuoteItem
* @param array $expectedUpdateResult
* @return void
*/
public function testUpdateWithQuote(bool $hasQuoteItem, array $expectedUpdateResult): void
{
$itemsCollection = $this->quoteItemCollectionFactory->create();
$itemId = $itemsCollection->getFirstItem()->getId();
$this->assertNotEmpty($itemId);
if (!$hasQuoteItem) {
$itemId++;
}
$this->dispatchCompositeCartUpdate(
[
'customer_id' => 1,
'website_id' => $this->baseWebsiteId,
],
[
'id' => $itemId,
'as_js_varname' => 'iFrameResponse',
'qty' => 20,
]
);
/** @var DataObject $updateResult */
$updateResult = $this->session->getCompositeProductResult();
$this->assertEquals($expectedUpdateResult, $updateResult->getData());
$this->assertRedirect($this->stringContains('catalog/product/showUpdateResult'));
}
/**
* Create update with quote provider
*
* @return array
*/
public function updateWithQuoteProvider(): array
{
return [
'with_quote_item_id' => [
'has_quote_item' => true,
'expected_update_result' => [
'ok' => true,
'js_var_name' => 'iFrameResponse',
],
],
'without_quote_item_id' => [
'has_quote_item' => false,
'expected_update_result' => [
'error' => true,
'message' => (string)__('The quote items are incorrect. Verify the quote items and try again.'),
'js_var_name' => 'iFrameResponse',
],
],
];
}
/**
* @magentoDataFixture Magento/Checkout/_files/customer_quote_with_items_simple_product_options.php
* @return void
*/
public function testUpdateSimpleProductOption(): void
{
$customer = $this->customerRepository->get('customer_uk_address@test.com');
/** @var Quote $quote */
$quote = $this->quoteRepository->getForCustomer($customer->getId());
/** @var QuoteItem $quoteItem */
$quoteItem = $quote->getItemsCollection()->getFirstItem();
$this->assertNotEmpty($quoteItem->getId());
$expectedData = $this->prepareExpectedData($quoteItem);
$expectedUpdateResult = [
'ok' => true,
'js_var_name' => 'iFrameResponse',
];
$expectedParams = [
'id' => $quoteItem->getId(),
'as_js_varname' => 'iFrameResponse',
'options' => $expectedData['options'],
'qty' => 5,
];
$this->dispatchCompositeCartUpdate(
[
'customer_id' => $customer->getId(),
'website_id' => $customer->getWebsiteId(),
],
$expectedParams
);
/** @var DataObject $updateResult */
$updateResult = $this->session->getCompositeProductResult();
$this->assertEquals($expectedUpdateResult, $updateResult->getData());
$quoteItem = $this->getQuoteItemBySku($quote, $expectedData['sku']);
$this->assertNotNull($quoteItem, 'Missing expected shopping cart item after update.');
$this->assertQuoteItemOptions($quoteItem, $expectedParams);
$this->assertRedirect($this->stringContains('catalog/product/showUpdateResult'));
}
/**
* Tests updating bundle item quantity in the customer's shopping cart.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Checkout/_files/quote_with_bundle_product.php
* @dataProvider bundleOptionQuantityProvider
* @param string $quantity
* @param string|null $message
* @return void
*/
public function testUpdateBundleOptionQuantity(string $quantity, ?string $message): void
{
$productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$bundleOptionList = $this->_objectManager->get(OptionList::class);
$getQuoteByReservedOrderId = $this->_objectManager->get(GetQuoteByReservedOrderId::class);
$bundleProduct = $productRepository->get('bundle-product');
$bundleOptions = $bundleOptionList->getItems($bundleProduct);
$option = reset($bundleOptions);
$productLinks = $option->getProductLinks();
$this->assertNotNull($productLinks[0]);
$customer = $this->customerRepository->get('customer@example.com');
$quote = $getQuoteByReservedOrderId->execute('test_cart_with_bundle');
$quote->assignCustomer($customer);
$this->quoteRepository->save($quote);
$quoteItem = $quote->getItemsCollection()->getFirstItem();
$this->assertNotEmpty($quoteItem->getId());
$postValue = [
'bundle_option' => [
$option->getOptionId() => $productLinks[0]->getId(),
],
'qty' => $quantity,
'id' => $quoteItem->getId(),
'as_js_varname' => 'iFrameResponse',
];
$this->dispatchCompositeCartUpdate(
[
'customer_id' => $customer->getId(),
'website_id' => $customer->getWebsiteId(),
],
$postValue
);
$updateResult = $this->session->getCompositeProductResult();
$this->assertEquals($message, $updateResult->getMessage());
}
/**
* @return array
*/
public function bundleOptionQuantityProvider(): array
{
return [
'Quantity, less than allowed in the Shopping Cart' => [
'0.1',
'The fewest you may purchase is 1.',
],
'Decimal quantity not allowed' => [
'1.1',
'You cannot use decimal quantity for this product.',
],
'Quantity, greater than available' => [
'1000',
'The requested qty is not available',
],
'Quantity, greater than allowed in the Shopping Cart' => [
'100000',
'The requested qty exceeds the maximum qty allowed in shopping cart',
],
'Allowed quantity' => [
'2',
null,
],
];
}
/**
* Prepare quote item options and sku for update.
*
* @param QuoteItem $quoteItem
* @return array
*/
private function prepareExpectedData(QuoteItem $quoteItem): array
{
$buyRequest = $this->json->unserialize($quoteItem->getOptionByCode('info_buyRequest')->getValue());
$productOptions = $quoteItem->getProduct()->getOptions();
$options = [];
$sku = $quoteItem->getSku();
/** @var ProductOption $productOption */
foreach ($productOptions as $productOption) {
$itemOptionValue = $buyRequest['options'][$productOption->getId()];
switch ($productOption->getType()) {
case ProductCustomOptionInterface::OPTION_TYPE_RADIO:
$productValues = $productOption->getValues();
$currentRadioSku = $productValues[$itemOptionValue]->getSku();
unset($productValues[$itemOptionValue]);
$value = (string)key($productValues);
$newRadioSku = $productValues[$value]->getSku();
$sku = str_replace($currentRadioSku, $newRadioSku, $sku);
break;
case ProductCustomOptionInterface::OPTION_TYPE_DATE:
$value = ['year' => 2019, 'month' => 8, 'day' => 9, 'hour' => 13, 'minute' => 35];
break;
case ProductCustomOptionInterface::OPTION_TYPE_FILE:
$itemOptionValue['title'] = 'testcart.jpg';
$value = $itemOptionValue;
$validatorInfoMock = $this->prepareValidatorInfoMock();
$this->_objectManager->addSharedInstance($validatorInfoMock, ValidatorInfo::class);
break;
case ProductCustomOptionInterface::OPTION_TYPE_AREA:
$value = 'testcart';
break;
default:
$value = $itemOptionValue;
break;
}
$options[$productOption->getId()] = $value;
}
return [
'options' => $options,
'sku' => $sku,
];
}
/**
* Prepare mock for updating file type options.
*
* @return MockObject
*/
private function prepareValidatorInfoMock(): MockObject
{
$validatorInfoMock = $this->createMock(ValidatorInfo::class);
$validatorInfoMock->method('setUseQuotePath')->willReturnSelf();
$validatorInfoMock->expects($this->any())
->method('validate')
->willReturn(true);
return $validatorInfoMock;
}
/**
* Get quote item by sku.
*
* @param Quote $quote
* @param string $sku
* @return QuoteItem|null
*/
private function getQuoteItemBySku(Quote $quote, string $sku): ?QuoteItem
{
$itemsCollection = $quote->getItemsCollection(false);
$itemsCollection->addFieldToFilter('sku', $sku);
/** @var QuoteItem $quoteItem */
$quoteItem = $itemsCollection->getFirstItem();
return empty($quoteItem->getId()) ? null : $quoteItem;
}
/**
* Verify that the quote item options are saved successfully.
*
* @param QuoteItem $quoteItem
* @param array $expectedParams
* @return void
*/
private function assertQuoteItemOptions(QuoteItem $quoteItem, array $expectedParams): void
{
$buyRequest = $this->json->unserialize($quoteItem->getOptionByCode('info_buyRequest')->getValue());
foreach ($expectedParams as $key => $value) {
if ($key == 'options') {
foreach ($value as $optionId => $optionValue) {
$buyRequestValue = is_array($optionValue)
? array_intersect_assoc($optionValue, $buyRequest[$key][$optionId])
: $buyRequest[$key][$optionId];
$this->assertEquals($optionValue, $buyRequestValue);
}
} else {
$this->assertEquals($value, $buyRequest[$key]);
}
}
}
/**
* Dispatch update quote item in customer shopping cart
* using backend/customer/cart_product_composite_cart/update action.
*
* @param array $params
* @param array $postValue
* @return void
*/
private function dispatchCompositeCartUpdate(array $params = [], array $postValue = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams($params);
$this->getRequest()->setPostValue($postValue);
$this->dispatch('backend/customer/cart_product_composite_cart/update');
}
}
@@ -0,0 +1,62 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Customer;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Invalidate customer token tests.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class InvalidateTokenTest extends AbstractBackendController
{
/** @var Escaper */
private $escaper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
}
/**
* @magentoDataFixture Magento/Integration/_files/customer_with_integration_token.php
*
* @return void
*/
public function testInvalidateCustomerToken(): void
{
$customerId = 1;
$this->getRequest()->setParam('customer_id', $customerId)->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/customer/invalidateToken');
$this->assertRedirect($this->stringContains('backend/customer/index/edit/id/' . $customerId));
$message = $this->escaper->escapeHtml('You have revoked the customer\'s tokens.');
$this->assertSessionMessages($this->equalTo([(string)__($message)]), MessageInterface::TYPE_SUCCESS);
}
/**
* @return void
*/
public function testInvalidateCustomerTokenWithoutParams(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/customer/invalidateToken');
$this->assertRedirect($this->stringContains('backend/customer/index/index'));
$message = $this->escaper->escapeHtml('We can\'t find a customer to revoke.');
$this->assertSessionMessages($this->equalTo([(string)__($message)]), MessageInterface::TYPE_ERROR);
}
}
@@ -0,0 +1,331 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller\Adminhtml;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class GroupTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
const TAX_CLASS_ID = 3;
const TAX_CLASS_NAME = 'Retail Customer';
const CUSTOMER_GROUP_CODE = 'custom_group';
const BASE_CONTROLLER_URL = 'http://localhost/index.php/backend/customer/group/';
const CUSTOMER_GROUP_ID = 2;
/** @var \Magento\Framework\Session\SessionManagerInterface */
private $session;
/** @var \Magento\Customer\Api\GroupRepositoryInterface */
private $groupRepository;
/**
* @inheritDoc
*
* @throws \Magento\Framework\Exception\AuthenticationException
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->session = $objectManager->get(\Magento\Framework\Session\SessionManagerInterface::class);
$this->groupRepository = $objectManager->get(\Magento\Customer\Api\GroupRepositoryInterface::class);
}
/**
* Test new group form.
*/
public function testNewActionNoCustomerGroupDataInSession()
{
$this->dispatch('backend/customer/group/new');
$responseBody = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression(
'/<h1 class\="page-title">\s*New Customer Group\s*<\/h1>/',
$responseBody
);
$expected = '<input id="customer_group_code" name="code" '
. 'data-ui-id="group-form-fieldset-element-text-code" value=""';
$this->assertStringContainsString($expected, $responseBody);
}
/**
* Test form filling with data in session.
*/
public function testNewActionWithCustomerGroupDataInSession()
{
/** @var \Magento\Customer\Api\Data\GroupInterfaceFactory $customerGroupFactory */
$customerGroupFactory = $this->_objectManager
->get(\Magento\Customer\Api\Data\GroupInterfaceFactory::class);
/** @var \Magento\Customer\Api\Data\GroupInterface $customerGroup */
$customerGroup = $customerGroupFactory->create()
->setCode(self::CUSTOMER_GROUP_CODE)
->setTaxClassId(self::TAX_CLASS_ID);
/** @var \Magento\Framework\Reflection\DataObjectProcessor $dataObjectProcessor */
$dataObjectProcessor = $this->_objectManager->get(\Magento\Framework\Reflection\DataObjectProcessor::class);
$customerGroupData = $dataObjectProcessor
->buildOutputDataArray($customerGroup, \Magento\Customer\Api\Data\GroupInterface::class);
if (array_key_exists('code', $customerGroupData)) {
$customerGroupData['customer_group_code'] = $customerGroupData['code'];
unset($customerGroupData['code']);
}
$this->session->setCustomerGroupData($customerGroupData);
$this->dispatch('backend/customer/group/new');
$responseBody = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression(
'/<h1 class\="page-title">\s*New Customer Group\s*<\/h1>/',
$responseBody
);
$expected = '<input id="customer_group_code" name="code" '
. 'data-ui-id="group-form-fieldset-element-text-code" value="' . self::CUSTOMER_GROUP_CODE . '"';
$this->assertStringContainsString($expected, $responseBody);
}
/**
* Test calling delete without an ID.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testDeleteActionNoGroupId()
{
$this->getRequest()->setMethod(\Magento\Framework\App\Request\Http::METHOD_POST);
$this->dispatch('backend/customer/group/delete');
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL));
}
/**
* Test deleting a group.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testDeleteActionExistingGroup()
{
$groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE);
$this->getRequest()->setParam('id', $groupId);
$this->getRequest()->setMethod(\Magento\Framework\App\Request\Http::METHOD_POST);
$this->dispatch('backend/customer/group/delete');
/**
* Check that success message is set
*/
$this->assertSessionMessages(
$this->equalTo(['You deleted the customer group.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'index'));
}
/**
* Tet deleting with wrong ID.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testDeleteActionNonExistingGroupId()
{
$this->getRequest()->setParam('id', 10000);
$this->getRequest()->setMethod(\Magento\Framework\App\Request\Http::METHOD_POST);
$this->dispatch('backend/customer/group/delete');
/**
* Check that error message is set
*/
$this->assertSessionMessages(
$this->equalTo(['The customer group no longer exists.']),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL));
}
/**
* Test saving a valid group.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testSaveActionExistingGroup()
{
$groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE);
$this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID);
$this->getRequest()->setParam('id', $groupId);
$this->getRequest()->setParam('code', self::CUSTOMER_GROUP_CODE);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR);
$this->assertSessionMessages($this->logicalNot($this->isEmpty()), MessageInterface::TYPE_SUCCESS);
$this->assertSessionMessages(
$this->equalTo(['You saved the customer group.']),
MessageInterface::TYPE_SUCCESS
);
/** @var \Magento\Framework\Api\SimpleDataObjectConverter $simpleDataObjectConverter */
$simpleDataObjectConverter = Bootstrap::getObjectManager()
->get(\Magento\Framework\Api\SimpleDataObjectConverter::class);
$customerGroupData = $simpleDataObjectConverter->toFlatArray(
$this->groupRepository->getById($groupId),
\Magento\Customer\Api\Data\GroupInterface::class
);
ksort($customerGroupData);
$this->assertEquals(
[
'code' => self::CUSTOMER_GROUP_CODE,
'id' => $groupId,
'tax_class_id' => self::TAX_CLASS_ID,
'tax_class_name' => self::TAX_CLASS_NAME,
],
$customerGroupData
);
}
/**
* Test saving an invalid group.
*/
public function testSaveActionCreateNewGroupWithoutCode()
{
$this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$this->assertSessionMessages(
$this->equalTo([htmlspecialchars('"code" is required. Enter and try again.')]),
MessageInterface::TYPE_ERROR
);
}
/**
* Test saving an empty group.
*/
public function testSaveActionForwardNewCreateNewGroup()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$responseBody = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression(
'/<h1 class\="page-title">\s*New Customer Group\s*<\/h1>/',
$responseBody
);
}
/**
* Test saving an existing group.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testSaveActionForwardNewEditExistingGroup()
{
$groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('id', $groupId);
$this->dispatch('backend/customer/group/save');
$responseBody = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression(
'/<h1 class\="page-title">\s*' . self::CUSTOMER_GROUP_CODE . '\s*<\/h1>/',
$responseBody
);
}
/**
* Test using an invalid ID.
*/
public function testSaveActionNonExistingGroupId()
{
$this->getRequest()->setParam('id', 10000);
$this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_SUCCESS);
$this->assertSessionMessages($this->logicalNot($this->isEmpty()), MessageInterface::TYPE_ERROR);
$this->assertSessionMessages(
$this->equalTo(['No such entity with id = 10000']),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/'));
$this->assertNull($this->session->getCustomerGroupData());
}
/**
* Test using existing code.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testSaveActionNewGroupWithExistingGroupCode()
{
$groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE);
$originalCode = $this->groupRepository->getById($groupId)->getCode();
$this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID);
$this->getRequest()->setParam('code', self::CUSTOMER_GROUP_CODE);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$this->assertSessionMessages($this->equalTo(['Customer Group already exists.']), MessageInterface::TYPE_ERROR);
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_SUCCESS);
$this->assertEquals($originalCode, $this->groupRepository->getById($groupId)->getCode());
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/'));
$this->assertEquals(self::CUSTOMER_GROUP_CODE, $this->session->getCustomerGroupData()['customer_group_code']);
$this->assertEquals(self::TAX_CLASS_ID, $this->session->getCustomerGroupData()['tax_class_id']);
}
/**
* Test saving an invalid group.
*
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testSaveActionNewGroupWithoutGroupCode()
{
$groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE);
$originalCode = $this->groupRepository->getById($groupId)->getCode();
$this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/group/save');
$this->assertSessionMessages(
$this->equalTo([htmlspecialchars('"code" is required. Enter and try again.')]),
MessageInterface::TYPE_ERROR
);
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_SUCCESS);
$this->assertEquals($originalCode, $this->groupRepository->getById($groupId)->getCode());
$this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/'));
$this->assertEquals('', $this->session->getCustomerGroupData()['customer_group_code']);
$this->assertEquals(self::TAX_CLASS_ID, $this->session->getCustomerGroupData()['tax_class_id']);
}
/**
* Find the group with a given code.
*
* @param string $code
* @return int
*/
protected function findGroupIdWithCode($code)
{
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->_objectManager->create(\Magento\Framework\Api\SearchCriteriaBuilder::class);
foreach ($this->groupRepository->getList($searchBuilder->create())->getItems() as $group) {
if ($group->getCode() === $code) {
return $group->getId();
}
}
return -1;
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Class checks customer's shopping cart controller.
*
* @see \Magento\Customer\Controller\Adminhtml\Index\Cart
* @magentoAppArea adminhtml
*/
class CartTest extends AbstractBackendController
{
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var CartRepositoryInterface */
private $quoteRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
* @return void
*/
public function testCartAction(): void
{
$this->dispatchShoppingCart(
[
'id' => 1,
'website_id' => 1,
],
['delete' => 1]
);
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('<div id="customer_cart_grid"', $body);
}
/**
* Delete customer shopping cart item
*
* @magentoDataFixture Magento/Checkout/_files/customer_quote_with_items_simple_product_options.php
* @return void
*/
public function testDeleteCartItem(): void
{
$customer = $this->customerRepository->get('customer_uk_address@test.com');
/** @var Quote $quote */
$quote = $this->quoteRepository->getForCustomer($customer->getId());
$quoteItemId = $quote->getItemsCollection()->getFirstItem()->getItemId();
$this->assertNotEmpty($quoteItemId);
$this->dispatchShoppingCart(
[
'id' => $customer->getId(),
'website_id' => $customer->getWebsiteId(),
],
['delete' => $quoteItemId]
);
$quote->getItemsCollection(false);
$this->assertFalse(
$quote->getItemById($quoteItemId),
sprintf('Customer\'s shopping cart item with ID = %s has not been deleted', $quoteItemId)
);
}
/**
* Dispatch admin shopping cart using backend/customer/index/cart action.
*
* @param array $params
* @param array $postValue
* @return void
*/
private function dispatchShoppingCart(array $params = [], array $postValue = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams($params);
$this->getRequest()->setPostValue($postValue);
$this->dispatch('backend/customer/index/cart');
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for delete customer via backend/customer/index/delete controller.
*
* @magentoAppArea adminhtml
*/
class DeleteTest extends AbstractBackendController
{
/** @var FormKey */
private $formKey;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* Delete customer
*
* @dataProvider deleteCustomerProvider
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
*
* @param array $paramsData
* @param string $expected
* @return void
*/
public function testDeleteCustomer(array $paramsData, array $expected): void
{
$this->dispatchCustomerDelete($paramsData);
$this->assertRedirect($this->stringContains('customer/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__(...$expected['message'])]),
$expected['message_type']
);
}
/**
* Delete customer provider
*
* @return array
*/
public function deleteCustomerProvider(): array
{
return [
'delete_customer_success' => [
'params_data' => [
'id' => 1,
],
'expected' => [
'message' => ['You deleted the customer.'],
'message_type' => MessageInterface::TYPE_SUCCESS,
],
],
'not_existing_customer_error' => [
'params_data' => [
'id' => 2,
],
'expected' => [
'message' => [
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'customerId',
'fieldValue' => '2',
],
],
'message_type' => MessageInterface::TYPE_ERROR,
],
],
];
}
/**
* Delete customer using backend/customer/index/delete action.
*
* @param array $params
* @return void
*/
private function dispatchCustomerDelete(array $params): void
{
$params['form_key'] = $this->formKey->getFormKey();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams($params);
$this->dispatch('backend/customer/index/delete');
}
}
@@ -0,0 +1,212 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Observer\AfterAddressSaveObserver;
use Magento\Eav\Model\AttributeRepository;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test inline edit action on customers grid.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class InlineEditTest extends AbstractBackendController
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var SerializerInterface */
private $json;
/** @var WebsiteRepositoryInterface */
private $websiteRepository;
/** @var AttributeRepository */
private $attributeRepository;
/** @var AddressRepositoryInterface */
private $addressRepository;
/** @var Registry */
private $coreRegistry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$this->json = $this->objectManager->get(SerializerInterface::class);
$this->websiteRepository = $this->objectManager->get(WebsiteRepositoryInterface::class);
$this->attributeRepository = $this->objectManager->get(AttributeRepository::class);
$this->addressRepository = $this->objectManager->get(AddressRepositoryInterface::class);
$this->coreRegistry = Bootstrap::getObjectManager()->get(Registry::class);
}
/**
* @magentoDataFixture Magento/Customer/_files/two_customers.php
*
* @return void
*/
public function testInlineEditAction(): void
{
$firstCustomer = $this->customerRepository->get('customer@example.com');
$secondCustomer = $this->customerRepository->get('customer_two@example.com');
$defaultWebsiteId = $this->websiteRepository->get('base')->getId();
$genderId = $this->attributeRepository->get(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'gender')
->getSource()->getOptionId('Male');
$params = [
'items' => [
$firstCustomer->getId() => [
CustomerInterface::EMAIL => 'updated_customer@example.com',
CustomerInterface::GROUP_ID => 2,
CustomerInterface::WEBSITE_ID => $defaultWebsiteId,
CustomerInterface::TAXVAT => 123123,
CustomerInterface::GENDER => $genderId,
],
$secondCustomer->getId() => [
CustomerInterface::EMAIL => 'updated_customer_two@example.com',
CustomerInterface::GROUP_ID => 3,
CustomerInterface::WEBSITE_ID => $defaultWebsiteId,
CustomerInterface::TAXVAT => 456456,
CustomerInterface::GENDER => $genderId,
],
],
'isAjax' => true,
];
$actual = $this->performInlineEditRequest($params);
$this->assertEmpty($actual['messages']);
$this->assertFalse($actual['error']);
$this->assertCustomersData($params);
}
/**
* @dataProvider inlineEditParametersDataProvider
*
* @param array $params
* @return void
*/
public function testInlineEditWithWrongParams(array $params): void
{
$actual = $this->performInlineEditRequest($params);
$this->assertEquals([(string)__('Please correct the data sent.')], $actual['messages']);
$this->assertTrue($actual['error']);
}
/**
* @return array
*/
public function inlineEditParametersDataProvider(): array
{
return [
[
'items' => [],
'isAjax' => true,
],
[
'items' => [],
],
];
}
/**
* Customer group should not change after saving customer via customer grid because of disabled address validation
*
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
* @magentoConfigFixture current_store customer/create_account/viv_invalid_group 2
* @magentoDataFixture Magento/Customer/_files/customer_one_address.php
*
* @return void
*/
public function testInlineEditActionWithAddress(): void
{
$customer = $this->getCustomer();
$params = [
'items' => [
$customer->getId() => []
],
'isAjax' => true,
];
$actual = $this->performInlineEditRequest($params);
$updatedCustomer = $this->customerRepository->get('customer_one_address@test.com');
$this->assertEmpty($actual['messages']);
$this->assertFalse($actual['error']);
$this->assertEquals(
$customer->getGroupId(),
$updatedCustomer->getGroupId(),
'Customer group was changed!'
);
}
/**
* Change customer address with setting country from EU and setting VAT number
*
* @return CustomerInterface
*/
private function getCustomer(): CustomerInterface
{
$customer = $this->customerRepository->get('customer_one_address@test.com');
$address = $this->addressRepository->getById((int)$customer->getDefaultShipping());
$address->setVatId(12345);
$address->setCountryId('DE');
$address->setRegionId(0);
$this->addressRepository->save($address);
$this->coreRegistry->unregister(AfterAddressSaveObserver::VIV_PROCESSED_FLAG);
//return customer after address repository save
return $this->customerRepository->get('customer_one_address@test.com');
}
/**
* Perform inline edit request.
*
* @param array $params
* @return array
*/
private function performInlineEditRequest(array $params): array
{
$this->getRequest()->setParams($params)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/inlineEdit');
return $this->json->unserialize($this->getResponse()->getBody());
}
/**
* Assert customers data.
*
* @param array $data
* @return void
*/
private function assertCustomersData(array $data): void
{
foreach ($data['items'] as $customerId => $expectedData) {
$customerData = $this->customerRepository->getById($customerId)->__toArray();
foreach ($expectedData as $key => $value) {
$this->assertEquals($value, $customerData[$key]);
}
}
}
}
@@ -0,0 +1,147 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Backend\Model\Session;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* @magentoAppArea adminhtml
*/
class MassAssignGroupTest extends AbstractBackendController
{
/**
* Base controller URL
*
* @var string
*/
protected $baseControllerUrl = 'http://localhost/index.php/backend/customer/index/index';
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @inheritDoc
*
* @throws \Magento\Framework\Exception\AuthenticationException
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
/**
* Unset customer data
*/
Bootstrap::getObjectManager()->get(Session::class)->setCustomerData(null);
/**
* Unset messages
*/
Bootstrap::getObjectManager()->get(Session::class)->getMessages(true);
}
/**
* Tests os update a single customer record.
*
* @magentoDataFixture Magento/Customer/_files/five_repository_customers.php
* @magentoDbIsolation disabled
*/
public function testMassAssignGroupAction()
{
$customerEmail = 'customer1@example.com';
/** @var CustomerInterface $customer */
$customer = $this->customerRepository->get($customerEmail);
$this->assertEquals(1, $customer->getGroupId());
$params = [
'group' => 0,
'namespace' => 'customer_listing',
'selected' => [$customer->getId()]
];
$this->getRequest()->setParams($params)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massAssignGroup');
$this->assertSessionMessages(
self::equalTo(['A total of 1 record(s) were updated.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
$customer = $this->customerRepository->get($customerEmail);
$this->assertEquals(0, $customer->getGroupId());
}
/**
* Tests os update a multiple customer records.
*
* @magentoDataFixture Magento/Customer/_files/five_repository_customers.php
* @magentoDbIsolation disabled
*/
public function testLargeGroupMassAssignGroupAction()
{
$ids = [];
for ($i = 1; $i <= 5; $i++) {
/** @var CustomerInterface $customer */
$customer = $this->customerRepository->get('customer' . $i . '@example.com');
$this->assertEquals(1, $customer->getGroupId());
$ids[] = $customer->getId();
}
$params = [
'group' => 0,
'namespace' => 'customer_listing',
'selected' => $ids,
];
$this->getRequest()->setParams($params)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massAssignGroup');
$this->assertSessionMessages(
self::equalTo(['A total of 5 record(s) were updated.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
for ($i = 1; $i < 5; $i++) {
/** @var CustomerInterface $customer */
$customer = $this->customerRepository->get('customer' . $i . '@example.com');
$this->assertEquals(0, $customer->getGroupId());
}
}
/**
* Valid group Id but no customer Ids specified
*
* @magentoDbIsolation enabled
*/
public function testMassAssignGroupActionNoCustomerIds()
{
$params = ['group'=> 0,'namespace'=> 'customer_listing',
];
$this->getRequest()->setParams($params)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massAssignGroup');
$this->assertSessionMessages(
$this->equalTo(['An item needs to be selected. Select and try again.']),
MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,173 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Backend\Model\Session;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use PHPUnit\Framework\Constraint\Constraint;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* @magentoAppArea adminhtml
*/
class MassDeleteTest extends AbstractBackendController
{
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* Base controller URL
*
* @var string
*/
private $baseControllerUrl = 'http://localhost/index.php/backend/customer/index/index';
/**
* @inheritDoc
*
* @throws \Magento\Framework\Exception\AuthenticationException
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
/**
* Unset customer data
*/
Bootstrap::getObjectManager()->get(Session::class)->setCustomerData(null);
/**
* Unset messages
*/
Bootstrap::getObjectManager()->get(Session::class)->getMessages(true);
}
/**
* Validates failure attempts to delete customers from grid.
*
* @param array|null $ids
* @param Constraint $constraint
* @param string|null $messageType
* @magentoDataFixture Magento/Customer/_files/five_repository_customers.php
* @magentoDbIsolation disabled
* @dataProvider failedRequestDataProvider
*/
public function testFailedMassDeleteAction($ids, Constraint $constraint, $messageType)
{
$this->massDeleteAssertions($ids, $constraint, $messageType);
}
/**
* Validates success attempt to delete customer from grid.
*
* @param array $emails
* @param Constraint $constraint
* @param string $messageType
* @magentoDataFixture Magento/Customer/_files/five_repository_customers.php
* @magentoDbIsolation disabled
* @dataProvider successRequestDataProvider
*/
public function testSuccessMassDeleteAction(array $emails, Constraint $constraint, string $messageType)
{
$ids = [];
foreach ($emails as $email) {
/** @var CustomerInterface $customer */
$customer = $this->customerRepository->get($email);
$ids[] = $customer->getId();
}
$this->massDeleteAssertions(
$ids,
$constraint,
$messageType
);
}
/**
* Performs required request and assertions.
*
* @param array|null $ids
* @param Constraint $constraint
* @param string|null $messageType
*/
private function massDeleteAssertions($ids, Constraint $constraint, $messageType)
{
$requestData = [
'selected' => $ids,
'namespace' => 'customer_listing',
];
$this->getRequest()->setParams($requestData)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massDelete');
$this->assertSessionMessages(
$constraint,
$messageType
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
}
/**
* Provides sets of data for unsuccessful attempts.
*
* @return array
*/
public function failedRequestDataProvider(): array
{
return [
[
'ids' => [],
'constraint' => self::equalTo(['An item needs to be selected. Select and try again.']),
'messageType' => MessageInterface::TYPE_ERROR,
],
[
'ids' => [111],
'constraint' => self::isEmpty(),
'messageType' => null,
],
[
'ids' => null,
'constraint' => self::equalTo(['An item needs to be selected. Select and try again.']),
'messageType' => MessageInterface::TYPE_ERROR,
]
];
}
/**
* Provides sets of data for successful attempts.
*
* @return array
*/
public function successRequestDataProvider(): array
{
return [
[
'customerEmails' => ['customer1@example.com'],
'constraint' => self::equalTo(['A total of 1 record(s) were deleted.']),
'messageType' => MessageInterface::TYPE_SUCCESS,
],
[
'customerEmails' => ['customer2@example.com', 'customer3@example.com'],
'constraint' => self::equalTo(['A total of 2 record(s) were deleted.']),
'messageType' => MessageInterface::TYPE_SUCCESS,
],
];
}
}
@@ -0,0 +1,124 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Backend\Model\Session;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Newsletter\Model\Subscriber;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
/**
* @magentoAppArea adminhtml
*/
class MassSubscribeTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Base controller URL
*
* @var string
*/
protected $baseControllerUrl = 'http://localhost/index.php/backend/customer/index/index';
protected function tearDown(): void
{
/**
* Unset customer data
*/
Bootstrap::getObjectManager()->get(Session::class)->setCustomerData(null);
/**
* Unset messages
*/
Bootstrap::getObjectManager()->get(Session::class)->getMessages(true);
}
/**
* Tests subscriber status of customers.
*
* @magentoDataFixture Magento/Customer/_files/five_repository_customers.php
* @magentoDbIsolation disabled
*/
public function testMassSubscriberAction()
{
/** @var SubscriberFactory $subscriberFactory */
$subscriberFactory = Bootstrap::getObjectManager()->get(SubscriberFactory::class);
$customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class);
$this->assertNull(
$subscriberFactory->create()
->loadByEmail('customer1@example.com')
->getSubscriberStatus()
);
$this->assertNull(
$subscriberFactory->create()
->loadByEmail('customer2@example.com')
->getSubscriberStatus()
);
/** @var CustomerInterface $customer1 */
$customer1 = $customerRepository->get('customer1@example.com');
/** @var CustomerInterface $customer2 */
$customer2 = $customerRepository->get('customer2@example.com');
$params = [
'selected' => [
$customer1->getId(),
$customer2->getId(),
],
'namespace' => 'customer_listing',
];
$this->getRequest()->setParams($params)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massSubscribe');
// Assertions
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
$this->assertSessionMessages(
self::equalTo(['A total of 2 record(s) were updated.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertEquals(
Subscriber::STATUS_SUBSCRIBED,
$subscriberFactory->create()
->loadByEmail('customer1@example.com')
->getSubscriberStatus()
);
$this->assertEquals(
Subscriber::STATUS_SUBSCRIBED,
$subscriberFactory->create()
->loadByEmail('customer2@example.com')
->getSubscriberStatus()
);
}
/**
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testMassSubscriberActionNoSelection()
{
$params = [
'namespace' => 'customer_listing'
];
$this->getRequest()->setParams($params)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massSubscribe');
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
$this->assertSessionMessages(
self::equalTo(['An item needs to be selected. Select and try again.']),
MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory;
use Magento\Newsletter\Model\Subscriber;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test mass subscribe action on customers grid.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class MassUnsubscribeTest extends AbstractBackendController
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var CollectionFactory */
private $subscriberCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->subscriberCollectionFactory = $this->objectManager->get(CollectionFactory::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
}
/**
* @magentoDataFixture Magento/Newsletter/_files/three_subscribers.php
*
* @return void
*/
public function testMassUnsubscribeAction(): void
{
$params = [
'selected' => [1, 2, 3],
'namespace' => 'customer_listing',
];
$this->getRequest()->setParams($params)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massUnsubscribe');
$this->assertRedirect($this->stringContains('backend/customer/index/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__('A total of 3 record(s) were updated.')]),
MessageInterface::TYPE_SUCCESS
);
$emails = ['customer@search.example.com', 'customer2@search.example.com', 'customer3@search.example.com'];
$collection = $this->subscriberCollectionFactory->create()->addFieldToFilter('subscriber_email', $emails)
->addFieldToSelect('subscriber_status');
$this->assertCount(3, $collection);
foreach ($collection as $subscriber) {
$this->assertEquals(Subscriber::STATUS_UNSUBSCRIBED, $subscriber->getData('subscriber_status'));
}
}
/**
* @return void
*/
public function testMassSubscriberActionNoSelection(): void
{
$params = [
'namespace' => 'customer_listing',
];
$this->getRequest()->setParams($params)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/massUnsubscribe');
$this->assertRedirect($this->stringContains('backend/customer/index/index'));
$this->assertSessionMessages(
$this->equalTo([(string)__('An item needs to be selected. Select and try again.')]),
MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,152 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Framework\App\Request\Http as HttpRequest;
/**
* ResetPassword controller test.
*
* @magentoAppArea adminhtml
*/
class ResetPasswordTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Base controller URL
*
* @var string
*/
protected $baseControllerUrl = 'http://localhost/index.php/backend/customer/index/';
/**
* Checks reset password functionality with no restrictive settings and customer reset request event.
* Admin is not affected by this security check, so reset password email must be sent.
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordSuccess()
{
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST
);
$this->getRequest()->setPostValue(['customer_id' => '1'])->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertSessionMessages(
$this->equalTo(['The customer will receive an email with a link to reset password.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl . 'edit'));
}
/**
* Checks reset password functionality cannot be performed with POST request
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordWithPost()
{
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST
);
$this->getRequest()->setPostValue(['customer_id' => '1'])->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertEquals('noroute', $this->getRequest()->getControllerName());
}
/**
* Checks reset password functionality with default restrictive min time between
* password reset requests and customer reset request event.
* Admin is not affected by this security check, so reset password email must be sent.
*
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 10
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordMinTimeError()
{
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST
);
$this->getRequest()->setPostValue(['customer_id' => '1'])->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertSessionMessages(
$this->equalTo(['The customer will receive an email with a link to reset password.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl . 'edit'));
}
/**
* Checks reset password functionality with default restrictive limited number
* password reset requests and customer reset request event.
* Admin is not affected by this security check, so reset password email must be sent.
*
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordLimitError()
{
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST
);
$this->getRequest()->setPostValue(['customer_id' => '1'])->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertSessionMessages(
$this->equalTo(['The customer will receive an email with a link to reset password.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl . 'edit'));
}
/**
* Checks reset password functionality with default settings, customer and admin reset request events.
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 1
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 10
* @magentoConfigFixture current_store contact/email/recipient_email hello@example.com
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordWithSecurityViolationException()
{
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST
);
$this->passwordResetRequestEventCreate(
\Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST
);
$this->getRequest()->setPostValue(['customer_id' => '1'])->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertSessionMessages(
$this->equalTo(['The customer will receive an email with a link to reset password.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringStartsWith($this->baseControllerUrl . 'edit'));
}
/**
* Create and save reset request event with provided request type.
*
* @param int $requestType
*/
private function passwordResetRequestEventCreate($requestType)
{
$passwordResetRequestEventFactory = $this->_objectManager->get(
\Magento\Security\Model\PasswordResetRequestEventFactory::class
);
$passwordResetRequestEvent = $passwordResetRequestEventFactory->create();
$passwordResetRequestEvent
->setRequestType($requestType)
->setAccountReference('customer@example.com')
->setCreatedAt(strtotime('now'))
->setIp('3232249856')
->save();
}
}
@@ -0,0 +1,672 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Backend\Model\Session;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\CustomerNameGenerationInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\Data\Customer as CustomerData;
use Magento\Customer\Model\EmailNotification;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Mail\TransportInterface;
use Magento\Framework\Message\MessageInterface;
use Magento\Newsletter\Model\Subscriber;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractBackendController;
use PHPUnit\Framework\MockObject\MockObject;
/**
* Tests for save customer via backend/customer/index/save controller.
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SaveTest extends AbstractBackendController
{
/**
* @var string
*/
private $baseControllerUrl = 'backend/customer/index/';
/** @var CustomerRepositoryInterface */
private $customerRepository;
/**@var CustomerNameGenerationInterface */
private $customerViewHelper;
/** @var SubscriberFactory */
private $subscriberFactory;
/** @var Session */
private $session;
/** @var StoreManagerInterface */
private $storeManager;
/** @var ResolverInterface */
private $localeResolver;
/** @var CustomerInterface */
private $customer;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->customerViewHelper = $this->_objectManager->get(CustomerNameGenerationInterface::class);
$this->subscriberFactory = $this->_objectManager->get(SubscriberFactory::class);
$this->session = $this->_objectManager->get(Session::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->localeResolver = $this->_objectManager->get(ResolverInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if ($this->customer instanceof CustomerInterface) {
$this->customerRepository->delete($this->customer);
}
parent::tearDown();
}
/**
* Create customer
*
* @dataProvider createCustomerProvider
* @magentoDbIsolation enabled
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testCreateCustomer(array $postData, array $expectedData): void
{
$this->dispatchCustomerSave($postData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the customer.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/'));
$this->assertCustomerData(
$postData['customer'][CustomerData::EMAIL],
(int)$postData['customer'][CustomerData::WEBSITE_ID],
$expectedData
);
}
/**
* Create customer provider
*
* @return array
*/
public function createCustomerProvider(): array
{
$defaultCustomerData = $this->getDefaultCustomerData();
$expectedCustomerData = $this->getExpectedCustomerData($defaultCustomerData);
return [
"fill_all_fields" => [
'post_data' => $defaultCustomerData,
'expected_data' => $expectedCustomerData
],
'only_require_fields' => [
'post_data' => array_replace_recursive(
$defaultCustomerData,
[
'customer' => [
CustomerData::DISABLE_AUTO_GROUP_CHANGE => '0',
CustomerData::PREFIX => '',
CustomerData::MIDDLENAME => '',
CustomerData::SUFFIX => '',
CustomerData::DOB => '',
CustomerData::TAXVAT => '',
CustomerData::GENDER => '',
],
]
),
'expected_data' => array_replace_recursive(
$expectedCustomerData,
[
'customer' => [
CustomerData::DISABLE_AUTO_GROUP_CHANGE => '0',
CustomerData::PREFIX => '',
CustomerData::MIDDLENAME => '',
CustomerData::SUFFIX => '',
CustomerData::DOB => '',
CustomerData::TAXVAT => '',
CustomerData::GENDER => '0',
],
]
),
],
];
}
/**
* Create customer with exceptions
*
* @dataProvider createCustomerErrorsProvider
* @magentoDbIsolation enabled
*
* @param array $postData
* @param array $expectedData
* @param array $expectedMessage
* @return void
*/
public function testCreateCustomerErrors(array $postData, array $expectedData, array $expectedMessage): void
{
$this->dispatchCustomerSave($postData);
$this->assertSessionMessages(
$this->equalTo($expectedMessage),
MessageInterface::TYPE_ERROR
);
$customerFormData = $this->session->getCustomerFormData();
$this->assertNotEmpty($customerFormData);
unset($customerFormData['form_key']);
$this->assertEquals($expectedData, $customerFormData);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'new/key/'));
}
/**
* Create customer errors provider
*
* @return array
*/
public function createCustomerErrorsProvider(): array
{
$defaultCustomerData = $this->getDefaultCustomerData();
return [
'without_some_require_fields' => [
'post_data' => array_replace_recursive(
$defaultCustomerData,
[
'customer' => [
CustomerData::FIRSTNAME => '',
CustomerData::LASTNAME => '',
],
]
),
'expected_data' => array_replace_recursive(
$defaultCustomerData,
[
'customer' => [
CustomerData::FIRSTNAME => '',
CustomerData::LASTNAME => '',
CustomerData::DOB => '2000-01-01',
],
]
),
'expected_message' => [
(string)__('"%1" is a required value.', 'First Name'),
(string)__('"%1" is a required value.', 'Last Name'),
],
],
'with_empty_post_data' => [
'post_data' => [],
'expected_data' => [],
'expected_message' => [
(string)__('The customer email is missing. Enter and try again.'),
],
],
'with_invalid_form_data' => [
'post_data' => [
'account' => [
'middlename' => 'test middlename',
'group_id' => 1,
],
],
'expected_data' => [
'account' => [
'middlename' => 'test middlename',
'group_id' => 1,
],
],
'expected_message' => [
(string)__('The customer email is missing. Enter and try again.'),
],
]
];
}
/**
* Update customer with exceptions
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testUpdateCustomerErrors(): void
{
$postData = [
'customer' => [
CustomerData::FIRSTNAME => 'John',
CustomerData::LASTNAME => 'Doe',
],
'subscription' => '1',
];
$expectedMessages = [(string)__('Something went wrong while saving the customer.')];
$postData['customer']['entity_id'] = -1;
$params = ['back' => true];
$this->dispatchCustomerSave($postData, $params);
$this->assertSessionMessages(
$this->equalTo($expectedMessages),
MessageInterface::TYPE_ERROR
);
}
/**
* Update customer with subscription and redirect to edit page.
*
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testUpdateCustomer(): void
{
/** @var CustomerData $customerData */
$customerData = $this->customerRepository->getById(1);
$secondStore = $this->storeManager->getStore('fixturestore');
$postData = $expectedData = [
'customer' => [
CustomerData::FIRSTNAME => 'Jane',
CustomerData::MIDDLENAME => 'Mdl',
CustomerData::LASTNAME => 'Doe',
],
'subscription_status' => [$customerData->getWebsiteId() => '1'],
'subscription_store' => [$customerData->getWebsiteId() => $secondStore->getId()],
];
$postData['customer']['entity_id'] = $customerData->getId();
$params = ['back' => true];
$this->dispatchCustomerSave($postData, $params);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the customer.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains(
$this->baseControllerUrl . 'edit/id/' . $customerData->getId()
));
$this->assertCustomerData($customerData->getEmail(), (int)$customerData->getWebsiteId(), $expectedData);
$this->assertCustomerSubscription(
(int)$customerData->getId(),
(int)$customerData->getWebsiteId(),
Subscriber::STATUS_SUBSCRIBED,
(int)$secondStore->getId()
);
}
/**
* @magentoDataFixture Magento/Newsletter/_files/subscribers.php
* @return void
*/
public function testExistingCustomerUnsubscribeNewsletter(): void
{
/** @var CustomerData $customerData */
$customerData = $this->customerRepository->getById(1);
/** @var Store $defaultStore */
$defaultStore = $this->storeManager->getWebsite()->getDefaultStore();
$postData = [
'customer' => [
'entity_id' => $customerData->getId(),
CustomerData::EMAIL => 'customer@example.com',
CustomerData::FIRSTNAME => 'test firstname',
CustomerData::LASTNAME => 'test lastname',
'sendemail_store_id' => '1'
],
'subscription_status' => [$customerData->getWebsiteId() => '0'],
'subscription_store' => [$customerData->getWebsiteId() => $defaultStore->getId()],
];
$this->dispatchCustomerSave($postData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the customer.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/'));
$this->assertCustomerSubscription(
(int)$customerData->getId(),
(int)$customerData->getWebsiteId(),
Subscriber::STATUS_UNSUBSCRIBED,
(int)$defaultStore->getId()
);
}
/**
* Ensure that an email is sent during save action
*
* @magentoConfigFixture current_store customer/account_information/change_email_template change_email_template
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
* @return void
*/
public function testExistingCustomerChangeEmail(): void
{
$customerId = 1;
$newEmail = 'newcustomer@example.com';
$transportBuilderMock = $this->prepareEmailMock(
2,
'change_email_template',
[
'name' => 'CustomerSupport',
'email' => 'support@example.com',
],
$customerId,
$newEmail
);
$this->addEmailMockToClass($transportBuilderMock, EmailNotification::class);
$postData = [
'customer' => [
'entity_id' => $customerId,
CustomerData::WEBSITE_ID => '1',
CustomerData::GROUP_ID => '1',
CustomerData::FIRSTNAME => 'test firstname',
CustomerData::MIDDLENAME => 'test middlename',
CustomerData::LASTNAME => 'test lastname',
CustomerData::EMAIL => $newEmail,
'new_password' => 'auto',
'sendemail_store_id' => '1',
'sendemail' => '1',
CustomerData::CREATED_AT => '2000-01-01 00:00:00',
CustomerData::DEFAULT_SHIPPING => '1',
CustomerData::DEFAULT_BILLING => '1'
]
];
$this->dispatchCustomerSave($postData);
/**
* Check that no errors were generated and set to session
*/
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/'));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
* @return void
*/
public function testCreateSameEmailFormatDateError(): void
{
$postData = [
'customer' => [
CustomerData::WEBSITE_ID => '1',
CustomerData::FIRSTNAME => 'test firstname',
CustomerData::MIDDLENAME => 'test middlename',
CustomerData::LASTNAME => 'test lastname',
CustomerData::EMAIL => 'customer@example.com',
CustomerData::DOB => '12/3/1996',
],
];
$postFormatted = array_replace_recursive(
$postData,
[
'customer' => [
CustomerData::DOB => '1996-12-03',
],
]
);
$this->dispatchCustomerSave($postData);
$this->assertSessionMessages(
$this->equalTo([
(string)__('A customer with the same email address already exists in an associated website.'),
]),
MessageInterface::TYPE_ERROR
);
$customerFormData = $this->session->getCustomerFormData();
$this->assertNotEmpty($customerFormData);
unset($customerFormData['form_key']);
$this->assertEquals(
$postFormatted,
$customerFormData,
'Customer form data should be formatted'
);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'new/key/'));
}
/**
* @return void
*/
public function testCreateCustomerByAdminWithLocaleGB(): void
{
$this->localeResolver->setLocale('en_GB');
$postData = array_replace_recursive(
$this->getDefaultCustomerData(),
[
'customer' => [
CustomerData::DOB => '24/10/1990',
],
]
);
$expectedData = array_replace_recursive(
$postData,
[
'customer' => [
CustomerData::DOB => '1990-10-24',
],
]
);
unset($expectedData['customer']['sendemail_store_id']);
$this->dispatchCustomerSave($postData);
$this->assertSessionMessages(
$this->containsEqual((string)__('You saved the customer.')),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/'));
$this->assertCustomerData(
$postData['customer'][CustomerData::EMAIL],
(int)$postData['customer'][CustomerData::WEBSITE_ID],
$expectedData
);
}
/**
* Default values for customer creation
*
* @return array
*/
private function getDefaultCustomerData(): array
{
return [
'customer' => [
CustomerData::WEBSITE_ID => '1',
CustomerData::GROUP_ID => '1',
CustomerData::DISABLE_AUTO_GROUP_CHANGE => '1',
CustomerData::PREFIX => 'Mr.',
CustomerData::FIRSTNAME => 'Jane',
CustomerData::MIDDLENAME => 'Mdl',
CustomerData::LASTNAME => 'Doe',
CustomerData::SUFFIX => 'Esq.',
CustomerData::EMAIL => 'janedoe' . uniqid() . '@example.com',
CustomerData::DOB => '01/01/2000',
CustomerData::TAXVAT => '121212',
CustomerData::GENDER => Bootstrap::getObjectManager()->get(AttributeRepositoryInterface::class)
->get(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'gender')->getSource()->getOptionId('Male'),
'sendemail_store_id' => '1',
]
];
}
/**
* Expected values for customer creation
*
* @param array $defaultCustomerData
* @return array
*/
private function getExpectedCustomerData(array $defaultCustomerData): array
{
unset($defaultCustomerData['customer']['sendemail_store_id']);
return array_replace_recursive(
$defaultCustomerData,
[
'customer' => [
CustomerData::DOB => '2000-01-01',
CustomerData::STORE_ID => 1,
CustomerData::CREATED_IN => 'Default Store View',
],
]
);
}
/**
* Create or update customer using backend/customer/index/save action.
*
* @param array $postData
* @param array $params
* @return void
*/
private function dispatchCustomerSave(array $postData, array $params = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
if (!empty($params)) {
$this->getRequest()->setParams($params);
}
$this->dispatch($this->baseControllerUrl . 'save');
}
/**
* Check that customer parameters match expected values.
*
* @param string $customerEmail
* @param int $customerWebsiteId
* @param array $expectedData
* @return void
*/
private function assertCustomerData(
string $customerEmail,
int $customerWebsiteId,
array $expectedData
): void {
$this->customer = $this->customerRepository->get($customerEmail, $customerWebsiteId);
$actualCustomerArray = $this->customer->__toArray();
foreach ($expectedData['customer'] as $key => $expectedValue) {
$this->assertEquals(
$expectedValue,
$actualCustomerArray[$key],
"Invalid expected value for $key field."
);
}
}
/**
* Check that customer subscription status match expected status.
*
* @param int $customerId
* @param int $websiteId
* @param int $expectedStatus
* @param int $expectedStoreId
* @return void
*/
private function assertCustomerSubscription(
int $customerId,
int $websiteId,
int $expectedStatus,
int $expectedStoreId
): void {
$subscriber = $this->subscriberFactory->create();
$subscriber->loadByCustomer($customerId, $websiteId);
$this->assertNotEmpty($subscriber->getId());
$this->assertEquals($expectedStatus, $subscriber->getStatus());
$this->assertEquals($expectedStoreId, $subscriber->getStoreId());
}
/**
* Prepare email mock to test emails.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @param int $occurrenceNumber
* @param string $templateId
* @param array $sender
* @param int $customerId
* @param string|null $newEmail
* @return MockObject
*/
private function prepareEmailMock(
int $occurrenceNumber,
string $templateId,
array $sender,
int $customerId,
$newEmail = null
) : MockObject {
$area = Area::AREA_FRONTEND;
$customer = $this->customerRepository->getById($customerId);
$storeId = $customer->getStoreId();
$name = $this->customerViewHelper->getCustomerName($customer);
$transportMock = $this->getMockBuilder(TransportInterface::class)
->setMethods(['sendMessage'])
->getMockForAbstractClass();
$transportMock->expects($this->exactly($occurrenceNumber))
->method('sendMessage');
$transportBuilderMock = $this->getMockBuilder(TransportBuilder::class)
->disableOriginalConstructor()
->setMethods(
[
'addTo',
'setFrom',
'setTemplateIdentifier',
'setTemplateVars',
'setTemplateOptions',
'getTransport',
]
)
->getMock();
$transportBuilderMock->method('setTemplateIdentifier')
->with($templateId)
->willReturnSelf();
$transportBuilderMock->method('setTemplateOptions')
->with(['area' => $area, 'store' => $storeId])
->willReturnSelf();
$transportBuilderMock->method('setTemplateVars')
->willReturnSelf();
$transportBuilderMock->method('setFrom')
->with($sender)
->willReturnSelf();
$transportBuilderMock->method('addTo')
->with($this->logicalOr($customer->getEmail(), $newEmail), $name)
->willReturnSelf();
$transportBuilderMock->expects($this->exactly($occurrenceNumber))
->method('getTransport')
->willReturn($transportMock);
return $transportBuilderMock;
}
/**
* Add email mock to class
*
* @param MockObject $transportBuilderMock
* @param string $className
* @return void
*/
private function addEmailMockToClass(
MockObject $transportBuilderMock,
$className
): void {
$mocked = $this->_objectManager->create(
$className,
['transportBuilder' => $transportBuilderMock]
);
$this->_objectManager->addSharedInstance(
$mocked,
$className
);
}
}
@@ -0,0 +1,123 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Index;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for validation customer via backend/customer/index/validate controller.
*
* @magentoAppArea adminhtml
*/
class ValidateTest extends AbstractBackendController
{
/** @var SerializerInterface */
private $jsonSerializer;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->jsonSerializer = $this->_objectManager->get(SerializerInterface::class);
}
/**
* Validate customer with exception
*
* @magentoDbIsolation enabled
* @return void
*/
public function testValidateCustomerErrors(): void
{
$postData = [
'customer' => [],
];
$attributeEmptyMessage = 'The "%1" attribute value is empty. Set the attribute and try again.';
$expectedErrors = [
'error' => true,
'messages' => [
(string)__($attributeEmptyMessage, 'First Name'),
(string)__($attributeEmptyMessage, 'Last Name'),
(string)__($attributeEmptyMessage, 'Email'),
],
];
$this->dispatchCustomerValidate($postData);
$errors = $this->jsonSerializer->unserialize($this->getResponse()->getBody());
$this->assertEquals($expectedErrors, $errors);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @return void
*/
public function testValidateCustomerWithAddressSuccess(): void
{
$customerData = [
'customer' => [
'entity_id' => '1',
'middlename' => 'new middlename',
'group_id' => 1,
'website_id' => 1,
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@domain.com',
'default_shipping' => '_item1',
'new_password' => 'auto',
'sendemail_store_id' => '1',
'sendemail' => '1',
],
'address' => [
'_item1' => [
'firstname' => 'update firstname',
'lastname' => 'update lastname',
'street' => ['update street'],
'city' => 'update city',
'country_id' => 'US',
'region_id' => 10,
'postcode' => '01001',
'telephone' => '+7000000001',
],
'_template_' => [
'firstname' => '',
'lastname' => '',
'street' => [],
'city' => '',
'country_id' => 'US',
'postcode' => '',
'telephone' => '',
],
],
];
$this->dispatchCustomerValidate($customerData);
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR);
$errors = $this->jsonSerializer->unserialize($this->getResponse()->getBody());
$this->assertEquals(['error' => 0], $errors);
}
/**
* Validate customer using backend/customer/index/validate action.
*
* @param array $postData
* @return void
*/
private function dispatchCustomerValidate(array $postData): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/customer/index/validate');
}
}
@@ -0,0 +1,305 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller\Adminhtml;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\Session;
use Magento\Customer\Api\CustomerNameGenerationInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\EmailNotification;
use Magento\Framework\Acl\Builder;
use Magento\Framework\App\Area;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Mail\TransportInterface;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Bootstrap;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\TestFramework\TestCase\AbstractBackendController;
use PHPUnit\Framework\MockObject\MockObject;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class IndexTest extends AbstractBackendController
{
/**
* @var string
*/
private $baseControllerUrl = 'backend/customer/index/';
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var CustomerNameGenerationInterface */
private $customerViewHelper;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$this->customerViewHelper = $this->_objectManager->get(CustomerNameGenerationInterface::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
/**
* Unset customer data
*/
$this->_objectManager->get(Session::class)->setCustomerData(null);
/**
* Unset messages
*/
$this->_objectManager->get(Session::class)->getMessages(true);
}
/**
* Ensure that an email is sent during inlineEdit action
*
* @magentoConfigFixture current_store customer/account_information/change_email_template change_email_template
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
*/
public function testInlineEditChangeEmail()
{
$customerId = 1;
$newEmail = 'newcustomer@example.com';
$transportBuilderMock = $this->prepareEmailMock(
2,
'change_email_template',
[
'name' => 'CustomerSupport',
'email' => 'support@example.com',
],
$customerId,
$newEmail
);
$this->addEmailMockToClass($transportBuilderMock, EmailNotification::class);
$post = [
'items' => [
$customerId => [
'middlename' => 'test middlename',
'group_id' => 1,
'website_id' => 1,
'firstname' => 'test firstname',
'lastname' => 'test lastname',
'email' => $newEmail,
'password' => 'password',
],
]
];
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true);
$this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/inlineEdit');
/**
* Check that no errors were generated and set to session
*/
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
*/
public function testEditAction()
{
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
// verify
$this->assertStringContainsString('<h1 class="page-title">test firstname test lastname</h1>', $body);
}
/**
* Test new customer form page.
*/
public function testNewAction()
{
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
// verify
$this->assertStringContainsString('<h1 class="page-title">New Customer</h1>', $body);
}
/**
* Test the editing of a new customer that has not been saved but the page has been reloaded
*/
public function te1stNewActionWithCustomerData()
{
$customerData = [
'customer_id' => 0,
'customer' => [
'created_in' => false,
'disable_auto_group_change' => false,
'email' => false,
'firstname' => false,
'group_id' => false,
'lastname' => false,
'website_id' => false,
'customer_address' => [],
],
];
$context = BootstrapHelper::getObjectManager()->get(Context::class);
$context->getBackendSession()->setCustomerData($customerData);
$this->testNewAction();
}
/**
* @magentoDbIsolation enabled
*/
public function testResetPasswordActionNoCustomerId()
{
// No customer ID in post, will just get redirected to base
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertRedirect($this->stringContains($this->baseControllerUrl));
}
/**
* @magentoDbIsolation enabled
*/
public function testResetPasswordActionBadCustomerId()
{
// Bad customer ID in post, will just get redirected to base
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->getRequest()->setPostValue(['customer_id' => '789']);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertRedirect($this->stringContains($this->baseControllerUrl));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testResetPasswordActionSuccess()
{
$this->getRequest()->setPostValue(['customer_id' => '1']);
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('backend/customer/index/resetPassword');
$this->assertSessionMessages(
$this->equalTo(['The customer will receive an email with a link to reset password.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains($this->baseControllerUrl . 'edit'));
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testAclDeleteActionAllow()
{
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('Delete Customer', $body);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testAclDeleteActionDeny()
{
$resource= 'Magento_Customer::delete';
$this->_objectManager->get(Builder::class)
->getAcl()
->deny(Bootstrap::ADMIN_ROLE_ID, $resource);
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
$this->assertStringNotContainsString('Delete Customer', $body);
}
/**
* Prepare email mock to test emails.
*
* @param int $occurrenceNumber
* @param string $templateId
* @param array $sender
* @param int $customerId
* @param string|null $newEmail
* @return MockObject
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
protected function prepareEmailMock(
int $occurrenceNumber,
string $templateId,
array $sender,
int $customerId,
$newEmail = null
) : MockObject {
$area = Area::AREA_FRONTEND;
$customer = $this->customerRepository->getById($customerId);
$storeId = $customer->getStoreId();
$name = $this->customerViewHelper->getCustomerName($customer);
$transportMock = $this->getMockBuilder(TransportInterface::class)
->setMethods(['sendMessage'])
->getMockForAbstractClass();
$transportMock->expects($this->exactly($occurrenceNumber))
->method('sendMessage');
$transportBuilderMock = $this->getMockBuilder(TransportBuilder::class)
->disableOriginalConstructor()
->setMethods(
[
'addTo',
'setFrom',
'setTemplateIdentifier',
'setTemplateVars',
'setTemplateOptions',
'getTransport',
]
)
->getMock();
$transportBuilderMock->method('setTemplateIdentifier')
->with($templateId)
->willReturnSelf();
$transportBuilderMock->method('setTemplateOptions')
->with(['area' => $area, 'store' => $storeId])
->willReturnSelf();
$transportBuilderMock->method('setTemplateVars')
->willReturnSelf();
$transportBuilderMock->method('setFrom')
->with($sender)
->willReturnSelf();
$transportBuilderMock->method('addTo')
->with($this->logicalOr($customer->getEmail(), $newEmail), $name)
->willReturnSelf();
$transportBuilderMock->expects($this->exactly($occurrenceNumber))
->method('getTransport')
->willReturn($transportMock);
return $transportBuilderMock;
}
/**
* @param MockObject $transportBuilderMock
* @param string $className
*/
protected function addEmailMockToClass(
MockObject $transportBuilderMock,
$className
) {
$mocked = $this->_objectManager->create(
$className,
['transportBuilder' => $transportBuilderMock]
);
$this->_objectManager->addSharedInstance(
$mocked,
$className
);
}
}
@@ -0,0 +1,151 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Adminhtml\Wishlist\Product\Composite\Wishlist;
use Magento\Backend\Model\Session;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\TestFramework\Wishlist\Model\GetWishlistByCustomerId;
use Magento\Wishlist\Model\Item;
/**
* Tests for update wish list items.
*
* @magentoAppArea adminhtml
*/
class UpdateTest extends AbstractBackendController
{
/** @var GetWishlistByCustomerId */
private $getWishlistByCustomerId;
/** @var SerializerInterface */
private $json;
/** @var Session */
private $session;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->getWishlistByCustomerId = $this->_objectManager->get(GetWishlistByCustomerId::class);
$this->json = $this->_objectManager->get(SerializerInterface::class);
$this->session = $this->_objectManager->get(Session::class);
}
/**
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testUpdateItem(): void
{
$item = $this->getWishlistByCustomerId->getItemBySku(1, 'simple-1');
$this->assertNotNull($item);
$params = ['id' => $item->getId(), 'qty' => 5];
$this->dispatchUpdateItemRequest($params);
$this->assertEquals($params['qty'], $this->getWishlistByCustomerId->getItemBySku(1, 'simple-1')->getQty());
}
/**
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_configurable_product.php
* @magentoDbIsolation disabled
*
* @return void
*/
public function testUpdateItemOption(): void
{
$item = $this->getWishlistByCustomerId->getItemBySku(1, 'Configurable product');
$this->assertNotNull($item);
$params = [
'id' => $item->getId(),
'super_attribute' => $this->performConfigurableOption($item->getProduct()),
'qty' => 5,
];
$this->dispatchUpdateItemRequest($params);
$this->assertUpdatedItem(
$this->getWishlistByCustomerId->getItemBySku(1, 'Configurable product'),
$params
);
}
/**
* @return void
*/
public function testUpdateNotExistingItem(): void
{
$this->dispatchUpdateItemRequest(['id' => 989]);
$this->assertTrue($this->session->getCompositeProductResult()->getError());
$this->assertEquals(
(string)__('Please load Wish List item.'),
$this->session->getCompositeProductResult()->getMessage()
);
}
/**
* @return void
*/
public function testUpdateWithoutParams(): void
{
$this->dispatchUpdateItemRequest([]);
$this->assertTrue($this->session->getCompositeProductResult()->getError());
$this->assertEquals(
(string)__('Please define Wish List item ID.'),
$this->session->getCompositeProductResult()->getMessage()
);
}
/**
* Assert updated item in wish list.
*
* @param Item $item
* @param array $expectedData
* @return void
*/
private function assertUpdatedItem(Item $item, array $expectedData): void
{
$this->assertEquals($expectedData['qty'], $item->getQty());
$buyRequestOption = $this->json->unserialize($item->getOptionByCode('info_buyRequest')->getValue());
foreach ($expectedData as $key => $value) {
$this->assertEquals($value, $buyRequestOption[$key]);
}
}
/**
* Perform configurable option to select.
*
* @param ProductInterface $product
* @return array
*/
private function performConfigurableOption(ProductInterface $product): array
{
$configurableOptions = $product->getTypeInstance()->getConfigurableOptions($product);
$attributeId = key($configurableOptions);
$option = reset($configurableOptions[$attributeId]);
return [$attributeId => $option['value_index']];
}
/**
* Dispatch update wish list item request.
*
* @param array $params
* @return void
*/
private function dispatchUpdateItemRequest(array $params): void
{
$this->getRequest()->setParams($params)->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/customer/wishlist_product_composite_wishlist/update');
$this->assertRedirect($this->stringContains('backend/catalog/product/showUpdateResult/'));
}
}
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Controller;
use Magento\TestFramework\Helper\Bootstrap;
class AjaxLoginTest extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* Login the user
*
* @param string $customerId Customer to mark as logged in for the session
* @return void
*/
protected function login($customerId)
{
/** @var \Magento\Customer\Model\Session $session */
$session = Bootstrap::getObjectManager()
->get(\Magento\Customer\Model\Session::class);
$session->loginById($customerId);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testLogoutAction()
{
$this->login(1);
$this->dispatch('customer/ajax/logout');
$body = $this->getResponse()->getBody();
$logoutMessage = Bootstrap::getObjectManager()->get(
\Magento\Framework\Json\Helper\Data::class
)->jsonDecode($body);
$this->assertStringContainsString('Logout Successful', $logoutMessage['message']);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller;
use Magento\Customer\Controller\Plugin\Account as AccountPlugin;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Set of Tests to verify that Authentication methods work properly
*/
class AuthenticationTest extends AbstractController
{
/**
* Make sure that customized AccountPlugin was reverted.
*/
protected function tearDown(): void
{
$this->resetAllowedActions();
parent::tearDown();
}
/**
* After changes to `di.xml` and overriding list of allowed actions, unallowed ones should cause redirect.
*/
public function testExpectRedirectResponseWhenDispatchNotAllowedAction()
{
$this->overrideAllowedActions(['notExistingRoute']);
$this->dispatch('customer/account/create');
$this->assertRedirect($this->stringContains('customer/account/login'));
}
/**
* Allowed actions should be rendered normally
*/
public function testExpectPageResponseWhenAllowedAction()
{
$this->overrideAllowedActions(['create']);
$this->dispatch('customer/account/create');
$this->assertEquals(200, $this->getResponse()->getStatusCode());
}
/**
* Overrides list of `allowedActions` for Authorization Plugin
*
* @param string[] $allowedActions
* @see \Magento\Customer\Controller\Plugin\Account
*/
private function overrideAllowedActions(array $allowedActions): void
{
$allowedActions = array_combine($allowedActions, $allowedActions);
$pluginFake = $this->_objectManager->create(AccountPlugin::class, ['allowedActions' => $allowedActions]);
$this->_objectManager->addSharedInstance($pluginFake, AccountPlugin::class);
}
/**
* Removes all the customizations applied to `allowedActions`
* @see \Magento\Customer\Controller\Plugin\Account
*/
private function resetAllowedActions()
{
$this->_objectManager->removeSharedInstance(AccountPlugin::class);
}
}
@@ -0,0 +1,169 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\ResourceModel\Customer as CustomerResource;
use Magento\Customer\Model\Session;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Math\Random;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Class checks password forgot scenarios
*
* @magentoDbIsolation enabled
*/
class CreatePasswordTest extends AbstractController
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Session */
private $session;
/** @var LayoutInterface */
private $layout;
/** @var Random */
private $random;
/** @var CustomerResource */
private $customerResource;
/** @var CustomerRegistry */
private $customerRegistry;
/** @var DateTimeFactory */
private $dateTimeFactory;
/** @var WebsiteRepositoryInterface */
private $websiteRepository;
/** @var int */
private $customerId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->session = $this->objectManager->get(Session::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->random = $this->objectManager->get(Random::class);
$this->customerResource = $this->objectManager->get(CustomerResource::class);
$this->customerRegistry = $this->objectManager->get(CustomerRegistry::class);
$this->dateTimeFactory = $this->objectManager->get(DateTimeFactory::class);
$this->websiteRepository = $this->objectManager->get(WebsiteRepositoryInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerRegistry->remove($this->customerId);
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_with_website.php
*
* @return void
*/
public function testCreatePassword(): void
{
$defaultWebsite = $this->websiteRepository->get('base')->getId();
$customer = $this->customerRegistry->retrieveByEmail('john.doe@magento.com', $defaultWebsite);
$this->customerId = $customer->getId();
$token = $this->random->getUniqueHash();
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$this->customerResource->save($customer);
$this->session->setRpToken($token);
$this->session->setRpCustomerId($customer->getId());
$this->dispatch('customer/account/createPassword');
$block = $this->layout->getBlock('resetPassword');
$this->assertEquals($token, $block->getResetPasswordLinkToken());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_with_website.php
*
* @return void
*/
public function testTokenHasExpired(): void
{
$defaultWebsite = $this->websiteRepository->get('base')->getId();
$customer = $this->customerRegistry->retrieveByEmail('john.doe@magento.com', $defaultWebsite);
$this->customerId = $customer->getId();
$token = $this->random->getUniqueHash();
$tooLongAgo = $this->dateTimeFactory->create()
->sub(\DateInterval::createFromDateString('1 month'))
->format(DateTime::DATETIME_PHP_FORMAT);
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$customerSecure = $this->customerRegistry->retrieveSecureData($this->customerId);
$customerSecure->setRpTokenCreatedAt($tooLongAgo);
$this->customerResource->save($customer);
$this->session->setRpToken($token);
$this->session->setRpCustomerId($this->customerId);
$this->dispatch('customer/account/createPassword');
$this->assertRedirect($this->stringContains('customer/account/forgotpassword'));
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_with_website.php
*
* @return void
*/
public function testTokenExtendedOnPageLoad(): void
{
$defaultWebsite = $this->websiteRepository->get('base')->getId();
$customer = $this->customerRegistry->retrieveByEmail('john.doe@magento.com', $defaultWebsite);
$this->customerId = $customer->getId();
$token = $this->random->getUniqueHash();
$anHourAgo = $this->dateTimeFactory->create()
->sub(\DateInterval::createFromDateString('1 hour'))
->format(DateTime::DATETIME_PHP_FORMAT);
$customer->changeResetPasswordLinkToken($token);
$customer->setData('confirmation', 'confirmation');
$customerSecure = $this->customerRegistry->retrieveSecureData($this->customerId);
$customerSecure->setRpTokenCreatedAt($anHourAgo);
$this->customerResource->save($customer);
$this->session->setRpToken($token);
$this->session->setRpCustomerId($this->customerId);
$this->dispatch('customer/account/createPassword');
$block = $this->layout->getBlock('resetPassword');
$this->assertEquals($token, $block->getResetPasswordLinkToken());
$customerSecure = $this->customerRegistry->retrieveSecureData($this->customerId);
$this->assertNotEquals($anHourAgo, $customerSecure->getRpTokenCreatedAt());
}
}
@@ -0,0 +1,595 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller;
use Magento\Config\Model\ResourceModel\Config as CoreConfig;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\ResourceModel\Customer as CustomerResource;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Http;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Math\Random;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\Stdlib\DateTime;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\Request;
use Magento\TestFramework\TestCase\AbstractController;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Theme\Controller\Result\MessagePlugin;
/**
* Class checks password forgot scenarios
*
* @see \Magento\Customer\Controller\Account\ForgotPasswordPost
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ForgotPasswordPostTest extends AbstractController
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var TransportBuilderMock */
private $transportBuilderMock;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var CoreConfig
*/
protected $resourceConfig;
/**
* @var ReinitableConfigInterface
*/
private $reinitableConfig;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var DateTimeFactory
*/
private $dateTimeFactory;
/**
* @var CustomerResource
*/
private $customerResource;
/**
* @var Random
*/
private $random;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->transportBuilderMock = $this->objectManager->get(TransportBuilderMock::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$this->searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$this->resourceConfig = $this->_objectManager->get(CoreConfig::class);
$this->reinitableConfig = $this->_objectManager->get(ReinitableConfigInterface::class);
$this->scopeConfig = Bootstrap::getObjectManager()->get(ScopeConfigInterface::class);
$this->dateTimeFactory = $this->objectManager->get(DateTimeFactory::class);
$this->customerResource = $this->objectManager->get(CustomerResource::class);
$this->random = $this->objectManager->get(Random::class);
}
/**
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @return void
*/
public function testWithoutEmail(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['email' => '']);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertSessionMessages(
$this->equalTo([(string)__('Please enter your email.')]),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('customer/account/forgotpassword'));
}
/**
* Test that forgot password email message displays special characters correctly.
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 0
* @codingStandardsIgnoreStart
* @magentoConfigFixture current_store customer/password/forgot_email_template customer_password_forgot_email_template
* @codingStandardsIgnoreEnd
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoConfigFixture current_store general/store_information/name Test special' characters
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testForgotPasswordEmailMessageWithSpecialCharacters(): void
{
$email = 'customer@example.com';
$this->getRequest()->setPostValue(['email' => $email]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSuccessSessionMessage($email);
$subject = $this->transportBuilderMock->getSentMessage()->getSubject();
$this->assertStringContainsString('Test special\' characters', $subject);
}
/**
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 0
* @codingStandardsIgnoreStart
* @magentoConfigFixture current_store customer/password/forgot_email_template customer_password_forgot_email_template
* @codingStandardsIgnoreEnd
* @magentoConfigFixture current_store customer/password/forgot_email_identity support
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testForgotPasswordPostAction(): void
{
$email = 'customer@example.com';
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['email' => $email]);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$this->assertSuccessSessionMessage($email);
}
/**
* @magentoConfigFixture current_store customer/captcha/enable 0
*
* @return void
*/
public function testForgotPasswordPostWithBadEmailAction(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['email' => 'bad@email']);
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/forgotpassword'));
$this->assertSessionMessages(
$this->equalTo(['The email address is incorrect. Verify the email address and try again.']),
MessageInterface::TYPE_ERROR
);
}
/**
* Assert success session message
*
* @param string $email
* @return void
*/
private function assertSuccessSessionMessage(string $email): void
{
$message = __(
'If there is an account associated with %1 you will receive an email with a link to reset your password.',
$email
);
$this->assertSessionMessages($this->equalTo([$message]), MessageInterface::TYPE_SUCCESS);
}
/**
* @magentoConfigFixture current_store customer/password/password_reset_protection_type 0
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testDisableLimitOfResetRequests(): void
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchResults = $this->customerRepository->getList($searchCriteria);
foreach ($searchResults->getItems() as $customer) {
$customAttributes = $customer->getCustomAttributes();
$numberOfRequests = $customAttributes['max_number_password_reset_requests'] ?? null;
$this->assertNull($numberOfRequests);
}
$email = 'customer@example.com';
$this->getRequest()->setPostValue(['email' => $email]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
for ($i = 0; $i < 10; $i++) {
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
$sendMessage = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent();
$this->assertStringContainsString(
'There was recently a request to change the password for your account',
$sendMessage
);
$this->assertSessionMessages(
$this->equalTo([]),
MessageInterface::TYPE_ERROR
);
}
}
/**
* Test to check reset password link send after forgot password link is click
*
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
* @throws NoSuchEntityException
*/
public function testResetLinkSentAfterForgotPassword(): void
{
$email = 'customer@example.com';
// Getting and asserting actual default expiration period
$defaultExpirationPeriod = 2;
$actualExpirationPeriod = (int) $this->scopeConfig->getValue(
'customer/password/reset_link_expiration_period',
\Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE
);
$this->assertEquals(
$defaultExpirationPeriod,
$actualExpirationPeriod
);
// Updating reset_link_expiration_period to 1 under customer configuration
$this->resourceConfig->saveConfig(
'customer/password/reset_link_expiration_period',
1,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
// Click forgot password link and assert mail received with reset password link
$this->clickForgotPasswordAndAssertResetLinkReceivedInMail($email);
}
/**
* Test to check reset password link expired by timeout
*
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @depends testResetLinkSentAfterForgotPassword
* @return void
* @throws NoSuchEntityException
* @throws AlreadyExistsException
* @throws AuthenticationException
* @throws LocalizedException
*/
public function testResetLinkExpirationByTimeout(): void
{
$this->reinitableConfig->reinit();
$email = 'customer@example.com';
// Generating random reset password token
$rpData = $this->generateResetPasswordToken($email);
// Resetting request and clearing cookie message
$this->resetRequest();
$this->clearCookieMessagesList();
// Setting token and customer id to session
/** @var Session $customer */
$session = Bootstrap::getObjectManager()->get(Session::class);
$session->setRpToken($rpData['token']);
$session->setRpCustomerId($rpData['customerId']);
// Click on the reset password link and assert no expiration error message received
$this->clickResetPasswordLink($rpData['token'], $rpData['customerId']);
$this->assertSessionMessages(
$this->equalTo([]),
MessageInterface::TYPE_ERROR
);
// Updating reset password created date
$this->updateResetPasswordCreatedDateAndTime($email, $rpData['customerId']);
// Clicking on the reset password link
$this->clickResetPasswordLink($rpData['token'], $rpData['customerId']);
// Asserting failed message after link expire
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
MessageInterface::TYPE_ERROR
);
}
/**
* Test to check reset password link expired after forgot password is click
*
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 0
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @depends testResetLinkExpirationByTimeout
* @return void
* @throws NoSuchEntityException
* @throws AlreadyExistsException
* @throws AuthenticationException
* @throws LocalizedException
*/
public function testExpiredResetPasswordLinkAfterForgotPassword(): void
{
$email = 'customer@example.com';
// Click forgot password link and assert mail received with reset password link
$this->clickForgotPasswordAndAssertResetLinkReceivedInMail($email);
// Generating random reset password token
$rpData = $this->generateResetPasswordToken($email);
// Resetting request and clearing cookie message
$this->resetRequest();
$this->clearCookieMessagesList();
// Updating reset password created date
$this->updateResetPasswordCreatedDateAndTime($email, $rpData['customerId']);
// Clicking on the reset password link
$this->clickResetPasswordLink($rpData['token'], $rpData['customerId']);
// Asserting failed message after link expire
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
MessageInterface::TYPE_ERROR
);
}
/**
* Function to generate random reset password token
*
* @param string $email
* @return array
* @throws AlreadyExistsException
* @throws AuthenticationException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
private function generateResetPasswordToken($email): array
{
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$customerData = $customerRegistry->retrieveByEmail($email);
$token = $this->random->getUniqueHash();
$customerData->changeResetPasswordLinkToken($token);
$customerData->setData('confirmation', 'confirmation');
$customerData->save();
$customerId = $customerData->getId();
return [
'token' => $token,
'customerId' => $customerId
];
}
/**
* Function to update the value of rp_token_created_at field in customer_entity table.
*
* @param string $email
* @param int $customerId
* @return void
* @throws AlreadyExistsException
* @throws NoSuchEntityException
*/
private function updateResetPasswordCreatedDateAndTime($email, $customerId): void
{
$rpTokenCreatedAt = $this->dateTimeFactory->create()
->sub(\DateInterval::createFromDateString('2 hour'))
->format(DateTime::DATETIME_PHP_FORMAT);
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$customerData = $customerRegistry->retrieveByEmail($email);
$customerSecure = $customerRegistry->retrieveSecureData($customerId);
$customerSecure->setRpTokenCreatedAt($rpTokenCreatedAt);
$this->customerResource->save($customerData);
}
/**
* Function to click on the reset password link.
*
* @param string $token
* @param int $customerId
* @return void
*/
private function clickResetPasswordLink($token, $customerId): void
{
$this->getRequest()->setParam('token', $token)->setParam('id', $customerId);
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('customer/account/createPassword');
}
/**
* Function to click on forgot password and assert reset link received in the mail
*
* @param string $email
* @return void
* @throws NoSuchEntityException
*/
private function clickForgotPasswordAndAssertResetLinkReceivedInMail($email): void
{
$this->getRequest()->setPostValue(['email' => $email]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
// Click on the forgot password link
$this->dispatch('customer/account/forgotPasswordPost');
$this->assertRedirect($this->stringContains('customer/account/'));
// Asserting the success message after forgot password
$this->assertSessionMessages(
$this->equalTo(
[
"If there is an account associated with {$email} you will receive an email with a link "
. "to reset your password."
]
),
MessageInterface::TYPE_SUCCESS
);
// Asserting mail received after forgot password
$sendMessage = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent();
$this->assertStringContainsString(
'There was recently a request to change the password for your account',
$sendMessage
);
// Getting reset password token and customer id from the database
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $this->_objectManager->get(CustomerRegistry::class);
$customerData = $customerRegistry->retrieveByEmail($email);
$token = $customerData->getRpToken();
$customerId = $customerData->getId();
// Asserting mail contains reset link
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
'//a[contains(@href, \'customer/account/createPassword/?id=%1$d&token=%2$s\')]',
$customerId,
$token
),
$sendMessage
)
);
}
/**
* Clears request.
*
* @return void
*/
protected function resetRequest(): void
{
$this->_objectManager->removeSharedInstance(Http::class);
$this->_objectManager->removeSharedInstance(Request::class);
parent::resetRequest();
}
/**
* Clear cookie messages list.
*
* @return void
*/
private function clearCookieMessagesList(): void
{
$cookieManager = $this->_objectManager->get(CookieManagerInterface::class);
$jsonSerializer = $this->_objectManager->get(Json::class);
$cookieManager->setPublicCookie(
MessagePlugin::MESSAGES_COOKIES_NAME,
$jsonSerializer->serialize([])
);
}
/**
* Test to enable password change frequency limit for customer
*
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoConfigFixture current_store customer/captcha/enable 0
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
* @throws LocalizedException
*/
public function testEnablePasswordChangeFrequencyLimitForCustomer(): void
{
$email = 'customer@example.com';
// Resetting password multiple times
for ($i = 0; $i < 5; $i++) {
$this->getRequest()->setPostValue(['email' => $email]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('customer/account/forgotPasswordPost');
}
// Asserting mail received after forgot password
$sendMessage = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent();
$this->assertStringContainsString(
'There was recently a request to change the password for your account',
$sendMessage
);
// Updating the limit to greater than 0
$this->resourceConfig->saveConfig(
'customer/password/min_time_between_password_reset_requests',
1,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
// Resetting password multiple times
for ($i = 0; $i < 5; $i++) {
$this->clearCookieMessagesList();
$this->getRequest()->setPostValue('email', $email);
$this->dispatch('customer/account/forgotPasswordPost');
}
// Asserting the error message
$this->assertSessionMessages(
$this->equalTo(
['We received too many requests for password resets.'
. ' Please wait and try again later or contact hello@example.com.']
),
MessageInterface::TYPE_ERROR
);
// Wait for 1 minute before resetting password
sleep(60);
// Clicking on the forgot password link
$this->getRequest()->setPostValue('email', $email);
$this->dispatch('customer/account/forgotPasswordPost');
// Asserting mail received after forgot password
$sendMessage = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent();
$this->assertStringContainsString(
'There was recently a request to change the password for your account',
$sendMessage
);
}
}
@@ -0,0 +1,106 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller\Section;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractController;
use Magento\Framework\Escaper;
/**
* Load customer data test class.
*
* @magentoDbIsolation disabled
* @magentoAppArea frontend
*/
class LoadTest extends AbstractController
{
/** @var Session */
private $customerSession;
/** @var SerializerInterface */
private $json;
/** @var Escaper */
private $escaper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerSession = $this->_objectManager->get(Session::class);
$this->json = $this->_objectManager->get(SerializerInterface::class);
$this->escaper = $this->_objectManager->get(Escaper::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerSession->setCustomerId(null);
parent::tearDown();
}
/**
* @return void
*/
public function testLoadInvalidSection(): void
{
$message = $this->escaper->escapeHtml('The "section<invalid" section source isn\'t supported.');
$expected = ['message' => $message];
$this->dispatch(
'/customer/section/load/?sections=section<invalid&force_new_section_timestamp=false&_=147066166394'
);
$this->assertEquals($this->json->serialize($expected), $this->getResponse()->getBody());
}
/**
* @magentoConfigFixture current_store wishlist/wishlist_link/use_qty 1
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_product_qty_three.php
*
* @return void
*/
public function testWishListCounterUseQty(): void
{
$this->customerSession->setCustomerId(1);
$response = $this->performWishListSectionRequest();
$this->assertEquals('3 items', $response['wishlist']['counter']);
}
/**
* @magentoConfigFixture current_store wishlist/wishlist_link/use_qty 0
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_product_qty_three.php
*
* @return void
*/
public function testWishListCounterNotUseQty(): void
{
$this->customerSession->setCustomerId(1);
$response = $this->performWishListSectionRequest();
$this->assertEquals('1 item', $response['wishlist']['counter']);
}
/**
* Perform wish list section request.
*
* @return array
*/
private function performWishListSectionRequest(): array
{
$this->getRequest()->setParam('sections', 'wishlist')->setMethod(HttpRequest::METHOD_GET);
$this->dispatch('customer/section/load');
return $this->json->unserialize($this->getResponse()->getBody());
}
}
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Controller;
use Magento\TestFramework\TestCase\AbstractController;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Data\Form\FormKey;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Customer\Model\Session;
use Psr\Log\LoggerInterface;
class SendTest extends AbstractController
{
/** @var AccountManagementInterface */
private $accountManagement;
/** @var FormKey */
private $formKey;
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function setUp(): void
{
parent::setUp();
$logger = $this->getMockForAbstractClass(LoggerInterface::class);
$session = Bootstrap::getObjectManager()->create(
Session::class,
[$logger]
);
$this->accountManagement = Bootstrap::getObjectManager()->create(AccountManagementInterface::class);
$this->formKey = Bootstrap::getObjectManager()->create(FormKey::class);
$customer = $this->accountManagement->authenticate('customer@example.com', 'password');
$session->setCustomerDataAsLoggedIn($customer);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testExecutePost()
{
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->formKey->getFormKey(),
'emails' => 'example1@gmail.com, example2@gmail.com, example3@gmail.com'
]
);
$this->dispatch('wishlist/index/send');
$this->assertRedirect($this->stringContains('wishlist/index/index'));
$this->assertSessionMessages(
$this->equalTo(['Your wish list has been shared.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
}
/**
* @magentoAppIsolation enabled
* @magentoConfigFixture default_store customer/captcha/enable 1
* @magentoConfigFixture default_store customer/captcha/failed_attempts_login 0
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoConfigFixture default_store customer/captcha/forms user_forgotpassword,user_login,share_wishlist_form
*
*/
public function testCaptchaFailed()
{
$this->getRequest()
->setMethod('POST')
->setPostValue(
[
'form_key' => $this->formKey->getFormKey(),
'emails' => 'example1@gmail.com, example2@gmail.com, example3@gmail.com',
'captcha' => [
'share_wishlist_form' => 'wrong_captcha_word'
]
]
);
$this->dispatch('wishlist/index/send');
$this->assertRedirect($this->stringContains('wishlist/index/share'));
$this->assertSessionMessages(
$this->equalTo(['Incorrect CAPTCHA']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
}