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,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 => '_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');
}
}
@@ -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/'));
}
}