This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,83 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit;
use Magento\Backend\Model\Search\AuthorizationMock;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Authorization;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class checks Create Order button visibility
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class OrderButtonTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var OrderButton */
private $button;
/** @var Registry */
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->addSharedInstance(
$this->objectManager->get(AuthorizationMock::class),
Authorization::class
);
$this->button = $this->objectManager->get(OrderButton::class);
$this->registry = $this->objectManager->get(Registry::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
parent::tearDown();
}
/**
* @return void
*/
public function testGetButtonDataWithoutCustomer(): void
{
$this->assertEmpty($this->button->getButtonData());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testGetButtonDataWithCustomer(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$data = $this->button->getButtonData();
$this->assertNotEmpty($data);
$this->assertEquals(__('Create Order'), $data['label']);
$this->assertStringContainsString('sales/order_create/start/customer_id/1/', $data['on_click']);
}
}
@@ -0,0 +1,148 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\QuoteFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Base class for testing \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart block
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractCartTest extends TestCase
{
const CUSTOMER_ID_VALUE = 1234;
/** @var Registry */
private $registry;
/** @var Cart */
protected $block;
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var CartRepositoryInterface */
protected $quoteRepository;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var QuoteFactory */
private $quoteFactory;
/**
* @inheritdoc
*/
public function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->registerCustomerId(self::CUSTOMER_ID_VALUE);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Cart::class);
$this->quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$this->quoteFactory = $this->objectManager->get(QuoteFactory::class);
}
/**
* @inheritdoc
*/
public function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* Check that the expected items of the shopping cart are in the block
*
* @param string $customerEmail
* @return void
*/
protected function processCheckQuoteItems(string $customerEmail): void
{
$customer = $this->customerRepository->get($customerEmail);
$this->registerCustomerId((int)$customer->getId());
$this->block->toHtml();
$quoteItemIds = $this->getQuoteItemIds((int)$customer->getId());
$this->assertCount(
count($quoteItemIds),
$this->block->getPreparedCollection(),
"Item's count in the customer cart grid block doesn't match expected count."
);
$this->assertEmpty(
array_diff(
$this->block->getPreparedCollection()->getAllIds(),
$quoteItemIds
),
"Items in the customer cart grid block doesn't match expected items."
);
}
/**
* Checks that customer's shopping cart block is empty
*
* @param string $customerEmail
* @return void
*/
protected function processCheckWithoutQuoteItems(string $customerEmail): void
{
$customer = $this->customerRepository->get($customerEmail);
$this->registerCustomerId((int)$customer->getId());
$this->block->toHtml();
$this->assertCount(
0,
$this->block->getPreparedCollection(),
"Item's count in the customer cart grid block doesn't match expected count."
);
}
/**
* Add customer id to registry.
*
* @param int $customerId
* @return void
*/
private function registerCustomerId(int $customerId): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
}
/**
* Get shopping cart quote item identifiers by customer id.
*
* @param int $customerId
* @return array
*/
private function getQuoteItemIds(int $customerId): array
{
$ids = [];
/** @var Quote $quote */
$quote = $this->quoteRepository->getForCustomer($customerId);
/** @var Item $item */
foreach ($quote->getItems() as $item) {
$ids[] = $item->getId();
}
return $ids;
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\Cart;
use Magento\Customer\Block\Adminhtml\Edit\Tab\AbstractCartTest;
use Magento\Framework\Module\Manager;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\ResourceModel\Quote\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks customer's shopping cart block with bundle product.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart
* @magentoAppArea adminhtml
*/
class CartBundleTest extends AbstractCartTest
{
/** @var CollectionFactory */
private $quoteCollectionFactory;
/**
* @inheritdoc
*/
public function setUp(): void
{
parent::setUp();
$this->quoteCollectionFactory = $this->objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because Customer independent of Magento_Bundle
if (!$moduleManager->isEnabled('Magento_Bundle')) {
self::markTestSkipped('Magento_Bundle module disabled.');
}
}
/**
* @magentoDataFixture Magento/Bundle/_files/quote_with_bundle_and_options.php
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testBundleProductView(): void
{
$quoteCollection = $this->quoteCollectionFactory->create();
$quoteCollection->addFieldToFilter('reserved_order_id', 'test_cart_with_bundle_and_options');
/** @var Quote $quote */
$quote = $quoteCollection->getFirstItem();
$this->assertNotEmpty($quote->getId());
$quote->setCustomerId(1);
$this->quoteRepository->save($quote);
$this->processCheckQuoteItems('customer@example.com');
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\Cart;
use Magento\Customer\Block\Adminhtml\Edit\Tab\AbstractCartTest;
use Magento\Framework\Module\Manager;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks customer's shopping cart block with configurable product.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart
* @magentoAppArea adminhtml
*/
class CartConfigurableTest extends AbstractCartTest
{
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because Customer independent of Magento_ConfigurableProduct
if (!$moduleManager->isEnabled('Magento_ConfigurableProduct')) {
self::markTestSkipped('Magento_ConfigurableProduct module disabled.');
}
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/customer_quote_with_items_configurable_product.php
* @return void
*/
public function testConfigurableProductView(): void
{
$this->processCheckQuoteItems('customer_uk_address@test.com');
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\Cart;
use Magento\Customer\Block\Adminhtml\Edit\Tab\Cart;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Data\Collection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Model\QuoteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use PHPUnit\Framework\TestCase;
/**
* Class checks that shopping cart grid can be filtered
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart::_prepareCollection()
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class CollectionTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->executeInStoreContext = $this->objectManager->get(ExecuteInStoreContext::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @magentoDataFixture Magento/Checkout/_files/customer_quote_on_second_website.php
*
* @return void
*/
public function testCollectionOnDifferentStores(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$collectionFirstWebsite = $this->executeInStoreContext->execute(
'default',
[$this->layout->createBlock(Cart::class), 'getPreparedCollection']
);
$this->assertCollection($collectionFirstWebsite, 'Simple Product');
$this->objectManager->removeSharedInstance(QuoteRepository::class);
$collectionSecondWebsite = $this->executeInStoreContext->execute(
'fixture_second_store',
[$this->layout->createBlock(Cart::class), 'getPreparedCollection']
);
$this->assertCollection($collectionSecondWebsite, 'Simple Product on second website');
}
/**
* Check is collection match expected value
*
* @param Collection $collection
* @param string $itemName
* @return void
*/
private function assertCollection(Collection $collection, string $itemName): void
{
$this->assertCount(1, $collection, 'Collection size does not match expected value');
$this->assertEquals($itemName, $collection->getFirstItem()->getName());
}
}
@@ -0,0 +1,146 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\Cart;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Class checks store switcher appearance in the customer shopping cart block.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class StoreSwitcherTest extends TestCase
{
private const WEBSITE_FILTER_XPATH = "//select[@name='website_id' and @id='website_filter']";
private const WEBSITE_FILTER_OPTION_XPATH = "//select[@name='website_id' and @id='website_filter']/option";
/** @var ObjectManagerInterface */
private $objectManager;
/** @var PageFactory */
private $pageFactory;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
}
/**
* @return void
*/
public function testStoreSwitcherDisplayed(): void
{
$html = $this->getBlockHtml('admin.customer.view.edit.cart');
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(self::WEBSITE_FILTER_XPATH, $html),
'Website Filter was not found on the page'
);
$this->checkFilterOptions($html, [$this->storeManager->getWebsite('base')->getName()]);
}
/**
* @magentoConfigFixture current_store general/single_store_mode/enabled 1
*
* @return void
*/
public function testStoreSwitcherIsNotDisplayed(): void
{
$html = $this->getBlockHtml('admin.customer.view.edit.cart');
$this->assertEmpty(Xpath::getElementsCountForXpath(self::WEBSITE_FILTER_XPATH, $html));
}
/**
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
*
* @return void
*/
public function testStoreSwitcherMultiWebsite(): void
{
$expectedWebsites = [
$this->storeManager->getWebsite('base')->getName(),
$this->storeManager->getWebsite('test')->getName(),
];
$html = $this->getBlockHtml('admin.customer.view.edit.cart');
$this->assertEquals(1, Xpath::getElementsCountForXpath(self::WEBSITE_FILTER_XPATH, $html));
$this->checkFilterOptions($html, $expectedWebsites);
}
/**
* Check store switcher appearance
*
* @param string $html
* @param array $expectedOptions
* @return void
*/
private function checkFilterOptions(string $html, array $expectedOptions): void
{
$this->assertEquals(
count($expectedOptions),
Xpath::getElementsCountForXpath(self::WEBSITE_FILTER_OPTION_XPATH, $html),
'Website filter options count does not match expected value'
);
$optionPath = self::WEBSITE_FILTER_OPTION_XPATH . "[contains(text(), '%s')]";
foreach ($expectedOptions as $option) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($optionPath, $option), $html),
sprintf('Option for %s website was not found in filter options list', $option)
);
}
}
/**
* Get block html
*
* @param string $alias
* @return string
*/
private function getBlockHtml(string $alias): string
{
$page = $this->preparePage();
$block = $page->getLayout()->getBlock($alias);
$this->assertNotFalse($block);
return $block->toHtml();
}
/**
* Prepare page layout
*
* @return Page
*/
private function preparePage(): Page
{
$page = $this->pageFactory->create();
$page->addHandle(['default', 'customer_index_cart']);
$page->getLayout()->generateXml();
return $page;
}
}
@@ -0,0 +1,163 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
use Magento\Backend\Model\Session\Quote as SessionQuote;
use Magento\Quote\Model\Quote;
/**
* Class checks customer's shopping cart block with simple product and simple product with options.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\Cart
* @magentoAppArea adminhtml
*/
class CartTest extends AbstractCartTest
{
/**
* @magentoDataFixture Magento/Checkout/_files/customer_quote_with_items_simple_product_options.php
*
* @return void
*/
public function testProductOptionsView(): void
{
$this->processCheckQuoteItems('customer_uk_address@test.com');
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @magentoDataFixture Magento/Customer/_files/two_customers.php
* @return void
*/
public function testCustomerWithoutQuoteView(): void
{
$this->processCheckWithoutQuoteItems('customer_two@example.com');
}
/**
* Verify Grid with quote items
*
* @magentoDataFixture Magento/Sales/_files/quote_with_two_products_and_customer.php
* @magentoDataFixture Magento/Customer/_files/customer.php
* @dataProvider getQuoteDataProvider
*
* @param int $customerId
* @param bool $guest
* @param bool $contains
* @return void
*/
public function testVerifyCollectionWithQuote(int $customerId, bool $guest, bool $contains): void
{
$session = $this->objectManager->create(SessionQuote::class);
$session->setCustomerId($customerId);
$quoteFixture = $this->objectManager->create(Quote::class);
$quoteFixture->load('test01', 'reserved_order_id');
$quoteFixture->setCustomerIsGuest($guest)
->setCustomerId($customerId)
->save();
$this->block->toHtml();
if ($contains) {
$this->assertStringContainsString(
"We couldn&#039;t find any records",
$this->block->getGridParentHtml()
);
} else {
$this->assertStringNotContainsString(
"We couldn&#039;t find any records",
$this->block->getGridParentHtml()
);
}
}
/**
* Data provider for withQuoteTest
*
* @return array
*/
public function getQuoteDataProvider(): array
{
return [
[
6,
false,
true
],
[
self::CUSTOMER_ID_VALUE,
true,
false
],
];
}
/**
* Verify Customer id
*
* @return void
*/
public function testGetCustomerId(): void
{
$this->assertEquals(self::CUSTOMER_ID_VALUE, $this->block->getCustomerId());
}
/**
* Verify get grid url
*
* @return void
*/
public function testGetGridUrl(): void
{
$this->assertStringContainsString('/backend/customer/index/cart', $this->block->getGridUrl());
}
/**
* Verify grid parent html
*
* @return void
*/
public function testGetGridParentHtml(): void
{
$mockCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class)
->disableOriginalConstructor()
->getMock();
$this->block->setCollection($mockCollection);
$this->assertStringContainsString(
"<div class=\"admin__data-grid-header admin__data-grid-toolbar\"",
$this->block->getGridParentHtml()
);
}
/**
* Verify row url
*
* @return void
*/
public function testGetRowUrl(): void
{
$row = new \Magento\Framework\DataObject();
$row->setProductId(1);
$this->assertStringContainsString('/backend/catalog/product/edit/id/1', $this->block->getRowUrl($row));
}
/**
* Verify get html
*
* @return void
*/
public function testGetHtml(): void
{
$html = $this->block->toHtml();
$this->assertStringContainsString("<div id=\"customer_cart_grid\"", $html);
$this->assertStringContainsString("<div class=\"admin__data-grid-header admin__data-grid-toolbar\"", $html);
$this->assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html);
$this->assertStringContainsString(
'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fconfigure\u002Fcustomer_id\u002F'
. self::CUSTOMER_ID_VALUE,
$html
);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
/**
* Magento\Customer\Block\Adminhtml\Edit\Tab\Carts
*
* @magentoAppArea adminhtml
*/
class CartsTest extends \PHPUnit\Framework\TestCase
{
/** @var Carts */
private $_block;
/** @var \Magento\Customer\Api\CustomerRepositoryInterface */
private $_customerRepository;
/** @var \Magento\Backend\Block\Template\Context */
private $_context;
/** @var \Magento\Framework\ObjectManagerInterface */
private $_objectManager;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_customerRepository = $this->_objectManager->get(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$storeManager = $this->_objectManager->get(\Magento\Store\Model\StoreManager::class);
$this->_context = $this->_objectManager->create(
\Magento\Backend\Block\Template\Context::class,
['storeManager' => $storeManager]
);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetHtml()
{
$customer = $this->_customerRepository->getById(1);
$data = ['account' => $customer->__toArray()];
$this->_context->getBackendSession()->setCustomerData($data);
$this->_block = $this->_objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\Carts::class,
'',
['context' => $this->_context]
);
$html = $this->_block->toHtml();
$this->assertStringContainsString("<div id=\"customer_cart_grid\"", $html);
$this->assertMatchesRegularExpression(
'/<div class=".*admin__data-grid-toolbar"/',
$html
);
$this->assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html);
$this->assertStringContainsString(
'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fconfigure\u002Fwebsite_id\u002F1',
$html
);
}
public function testGetHtmlNoCustomer()
{
$data = ['account' => []];
$this->_context->getBackendSession()->setCustomerData($data);
$this->_block = $this->_objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\Carts::class,
'',
['context' => $this->_context]
);
$html = $this->_block->toHtml();
$this->assertStringContainsString("<div id=\"customer_cart_grid\"", $html);
$this->assertMatchesRegularExpression(
'/<div class=".*admin__data-grid-toolbar"/',
$html
);
$this->assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html);
$this->assertStringContainsString(
'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fupdate\u002Fkey',
$html
);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test Customer account form block functionality
*
* @magentoAppArea adminhtml
*/
class NewsletterTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @var Newsletter
*/
private $block;
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\Newsletter::class,
'',
['registry' => $this->coreRegistry]
)->setTemplate(
'tab/newsletter.phtml'
);
}
/**
* Execute post test cleanup
*/
protected function tearDown(): void
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
*/
public function testRenderingNewsletterBlock()
{
$websiteId = 1;
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('\u003Cspan\u003ENewsletter Information\u003C\/span\u003E', $body);
$this->assertStringContainsString(
'\u003Cinput id=\"_newslettersubscription_status_' . $websiteId . '\"',
$body
);
$this->assertStringNotContainsString('checked="checked"', $body);
$this->assertStringContainsString('\u003Cspan\u003ESubscribed to Newsletter\u003C\/span\u003E', $body);
$this->assertStringContainsString('\u003ENo Newsletter Found\u003C', $body);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
* @magentoDataFixture Magento/Newsletter/_files/newsletter_sample.php
* @magentoDataFixture Magento/Newsletter/_files/queue.php
*/
public function testRenderingNewsletterBlockWithQueue()
{
$this->getRequest()->setParam('id', 1);
$this->dispatch('backend/customer/index/edit');
$body = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression(
'~.+\/newsletter\\\/template\\\/preview\\\/id\\\/\d+\\\/subscriber\\\/\d+\\\/.+~',
$body
);
}
}
@@ -0,0 +1,433 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\Orders;
use Magento\Customer\Block\Adminhtml\Edit\Tab\Orders;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Directory\Model\Currency;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Locale\CurrencyInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\View\Element\UiComponent\DataProvider\Document;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\System\Store;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Test cases related to check that orders tab with customer orders
* grid correctly renders and contains all necessary data.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class RenderOrdersTabTest extends TestCase
{
private const PATHS_TO_TABLE_BODY = [
"//div[contains(@data-grid-id, 'customer_orders_grid')]",
"//table[contains(@class, 'data-grid')]",
"//tbody",
];
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Store
*/
private $store;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var CurrencyInterface
*/
private $currency;
/**
* @var TimezoneInterface
*/
private $timezone;
/**
* @var Registry
*/
private $registry;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var Orders
*/
private $ordersGridBlock;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->store = $this->objectManager->get(Store::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->currency = $this->objectManager->get(CurrencyInterface::class);
$this->timezone = $this->objectManager->get(TimezoneInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->scopeConfig = $this->objectManager->get(ScopeConfigInterface::class);
parent::setUp();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
parent::tearDown();
}
/**
* Assert that customer orders tab renders with message "We couldn't find any records."
* when customer doesn't have any orders.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testRenderBlockWithoutOrders(): void
{
$this->processCheckOrdersGridByCustomerId(1, 0);
}
/**
* Assert that customer orders tab renders without message "We couldn't find any records."
* and contains rendered order item when customer has one order.
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testRenderBlockWithOneOrder(): void
{
$this->processCheckOrdersGridByCustomerId(1, 1);
}
/**
* Assert that customer orders tab renders without message "We couldn't find any records."
* and contains rendered orders items when customer has few orders.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Sales/_files/orders_with_customer.php
*
* @return void
*/
public function testRenderBlockWithFewOrders(): void
{
$this->processCheckOrdersGridByCustomerId(1, 5);
}
/**
* Render orders grid and assert that all data rendered as expected.
*
* @param int $customerId
* @param int $expectedOrderCount
* @return void
*/
private function processCheckOrdersGridByCustomerId(int $customerId, int $expectedOrderCount): void
{
$this->registerCustomerId($customerId);
$ordersGridHtml = $this->getOrdersGridHtml();
$orderItemsData = $this->getOrderGridItemsData();
$this->assertOrdersCount($expectedOrderCount, $ordersGridHtml);
$this->assertIsEmptyGridMessageArrears($ordersGridHtml, $expectedOrderCount === 0);
$this->checkOrderItemsFields($orderItemsData, $ordersGridHtml);
}
/**
* Add customer id to registry.
*
* @param int $customerId
* @return void
*/
private function registerCustomerId(int $customerId): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
}
/**
* Render customer orders tab.
*
* @return string
*/
private function getOrdersGridHtml(): string
{
$this->ordersGridBlock = $this->layout->createBlock(Orders::class);
return $this->ordersGridBlock->toHtml();
}
/**
* Check that rendered html contains all provided order items.
*
* @param array $orderItemsData
* @param string $html
* @return void
*/
private function checkOrderItemsFields(array $orderItemsData, string $html): void
{
foreach ($orderItemsData as $itemOrder => $orderItemData) {
$this->assertViewOrderUrl($itemOrder, $orderItemData['order_id'], $html);
$this->assertReorderUrl($itemOrder, $orderItemData['order_id'], $html);
$this->assertStoreViewLabels($itemOrder, $orderItemData['store_view_labels'], $html);
unset($orderItemData['order_id'], $orderItemData['store_view_labels']);
$this->assertColumnsValues($itemOrder, $orderItemData, $html);
}
}
/**
* Assert that field store_id contains all provided store codes.
*
* @param int $itemOrder
* @param array $storeViewLabels
* @param string $html
* @return void
*/
private function assertStoreViewLabels(int $itemOrder, array $storeViewLabels, string $html): void
{
if (empty($storeViewLabels)) {
return;
}
$elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [
"//tr[{$itemOrder}]",
"//td[contains(@class, 'store_id') and %s]",
]);
$storeLabelsPaths = [];
foreach ($storeViewLabels as $labelIndex => $storeViewLabel) {
$storeLabelsPaths[] = "contains(text()[{$labelIndex}], '{$storeViewLabel}')";
}
$checkStoreViewsXPath = sprintf(implode('', $elementPaths), implode(' and ', $storeLabelsPaths));
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($checkStoreViewsXPath, $html),
sprintf("Some store view label not found. Labels: %s. Html: %s", implode(', ', $storeViewLabels), $html)
);
}
/**
* Assert that columns values as expected.
*
* @param int $itemOrder
* @param array $columnsData
* @param string $html
* @return void
*/
private function assertColumnsValues(int $itemOrder, array $columnsData, string $html): void
{
$elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [
"//tr[{$itemOrder}]",
"//td[contains(@class, '%s') and contains(text(), '%s')]",
]);
$elementXPathTemplate = implode('', $elementPaths);
foreach ($columnsData as $columnName => $columnValue) {
$preparedXPath = sprintf($elementXPathTemplate, $columnName, $columnValue);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($preparedXPath, $html),
sprintf("Column %s doesn't have value %s. Html: %s", $columnName, $columnValue, $html)
);
}
}
/**
* Assert that rendered html contains URL to reorder by order id.
*
* @param int $itemOrder
* @param int $orderId
* @param string $html
* @return void
*/
private function assertReorderUrl(int $itemOrder, int $orderId, string $html): void
{
$urlLabel = (string)__('Reorder');
$elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [
"//tr[{$itemOrder}]",
"//td[contains(@class, 'action')]",
"//a[contains(@href, 'sales/order_create/reorder/order_id/$orderId') and contains(text(), '{$urlLabel}')]",
]);
$reorderUrlXPath = implode('', $elementPaths);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($reorderUrlXPath, $html),
sprintf('Reorder URL is not as expected. Html: %s', $html)
);
}
/**
* Assert that rendered html contains URL to order view by order id.
*
* @param int $itemOrder
* @param int $orderId
* @param string $html
* @return void
*/
private function assertViewOrderUrl(int $itemOrder, int $orderId, string $html): void
{
$elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [
"//tr[{$itemOrder}][contains(@title, 'sales/order/view/order_id/{$orderId}')]",
]);
$viewOrderUrlXPath = implode('', $elementPaths);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($viewOrderUrlXPath, $html),
sprintf('URL to view order is not as expected. Html: %s', $html)
);
}
/**
* Assert that provided orders count and count in html are equals.
*
* @param int $expectedOrdersCount
* @param string $html
* @return void
*/
private function assertOrdersCount(int $expectedOrdersCount, string $html): void
{
$elementPaths = [
"//div[contains(@data-grid-id, 'customer_orders_grid')]",
"//div[contains(@class, 'grid-header-row')]",
"//div[contains(@class, 'control-support-text')]",
sprintf("//span[contains(@id, 'grid-total-count') and contains(text(), '%s')]", $expectedOrdersCount),
];
$ordersCountXPath = implode('', $elementPaths);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($ordersCountXPath, $html),
sprintf('Provided count and count in html are not equals. Html: %s', $html)
);
}
/**
* Assert that grid contains or not contains message "We couldn't find any records.".
*
* @param string $html
* @param bool $isMessageAppears
* @return void
*/
private function assertIsEmptyGridMessageArrears(string $html, bool $isMessageAppears = false): void
{
$gridText = (string)__("We couldn't find any records.");
$elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [
"//tr[contains(@class, 'tr-no-data')]",
"//td[contains(@class, 'empty-text') and contains(text(), \"{$gridText}\")]",
]);
$emptyTextXPath = implode('', $elementPaths);
$this->assertEquals(
$isMessageAppears ? 1 : 0,
Xpath::getElementsCountForXpath($emptyTextXPath, $html),
sprintf('Message "We couldn\'t find any records." not found in html. Html: %s', $html)
);
}
/**
* Build array with rendered orders for check that all contained data appears.
*
* @return array
*/
private function getOrderGridItemsData(): array
{
$orders = [];
$orderNumber = 1;
/** @var Document $order */
foreach ($this->ordersGridBlock->getCollection() as $order) {
$orderGrandTotal = $this->prepareGrandTotal(
$order->getData('grand_total'),
$order->getData('order_currency_code')
);
$orders[$orderNumber] = [
'order_id' => (int)$order->getData(OrderInterface::ENTITY_ID),
'increment_id' => $order->getData(OrderInterface::INCREMENT_ID),
'created_at' => $this->prepareCreatedAtDate($order->getData(OrderInterface::CREATED_AT)),
'billing_name' => $order->getData('billing_name'),
'shipping_name' => $order->getData('shipping_name'),
'grand_total' => $orderGrandTotal,
'store_view_labels' => $this->prepareStoreViewLabels([$order->getData(OrderInterface::STORE_ID)]),
];
$orderNumber++;
}
return $orders;
}
/**
* Normalize created at date.
*
* @param string $createdAt
* @return string
*/
private function prepareCreatedAtDate(string $createdAt): string
{
$date = new \DateTime($createdAt);
return $this->timezone->formatDateTime($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM);
}
/**
* Normalize grand total.
*
* @param string $grandTotal
* @param string|null $orderCurrencyCode
* @return string
*/
private function prepareGrandTotal(string $grandTotal, ?string $orderCurrencyCode = null): string
{
$resultGrandTotal = sprintf("%f", (float)$grandTotal * 1.0);
$orderCurrencyCode = $orderCurrencyCode ?:
$this->scopeConfig->getValue(Currency::XML_PATH_CURRENCY_BASE, 'default');
return $this->currency->getCurrency($orderCurrencyCode)->toCurrency($resultGrandTotal);
}
/**
* Normalize store ids.
*
* @param array $orderStoreIds
* @return array
*/
private function prepareStoreViewLabels(array $orderStoreIds): array
{
$result = [];
$storeStructure = $this->store->getStoresStructure(false, $orderStoreIds);
$textIndex = 0;
foreach ($storeStructure as $website) {
$textIndex++;
foreach ($website['children'] as $group) {
$textIndex++;
foreach ($group['children'] as $store) {
$textIndex++;
$result[$textIndex] = $store['label'];
}
}
}
return $result;
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Escaper;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\Orders
*
* @magentoAppArea adminhtml
*/
class OrdersTest extends \PHPUnit\Framework\TestCase
{
/**
* The orders block under test.
*
* @var Orders
*/
private $block;
/**
* Core registry.
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* @var Escaper
*/
private $escaper;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\Orders::class,
'',
['coreRegistry' => $this->coreRegistry]
);
$this->block->getPreparedCollection();
$this->escaper = $objectManager->get(Escaper::class);
}
/**
* Execute post test cleanup.
*/
protected function tearDown(): void
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->block->setCollection(null);
}
/**
* Verify that a valid Url is returned for a given sales order row.
*/
public function testGetRowUrl()
{
$row = new \Magento\Framework\DataObject(['id' => 1]);
$this->assertStringContainsString('sales/order/view/order_id/1', $this->block->getRowUrl($row));
}
/**
* Verify that a valid grid Url is returned.
*/
public function testGetGridUrl()
{
$this->assertStringContainsString('customer/index/orders', $this->block->getGridUrl());
}
/**
* Verify that the sales order grid Html is valid and contains no records.
*/
public function testToHtml()
{
$this->assertStringContainsString(
$this->escaper->escapeHtml("We couldn't find any records."),
$this->block->toHtml()
);
}
}
@@ -0,0 +1,114 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Escaper;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Cart
*
* @magentoAppArea adminhtml
*/
class CartTest extends \PHPUnit\Framework\TestCase
{
/**
* Shopping cart.
*
* @var Cart
*/
private $block;
/**
* Core registry.
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* @var Escaper
*/
private $escaper;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\View\Cart::class,
'',
['coreRegistry' => $this->coreRegistry, 'data' => ['website_id' => 1]]
);
$this->block->getPreparedCollection();
$this->escaper = $objectManager->get(Escaper::class);
}
/**
* Execute per test cleanup.
*/
protected function tearDown(): void
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* Verify that the Url for a product row in the cart grid is correct.
*/
public function testGetRowUrl()
{
$row = new \Magento\Framework\DataObject(['product_id' => 1]);
$this->assertStringContainsString('catalog/product/edit/id/1', $this->block->getRowUrl($row));
}
/**
* Verify that the headers in the cart grid are visible.
*/
public function testGetHeadersVisibility()
{
$this->assertTrue($this->block->getHeadersVisibility());
}
/**
* Verify the basic content of an empty cart.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testToHtmlEmptyCart()
{
$this->assertEquals(0, $this->block->getCollection()->getSize());
$this->assertStringContainsString(
$this->escaper->escapeHtml('There are no items in customer\'s shopping cart.'),
$this->block->toHtml()
);
}
/**
* Verify the Html content for a single item in the customer's cart.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/quote.php
*/
public function testToHtmlCartItem()
{
$html = $this->block->toHtml();
$this->assertStringContainsString('Simple Product', $html);
$this->assertStringContainsString('simple', $html);
$this->assertStringContainsString('$10.00', $html);
$this->assertStringContainsString($this->escaper->escapeHtmlAttr('catalog/product/edit/id/1'), $html);
}
}
@@ -0,0 +1,120 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Helper\Product\Configuration;
use Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item as RendererItem;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Base class for testing \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item block
*/
abstract class AbstractItemTest extends TestCase
{
/** @var ObjectManager */
protected $objectManager;
/** @var RendererItem */
private $blockRendererItem;
/** @var CollectionFactory */
private $quoteItemCollectionFactory;
/** @var Configuration */
private $productConfiguration;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->blockRendererItem = $this->objectManager->get(LayoutInterface::class)->createBlock(RendererItem::class);
$this->quoteItemCollectionFactory = $this->objectManager->get(CollectionFactory::class);
$this->productConfiguration = $this->objectManager->get(Configuration::class);
}
/**
* Check item block rendering
*
* @return void
*/
protected function processRender(): void
{
$itemsCollection = $this->quoteItemCollectionFactory->create();
/** @var Item $quoteItem */
$quoteItem = $itemsCollection->getFirstItem();
$this->assertNotEmpty($quoteItem->getId());
$this->blockRendererItem->setProductHelpers([]);
$html = $this->blockRendererItem->render($quoteItem);
$this->assertRendererItemValue($quoteItem, $html);
}
/**
* Check that the product name and options are in the block.
*
* @param Item $quoteItem
* @param string $html
* @return void
*/
private function assertRendererItemValue(Item $quoteItem, string $html): void
{
$optionsXPath = $this->getOptionsValueXPath($quoteItem);
$productName = $quoteItem->getProduct()->getName();
$productNameXPath = count($optionsXPath) === 0 ? "/descendant::*[contains(text(), '$productName')]"
: "//div[contains(@class, 'product-title') and contains(text(), '$productName')]";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($productNameXPath, $html),
'The block\'s rendered value does not contain expected product name.'
);
foreach ($optionsXPath as $option) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($option['xpath'], $html),
sprintf('The block\'s rendered value does not contain expected option. Option: %s', $option['label'])
);
}
}
/**
* Get item options and their xpath expression
*
* @param Item $quoteItem
* @return array
*/
private function getOptionsValueXPath(Item $quoteItem): array
{
$options = $this->productConfiguration->getOptions($quoteItem);
foreach ($options as $key => $option) {
$options[$key]['xpath'] = "//dl[contains(@class, 'item-options')]"
. "/dt[contains(text(), '{$option['label']}')]"
. "/following-sibling::dd[1]";
if (isset($option['option_type'])
&& $option['option_type'] == ProductCustomOptionInterface::OPTION_GROUP_FILE) {
$value = explode(" ", $option['print_value']);
$options[$key]['xpath'] .= "[contains(text(), '{$value[0]}')]";
} else {
$options[$key]['xpath'] .= "[contains(text(), '{$option['value']}')]";
}
}
return $options;
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item;
use Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\AbstractItemTest;
use Magento\Framework\Module\Manager;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks item block rendering with configurable product.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item
*/
class ItemConfigurableTest extends AbstractItemTest
{
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because Customer independent of Magento_ConfigurableProduct
if (!$moduleManager->isEnabled('Magento_ConfigurableProduct')) {
self::markTestSkipped('Magento_ConfigurableProduct module disabled.');
}
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/customer_quote_with_items_configurable_product.php
* @return void
*/
public function testRenderConfigurableProduct(): void
{
$this->processRender();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer;
/**
* Class checks item block rendering with simple product and simple product with options.
*
* @see \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item
*/
class ItemTest extends AbstractItemTest
{
/**
* @magentoDataFixture Magento/Checkout/_files/customer_quote_with_items_simple_product_options.php
* @return void
*/
public function testRenderProductOptions(): void
{
$this->processRender();
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @return void
*/
public function testRenderSimpleProduct(): void
{
$this->processRender();
}
}
@@ -0,0 +1,287 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Controller\RegistryConstants;
/**
* Magento\Customer\Block\Adminhtml\Edit\Tab\View
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
*/
class PersonalInfoTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Backend\Block\Template\Context */
private $_context;
/** @var \Magento\Framework\Registry */
private $_coreRegistry;
/** @var CustomerInterfaceFactory */
private $_customerFactory;
/** @var \Magento\Customer\Api\CustomerRepositoryInterface */
private $_customerRepository;
/** @var \Magento\Customer\Api\GroupRepositoryInterface */
private $_groupRepository;
/** @var \Magento\Store\Model\StoreManagerInterface */
private $_storeManager;
/** @var \Magento\Framework\ObjectManagerInterface */
private $_objectManager;
/** @var \Magento\Framework\Reflection\DataObjectProcessor */
private $_dataObjectProcessor;
/** @var PersonalInfo */
private $_block;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_storeManager = $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);
$this->_context = $this->_objectManager->get(
\Magento\Backend\Block\Template\Context::class,
['storeManager' => $this->_storeManager]
);
$this->_customerFactory = $this->_objectManager->get(
\Magento\Customer\Api\Data\CustomerInterfaceFactory::class
);
$this->_coreRegistry = $this->_objectManager->get(\Magento\Framework\Registry::class);
$this->_customerRepository = $this->_objectManager->get(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$this->_dataObjectProcessor = $this->_objectManager->get(
\Magento\Framework\Reflection\DataObjectProcessor::class
);
$this->_groupRepository = $this->_objectManager->get(\Magento\Customer\Api\GroupRepositoryInterface::class);
$this->dateTime = $this->_objectManager->get(\Magento\Framework\Stdlib\DateTime::class);
$this->_block = $this->_objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo::class,
'',
[
'context' => $this->_context,
'groupService' => $this->_groupRepository,
'registry' => $this->_coreRegistry
]
);
}
protected function tearDown(): void
{
$this->_coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
/** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */
$customerRegistry = $this->_objectManager->get(\Magento\Customer\Model\CustomerRegistry::class);
//Cleanup customer from registry
$customerRegistry->remove(1);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCustomer()
{
$expectedCustomer = $this->_loadCustomer();
$expectedCustomerData = $this->_dataObjectProcessor->buildOutputDataArray(
$expectedCustomer,
\Magento\Customer\Api\Data\CustomerInterface::class
);
$actualCustomer = $this->_block->getCustomer();
$actualCustomerData = $this->_dataObjectProcessor->buildOutputDataArray(
$actualCustomer,
\Magento\Customer\Api\Data\CustomerInterface::class
);
foreach ($expectedCustomerData as $property => $value) {
$expectedValue = is_numeric($value) ? (int)$value : $value;
$actualValue = isset($actualCustomerData[$property]) ? $actualCustomerData[$property] : null;
$actualValue = is_numeric($actualValue) ? (int)$actualValue : $actualValue;
$this->assertEquals($expectedValue, $actualValue);
}
}
public function testGetCustomerEmpty()
{
$expectedCustomer = $this->createCustomerAndAddToBackendSession();
$actualCustomer = $this->_block->getCustomer();
$this->assertEquals($expectedCustomer->getExtensionAttributes(), $actualCustomer->getExtensionAttributes());
$this->assertEquals($expectedCustomer, $actualCustomer);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetGroupName()
{
$groupName = $this->_groupRepository->getById($this->_loadCustomer()->getGroupId())->getCode();
$this->assertEquals($groupName, $this->_block->getGroupName());
}
public function testGetGroupNameNull()
{
$this->createCustomerAndAddToBackendSession();
$this->assertNull($this->_block->getGroupName());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCreateDate()
{
$createdAt = $this->_block->formatDate(
$this->_loadCustomer()->getCreatedAt(),
\IntlDateFormatter::MEDIUM,
true
);
$this->assertEquals($createdAt, $this->_block->getCreateDate());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetStoreCreateDate()
{
$customer = $this->_loadCustomer();
$localeDate = $this->_context->getLocaleDate();
$timezone = $localeDate->getConfigTimezone(
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$customer->getStoreId()
);
$storeCreateDate = $this->_block->formatDate(
$customer->getCreatedAt(),
\IntlDateFormatter::MEDIUM,
true,
null,
$timezone
);
$this->assertEquals($storeCreateDate, $this->_block->getStoreCreateDate());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetStoreCreateDateTimezone()
{
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $defaultTimeZonePath
*/
$defaultTimeZonePath = $this->_objectManager->get(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class)
->getDefaultTimezonePath();
$timezone = $this->_context->getScopeConfig()->getValue(
$defaultTimeZonePath,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$this->_loadCustomer()->getStoreId()
);
$this->assertEquals($timezone, $this->_block->getStoreCreateDateTimezone());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testIsConfirmedStatusConfirmed()
{
$this->_loadCustomer();
$this->assertEquals(__('Confirmation Not Required'), $this->_block->getIsConfirmedStatus());
}
/**
* @magentoDbIsolation enabled
*/
public function testIsConfirmedStatusConfirmationIsNotRequired()
{
$password = 'password';
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->_customerFactory->create()->setConfirmation(
true
)->setFirstname(
'firstname'
)->setLastname(
'lastname'
)->setEmail(
'email@email.com'
);
$customer = $this->_customerRepository->save($customer, $password);
$this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId());
$this->assertEquals('Confirmation Not Required', $this->_block->getIsConfirmedStatus());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCreatedInStore()
{
$storeName = $this->_storeManager->getStore($this->_loadCustomer()->getStoreId())->getName();
$this->assertEquals($storeName, $this->_block->getCreatedInStore());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testGetBillingAddressHtml()
{
$this->_loadCustomer();
$html = $this->_block->getBillingAddressHtml();
$this->assertStringContainsString('John Smith<br />', $html);
$this->assertStringContainsString('Green str, 67<br />', $html);
$this->assertStringContainsString('CityM, Alabama, 75477<br />', $html);
}
public function testGetBillingAddressHtmlNoDefaultAddress()
{
$this->createCustomerAndAddToBackendSession();
$this->assertEquals(
__('The customer does not have default billing address.'),
$this->_block->getBillingAddressHtml()
);
}
/**
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
private function createCustomerAndAddToBackendSession()
{
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->_customerFactory->create()->setFirstname(
'firstname'
)->setLastname(
'lastname'
)->setEmail(
'email@email.com'
);
$data = ['account' => $this->_dataObjectProcessor
->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class), ];
$this->_context->getBackendSession()->setCustomerData($data);
return $customer;
}
/**
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
private function _loadCustomer()
{
$customer = $this->_customerRepository->getById(1);
$data = ['account' => $this->_dataObjectProcessor
->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class), ];
$this->_context->getBackendSession()->setCustomerData($data);
$this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId());
return $customer;
}
}
@@ -0,0 +1,127 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Sales
*
* @magentoAppArea adminhtml
*/
class SalesTest extends \PHPUnit\Framework\TestCase
{
const MAIN_WEBSITE = 1;
/**
* Sales block under test.
*
* @var Sales
*/
private $block;
/**
* Core registry.
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* Sales order view Html.
*
* @var string
*/
private $html;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\View\Sales::class,
'sales_' . random_int(0, PHP_INT_MAX),
['coreRegistry' => $this->coreRegistry]
)->setTemplate(
'tab/view/sales.phtml'
);
$this->html = $this->block->toHtml();
}
/**
* Execute post test cleanup.
*/
protected function tearDown(): void
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->html = '';
}
/**
* Test basic currency formatting on the Main Website.
*/
public function testFormatCurrency()
{
$this->assertEquals(
'<span class="price">$10.00</span>',
$this->block->formatCurrency(10.00, self::MAIN_WEBSITE)
);
}
/**
* Verify that the website is not in single store mode.
*/
public function testIsSingleStoreMode()
{
$this->assertFalse($this->block->isSingleStoreMode());
}
/**
* Verify sales totals. No sales so there are no totals.
*/
public function testGetTotals()
{
$this->assertEquals(
['lifetime' => 0, 'base_lifetime' => 0, 'base_avgsale' => 0, 'num_orders' => 0],
$this->block->getTotals()->getData()
);
}
/**
* Verify that there are no rows in the sales order grid.
*/
public function testGetRows()
{
$this->assertEmpty($this->block->getRows());
}
/**
* Verify that the Main Website has no websites.
*/
public function testGetWebsiteCount()
{
$this->assertEquals(0, $this->block->getWebsiteCount(self::MAIN_WEBSITE));
}
/**
* Verify basic content of the sales view Html.
*/
public function testToHtml()
{
$this->assertStringContainsString('<span class="title">Sales Statistics</span>', $this->html);
$this->assertStringContainsString('<strong>All Store Views</strong>', $this->html);
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for customer wish list tab.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class WishlistTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var Wishlist */
private $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Wishlist::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Wishlist/_files/wishlist.php
*
* @return void
*/
public function testWishListGrid(): void
{
$this->registerCustomerId(1);
$this->assertCount(1, $this->block->getPreparedCollection());
}
/**
* Add customer id to registry.
*
* @param int $customerId
* @return void
*/
private function registerCustomerId(int $customerId): void
{
$this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
}
}
@@ -0,0 +1,159 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Controller\RegistryConstants;
/**
* Magento\Customer\Block\Adminhtml\Edit\Tab\View
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
*/
class ViewTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Backend\Block\Template\Context */
private $_context;
/** @var \Magento\Framework\Registry */
private $_coreRegistry;
/** @var CustomerDataBuilder */
private $_customerFactory;
/** @var CustomerRepositoryInterface */
private $_customerRepository;
/** @var \Magento\Store\Model\StoreManagerInterface */
private $_storeManager;
/** @var \Magento\Framework\ObjectManagerInterface */
private $_objectManager;
/** @var \Magento\Framework\Reflection\DataObjectProcessor */
private $_dataObjectProcessor;
/** @var View */
private $_block;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_storeManager = $this->_objectManager->get(\Magento\Store\Model\StoreManager::class);
$this->_context = $this->_objectManager->get(
\Magento\Backend\Block\Template\Context::class,
['storeManager' => $this->_storeManager]
);
$this->_customerFactory = $this->_objectManager->get(
\Magento\Customer\Api\Data\CustomerInterfaceFactory::class
);
$this->_coreRegistry = $this->_objectManager->get(\Magento\Framework\Registry::class);
$this->_customerRepository = $this->_objectManager->get(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$this->_dataObjectProcessor = $this->_objectManager->get(
\Magento\Framework\Reflection\DataObjectProcessor::class
);
$this->_block = $this->_objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\View::class,
'',
[
'context' => $this->_context,
'registry' => $this->_coreRegistry
]
);
}
protected function tearDown(): void
{
$this->_coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
}
public function testGetTabLabel()
{
$this->assertEquals(__('Customer View'), $this->_block->getTabLabel());
}
public function testGetTabTitle()
{
$this->assertEquals(__('Customer View'), $this->_block->getTabTitle());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCanShowTab()
{
$this->_loadCustomer();
$this->assertTrue($this->_block->canShowTab());
}
public function testCanShowTabNot()
{
$this->_createCustomer();
$this->assertFalse($this->_block->canShowTab());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testIsHiddenNot()
{
$this->_loadCustomer();
$this->assertFalse($this->_block->isHidden());
}
public function testIsHidden()
{
$this->_createCustomer();
$this->assertTrue($this->_block->isHidden());
}
/**
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
private function _createCustomer()
{
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->_customerFactory->create()->setFirstname(
'firstname'
)->setLastname(
'lastname'
)->setEmail(
'email@email.com'
);
$data = ['account' => $this->_dataObjectProcessor
->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class), ];
$this->_context->getBackendSession()->setCustomerData($data);
return $customer;
}
/**
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
private function _loadCustomer()
{
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->_customerRepository->getById(1);
$data = ['account' => $this->_dataObjectProcessor
->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class), ];
$this->_context->getBackendSession()->setCustomerData($data);
$this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId());
return $customer;
}
protected function dataToString($data)
{
return parent::dataToString($data); // TODO: Change the autogenerated stub
}
}
@@ -0,0 +1,122 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for \Magento\Customer\Block\Adminhtml\Edit
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
class EditTest extends \PHPUnit\Framework\TestCase
{
/**
* The edit block under test.
*
* @var Edit
*/
private $block;
/**
* Core Registry.
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* The customer Id.
*
* @var int
*/
private static $customerId = 1;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, self::$customerId);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit::class,
'',
['coreRegistry' => $this->coreRegistry]
);
}
/**
* Execute post class cleanup after all tests have executed.
*/
protected function tearDown(): void
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* Verify that the customer Id is the one that was set in the registry.
*/
public function testGetCustomerId()
{
$this->assertEquals(self::$customerId, $this->block->getCustomerId());
}
/**
* Verify that the correct order create Url is generated.
*/
public function testGetCreateOrderUrl()
{
$this->assertStringContainsString(
'sales/order_create/start/customer_id/' . self::$customerId,
$this->block->getCreateOrderUrl()
);
}
/**
* Verify that the header text is correct for a new customer.
*/
public function testGetHeaderTextNewCustomer()
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->assertEquals('New Customer', $this->block->getHeaderText());
}
/**
* Verify that the header text is correct for an existing customer.
*/
public function testGetHeaderTextExistingCustomer()
{
$this->assertEquals('John Smith', $this->block->getHeaderText());
}
/**
* Verify that the correct customer validation Url is generated.
*/
public function testGetValidationUrl()
{
$this->assertStringContainsString('customer/index/validate', $this->block->getValidationUrl());
}
/**
* Verify the basic content of the block's form Html.
*/
public function testGetFormHtml()
{
$html = $this->block->getFormHtml();
$this->assertStringContainsString('<div class="entry-edit form-inline">', $html);
$this->assertStringMatchesFormat('%a name="customer_id" %s value="' . self::$customerId . '" %a', $html);
$this->assertStringContainsString('id="product_composite_configure_form"', $html);
}
}
@@ -0,0 +1,110 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Grid\Renderer;
use Magento\Backend\Block\Widget\Grid\Column\Extended;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Base class for testing \Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction block
*/
abstract class AbstractMultiactionTest extends TestCase
{
/** @var ObjectManager */
protected $objectManager;
/** @var Extended */
protected $blockColumn;
/** @var Multiaction */
protected $blockMultiaction;
/** @var LayoutInterface */
private $layout;
/** @var CollectionFactory */
private $quoteItemCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->blockColumn = $this->layout->createBlock(Extended::class);
$this->blockColumn->setData([
'header' => 'Action',
'index' => 'item_id',
'renderer' => Multiaction::class,
'filter' => false,
'sortable' => false,
]);
$this->blockMultiaction = $this->layout->createBlock(Multiaction::class);
$this->quoteItemCollectionFactory = $this->objectManager->get(CollectionFactory::class);
}
/**
* Check multiaction block rendering
*
* @return void
*/
protected function processRender(): void
{
$itemsCollection = $this->quoteItemCollectionFactory->create();
/** @var Item $quoteItem */
$quoteItem = $itemsCollection->getFirstItem();
$this->assertNotEmpty($quoteItem->getId());
$actions = [
[
'caption' => 'configure',
'url' => 'url_configureItem',
'process' => 'configurable',
'control_object' => 'cartControl',
],
[
'caption' => 'delete',
'url' => 'url_removeItem',
'onclick' => 'return cartControl.removeItem($item_id);'
],
];
$this->blockColumn->addData(['actions' => $actions]);
$this->blockMultiaction->setColumn($this->blockColumn);
$html = $this->blockMultiaction->render($quoteItem);
foreach ($actions as $action) {
$this->assertUrl((int)$quoteItem->getId(), $action, $html);
}
}
/**
* Check that the link in the block is correct
*
* @param int $quoteItemId
* @param array $action
* @param string $html
* @return void
*/
private function assertUrl(int $quoteItemId, array $action, string $html): void
{
$jsFunction = str_replace('url_', '', $action['url']);
$configureXPath = "//a[text()='{$action['caption']}' and @href='{$action['url']}']";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($configureXPath, $html),
sprintf('Expected %s link is incorrect or missing', $action['caption'])
);
$this->assertStringContainsString("return cartControl.$jsFunction($quoteItemId)", $html);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction;
use Magento\Customer\Block\Adminhtml\Grid\Renderer\AbstractMultiactionTest;
use Magento\Framework\Module\Manager;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks multiaction block rendering with bundle product.
*
* @see \Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction
*/
class MultiactionBundleTest extends AbstractMultiactionTest
{
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because Customer independent of Magento_Bundle
if (!$moduleManager->isEnabled('Magento_Bundle')) {
self::markTestSkipped('Magento_Bundle module disabled.');
}
}
/**
* @magentoDataFixture Magento/Bundle/_files/quote_with_bundle_and_options.php
* @return void
*/
public function testRenderConfigurableProduct(): void
{
$this->processRender();
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction;
use Magento\Customer\Block\Adminhtml\Grid\Renderer\AbstractMultiactionTest;
use Magento\Framework\Module\Manager;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks multiaction block rendering with configurable product.
*
* @see \Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction
*/
class MultiactionConfigurableTest extends AbstractMultiactionTest
{
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
//This check is needed because Customer independent of Magento_ConfigurableProduct
if (!$moduleManager->isEnabled('Magento_ConfigurableProduct')) {
self::markTestSkipped('Magento_ConfigurableProduct module disabled.');
}
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/customer_quote_with_items_configurable_product.php
* @return void
*/
public function testRenderConfigurableProduct(): void
{
$this->processRender();
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Block\Adminhtml\Grid\Renderer;
use Magento\Framework\DataObject;
/**
* Class checks multiaction block rendering with simple product and simple product with options.
*
* @see \Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction
*/
class MultiactionTest extends AbstractMultiactionTest
{
/**
* @dataProvider renderEmptyProvider
* @param array $columnData
* @return void
*/
public function testRenderEmpty(array $columnData): void
{
/** @var DataObject $row */
$row = $this->objectManager->create(DataObject::class);
$this->blockColumn->addData($columnData);
$this->blockMultiaction->setColumn($this->blockColumn);
$this->assertEquals(
'&nbsp;',
$this->blockMultiaction->render($row)
);
}
/**
* Data provider for testRenderEmpty
*
* @return array
*/
public function renderEmptyProvider(): array
{
return [
'empty_actions' => [
'column_data' => ['actions' => []],
],
'not_array_actions' => [
'column_data' => ['actions' => 'actions'],
],
'empty_actions_element' => [
'column_data' => [
'actions' => [
'action_1' => 'actions',
],
],
],
];
}
/**
* @magentoDataFixture Magento/Checkout/_files/customer_quote_with_items_simple_product_options.php
* @return void
*/
public function testRenderProductOptions(): void
{
$this->processRender();
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
* @return void
*/
public function testRenderSimpleProduct(): void
{
$this->markTestSkipped('Test is blocked by issue MC-34612');
$this->processRender();
}
}
@@ -0,0 +1,127 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Group\Edit;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Magento\Customer\Block\Adminhtml\Group\Edit\Form
*
* @magentoAppArea adminhtml
*/
class FormTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\View\LayoutInterface
*/
private $layout;
/**
* @var \Magento\Customer\Api\GroupRepositoryInterface
*/
private $groupRepository;
/**
* @var \Magento\Customer\Api\GroupManagementInterface
*/
private $groupManagement;
/**
* @var \Magento\Framework\Registry
*/
private $registry;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
parent::setUp();
$this->layout = Bootstrap::getObjectManager()->create(\Magento\Framework\View\Layout::class);
$this->groupRepository = Bootstrap::getObjectManager()
->get(\Magento\Customer\Api\GroupRepositoryInterface::class);
$this->groupManagement = Bootstrap::getObjectManager()
->get(\Magento\Customer\Api\GroupManagementInterface::class);
$this->registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
}
/**
* Execute per test cleanup.
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_GROUP_ID);
}
/**
* Test retrieving a valid group form.
*/
public function testGetForm()
{
$this->registry
->register(RegistryConstants::CURRENT_GROUP_ID, $this->groupManagement->getDefaultGroup(0)->getId());
/** @var $block Form */
$block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit\Form::class, 'block');
$form = $block->getForm();
$this->assertEquals('edit_form', $form->getId());
$this->assertEquals('post', $form->getMethod());
$baseFieldSet = $form->getElement('base_fieldset');
$this->assertNotNull($baseFieldSet);
$groupCodeElement = $form->getElement('customer_group_code');
$this->assertNotNull($groupCodeElement);
$taxClassIdElement = $form->getElement('tax_class_id');
$this->assertNotNull($taxClassIdElement);
$idElement = $form->getElement('id');
$this->assertNotNull($idElement);
$this->assertEquals('1', $idElement->getValue());
$this->assertEquals('3', $taxClassIdElement->getValue());
/** @var \Magento\Tax\Model\TaxClass\Source\Customer $taxClassCustomer */
$taxClassCustomer = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Customer::class);
$this->assertEquals($taxClassCustomer->toOptionArray(false), $taxClassIdElement->getData('values'));
$this->assertEquals('General', $groupCodeElement->getValue());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testGetFormExistInCustomGroup()
{
$builder = Bootstrap::getObjectManager()->create(\Magento\Framework\Api\FilterBuilder::class);
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteria */
$searchCriteria = Bootstrap::getObjectManager()
->create(\Magento\Framework\Api\SearchCriteriaBuilder::class)
->addFilters([$builder->setField('code')->setValue('custom_group')->create()]);
/** @var GroupInterface $customerGroup */
$customerGroup = $this->groupRepository->getList($searchCriteria->create())->getItems()[0];
$this->registry->register(RegistryConstants::CURRENT_GROUP_ID, $customerGroup->getId());
/** @var $block Form */
$block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit\Form::class, 'block');
$form = $block->getForm();
$this->assertEquals('edit_form', $form->getId());
$this->assertEquals('post', $form->getMethod());
$baseFieldSet = $form->getElement('base_fieldset');
$this->assertNotNull($baseFieldSet);
$groupCodeElement = $form->getElement('customer_group_code');
$this->assertNotNull($groupCodeElement);
$taxClassIdElement = $form->getElement('tax_class_id');
$this->assertNotNull($taxClassIdElement);
$idElement = $form->getElement('id');
$this->assertNotNull($idElement);
$this->assertEquals($customerGroup->getId(), $idElement->getValue());
$this->assertEquals($customerGroup->getTaxClassId(), $taxClassIdElement->getValue());
/** @var \Magento\Tax\Model\TaxClass\Source\Customer $taxClassCustomer */
$taxClassCustomer = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Customer::class);
$this->assertEquals($taxClassCustomer->toOptionArray(false), $taxClassIdElement->getData('values'));
$this->assertEquals($customerGroup->getCode(), $groupCodeElement->getValue());
}
}
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Group;
use Magento\Customer\Api\GroupManagementInterface;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Magento\Customer\Block\Adminhtml\Group\Edit
*
* @magentoAppArea adminhtml
*/
class EditTest extends AbstractController
{
/**
* @var \Magento\Framework\View\LayoutInterface
*/
private $layout;
/**
* @var GroupRepositoryInterface
*/
private $groupRepository;
/**
* @var GroupManagementInterface
*/
private $groupManagement;
/**
* @var \Magento\Framework\Registry
*/
private $registry;
/**
* Execute per test initialization.
*/
protected function setUp(): void
{
parent::setUp();
$this->layout = Bootstrap::getObjectManager()->get(\Magento\Framework\View\LayoutInterface::class);
$this->groupRepository = Bootstrap::getObjectManager()->create(
\Magento\Customer\Api\GroupRepositoryInterface::class
);
$this->groupManagement = Bootstrap::getObjectManager()->create(
\Magento\Customer\Api\GroupManagementInterface::class
);
$this->registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
}
/**
* Execute per test cleanup.
*/
protected function tearDown(): void
{
$this->registry->unregister(RegistryConstants::CURRENT_GROUP_ID);
}
/**
* Verify that the Delete button does not exist for the default group.
* @magentoAppIsolation enabled
*/
public function testDeleteButtonNotExistInDefaultGroup()
{
$groupId = $this->groupManagement->getDefaultGroup(0)->getId();
$this->registry->register(RegistryConstants::CURRENT_GROUP_ID, $groupId);
$this->getRequest()->setParam('id', $groupId);
/** @var $block Edit */
$block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit::class, 'block');
$buttonsHtml = $block->getButtonsHtml();
$this->assertStringNotContainsString('delete', $buttonsHtml);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_group.php
*/
public function testDeleteButtonExistInCustomGroup()
{
$builder = Bootstrap::getObjectManager()->create(\Magento\Framework\Api\FilterBuilder::class);
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteria */
$searchCriteria = Bootstrap::getObjectManager()
->create(\Magento\Framework\Api\SearchCriteriaBuilder::class)
->addFilters([$builder->setField('code')->setValue('custom_group')->create()])->create();
$customerGroup = $this->groupRepository->getList($searchCriteria)->getItems()[0];
$this->getRequest()->setParam('id', $customerGroup->getId());
$this->registry->register(RegistryConstants::CURRENT_GROUP_ID, $customerGroup->getId());
/** @var $block Edit */
$block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit::class, 'block');
$buttonsHtml = $block->getButtonsHtml();
$this->assertStringContainsString('delete', $buttonsHtml);
}
}