ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,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 => '_item1',
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');
}
}