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,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Items;
/**
* @magentoAppArea adminhtml
*/
class AbstractTest extends \PHPUnit\Framework\TestCase
{
public function testGetItemExtraInfoHtml()
{
/** @var $layout \Magento\Framework\View\Layout */
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
/** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */
$block = $layout->createBlock(\Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, 'block');
$item = new \Magento\Framework\DataObject();
$this->assertEmpty($block->getItemExtraInfoHtml($item));
$expectedHtml = '<html><body>some data</body></html>';
/** @var $childBlock \Magento\Framework\View\Element\Text */
$childBlock = $layout->addBlock(
\Magento\Framework\View\Element\Text::class,
'other_block',
'block',
'order_item_extra_info'
);
$childBlock->setText($expectedHtml);
$this->assertEquals($expectedHtml, $block->getItemExtraInfoHtml($item));
$this->assertSame($item, $childBlock->getItem());
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Items\Column;
/**
* @magentoAppArea adminhtml
*/
class NameTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Name
*/
private $block;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $layout \Magento\Framework\View\Layout */
$layout = $objectManager->create(\Magento\Framework\View\LayoutInterface::class);
/** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */
$this->block = $layout->createBlock(Name::class, 'block');
}
public function testTruncateString() : void
{
$remainder = '';
$this->assertEquals(
'12345',
$this->block->truncateString('1234567890', 5, '', $remainder)
);
}
public function testGetFormattedOptiong() : void
{
$this->assertEquals(
[
'value' => '1234567890123456789012345678901234567890123456789012345',
'remainder' => '67890',
],
$this->block->getFormattedOption(
'123456789012345678901234567890123456789012345678901234567890'
)
);
}
}
@@ -0,0 +1,186 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Address;
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\App\Config;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Checks order address edit form block
*
* @see \Magento\Sales\Block\Adminhtml\Order\Address\Form
*
* @magentoAppArea adminhtml
*/
class FormTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Form */
private $block;
/** @var Registry */
private $registry;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var CollectionFactory */
private $countryCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Form::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->objectManager->removeSharedInstance(Config::class);
$this->countryCollectionFactory = $this->objectManager->get(CollectionFactory::class);
}
/**
* @return void
*/
protected function tearDown(): void
{
$this->registry->unregister('order_address');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testGetFormValues(): void
{
$address = $this->getOrderAddress('100000001');
$this->registerOrderAddress($address);
$formValues = $this->block->getFormValues();
$this->assertEquals($address->getData(), $formValues);
}
/**
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
* @magentoConfigFixture default_store general/country/default US
* @magentoConfigFixture default_store general/country/allow US
* @magentoConfigFixture fixture_second_store_store general/country/default UY
* @magentoConfigFixture fixture_second_store_store general/country/allow UY
* @return void
*/
public function testCountryIdInAllowedList(): void
{
$address = $this->getOrderAddress('100000001');
$this->registerOrderAddress($address);
$this->assertEquals('US', $address->getCountryId());
$this->assertCountryField('US');
}
/**
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
* @magentoConfigFixture default_store general/country/default CA
* @magentoConfigFixture default_store general/country/allow CA
* @magentoConfigFixture fixture_second_store_store general/country/default UY
* @magentoConfigFixture fixture_second_store_store general/country/allow UY
* @return void
*/
public function testCountryIdInNotAllowedList(): void
{
$address = $this->getOrderAddress('100000001');
$this->registerOrderAddress($address);
$this->assertCountryField('CA');
}
/**
* @magentoDbIsolation disabled
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer_on_second_website.php
*
* @magentoConfigFixture default_store general/country/default UA
* @magentoConfigFixture default_store general/country/allow UA
*
* @return void
*/
public function testFormRenderedWithSelectRegionInput(): void
{
$address = $this->getOrderAddress('100000001');
$this->registerOrderAddress($address);
$form = $this->block->getForm();
$countryElement = $form->getElement('country_id');
$this->assertNotNull($countryElement);
$this->assertEquals('US', $countryElement->getEscapedValue());
$html = $form->toHtml();
$regionIdSelectXpath = '//select[@id=\'region_id\']';
$this->assertEquals(1, Xpath::getElementsCountForXpath($regionIdSelectXpath, $html));
$countryOptionsXpath = '//select[@id=\'country_id\']/option';
$allowedCountriesCount = count($this->countryCollectionFactory->create()->loadByStore());
$this->assertEquals($allowedCountriesCount, Xpath::getElementsCountForXpath($countryOptionsXpath, $html));
}
/**
* Prepares address edit from block.
*
* @param OrderAddressInterface $address
* @return void
*/
private function registerOrderAddress(OrderAddressInterface $address): void
{
$this->registry->unregister('order_address');
$this->registry->register('order_address', $address);
}
/**
* Return order billing address.
*
* @param string $orderIncrementId
* @return OrderAddressInterface
*/
private function getOrderAddress(string $orderIncrementId): OrderAddressInterface
{
/** @var OrderInterface $order */
$order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);
return $order->getBillingAddress();
}
/**
* Asserts country field data.
*
* @param string $countryCode
* @return void
*/
private function assertCountryField(string $countryCode): void
{
$countryIdField = $this->block->getForm()->getElement('country_id');
$this->assertEquals($countryCode, $countryIdField->getValue());
$options = $countryIdField->getValues();
$this->assertCount(1, $options);
$firstOption = reset($options);
$this->assertEquals($countryCode, $firstOption['value']);
}
}
@@ -0,0 +1,111 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\Order\Address as AddressType;
use Magento\Sales\Model\OrderFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks order address edit block
*
* @see \Magento\Sales\Block\Adminhtml\Order\Address
*
* @magentoAppArea adminhtml
*/
class AddressTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Address */
private $block;
/** @var Registry */
private $registry;
/** @var OrderFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Address::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->orderFactory = $this->objectManager->get(OrderFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('order_address');
parent::tearDown();
}
/**
* @dataProvider addressTypeProvider
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @param string $type
* @return void
*/
public function testGetHeaderText(string $type): void
{
$order = $this->orderFactory->create()->loadByIncrementId(100000001);
$address = $this->getAddressByType($order, $type);
$this->registry->unregister('order_address');
$this->registry->register('order_address', $address);
$text = $this->block->getHeaderText();
$this->assertEquals(
(string)__('Edit Order %1 %2 Address', $order->getIncrementId(), ucfirst($type)),
(string)$text
);
}
/**
* @return array
*/
public function addressTypeProvider(): array
{
return [
'billing_address' => [
AddressType::TYPE_BILLING,
],
'shipping_address' => [
AddressType::TYPE_SHIPPING,
]
];
}
/**
* Get address by address type
*
* @param OrderInterface $order
* @param string $type
* @return OrderAddressInterface|null
*/
private function getAddressByType(OrderInterface $order, string $type): ?OrderAddressInterface
{
return $type === AddressType::TYPE_BILLING ? $order->getBillingAddress() : $order->getShippingAddress();
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create;
use Magento\Config\Model\Config\Backend\Admin\Custom;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Model\Address\AddressModelInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Metadata\FormFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Data\Form;
use Magento\Framework\View\Element\BlockInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class consist of basic logic to check address form
*/
abstract class AbstractAddressFormTest extends TestCase
{
/** @var LayoutInterface */
protected $layout;
/** @var CustomerRegistry */
protected $customerRegistry;
/** @var CartRepositoryInterface */
private $quoteRepository;
/** @var BlockInterface */
private $form;
/** @var ScopeConfigInterface */
private $config;
/** @var array */
private $formAttributes;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->layout = $objectManager->get(LayoutInterface::class);
$this->form = $this->getFormBlock();
$this->customerRegistry = $objectManager->get(CustomerRegistry::class);
$this->quoteRepository = $objectManager->get(CartRepositoryInterface::class);
$this->config = $objectManager->get(ScopeConfigInterface::class);
$this->formAttributes = array_keys($objectManager->get(FormFactory::class)
->create('customer_address', 'adminhtml_customer_address')->getAttributes());
}
/**
* Check that all form values are filled according to address attributes values
*
* @param int $customerId
* @return void
*/
protected function checkFormValuesExist(int $customerId): void
{
$address = $this->getAddress($customerId);
$form = $this->prepareForm($customerId);
foreach ($this->formAttributes as $attribute) {
$this->assertEquals($address->getData($attribute), $form->getElement($attribute)->getValue());
}
}
/**
* Check that form values is empty
*
* @param int $customerId
* @return void
*/
protected function checkFormValuesAreEmpty(int $customerId): void
{
$defaultCountryCode = $this->config->getValue(Custom::XML_PATH_GENERAL_COUNTRY_DEFAULT);
$form = $this->prepareForm($customerId);
foreach ($this->formAttributes as $attribute) {
if ($attribute === AddressInterface::COUNTRY_ID) {
$this->assertEquals($defaultCountryCode, $form->getElement($attribute)->getValue());
continue;
}
$this->assertNull($form->getElement($attribute)->getValue());
}
}
/**
* Prepare form
*
* @param int $customerId
* @return Form
*/
private function prepareForm(int $customerId): Form
{
$quote = $this->quoteRepository->getForCustomer($customerId);
$this->form->getCreateOrderModel()->setQuote($quote);
return $this->form->getForm();
}
/**
* Get form block
*
* @return BlockInterface
*/
abstract protected function getFormBlock(): BlockInterface;
/**
* Get appropriate customer address
*
* @param int $customerId
* @return AddressModelInterface
*/
abstract protected function getAddress(int $customerId): AddressModelInterface;
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Billing;
use Magento\Customer\Model\Address\AddressModelInterface;
use Magento\Framework\View\Element\BlockInterface;
use Magento\Sales\Block\Adminhtml\Order\Create\AbstractAddressFormTest;
use Magento\Sales\Block\Adminhtml\Order\Create\Shipping\Address;
/**
* Class checks billing address form behaviour
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*
*/
class FormTest extends AbstractAddressFormTest
{
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
*
* @return void
*/
public function testFormValuesExist(): void
{
$this->checkFormValuesExist(1);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testFormValuesAreEmpty(): void
{
$this->checkFormValuesAreEmpty(1);
}
/**
* @inheritdoc
*/
protected function getFormBlock(): BlockInterface
{
return $this->layout->createBlock(Address::class);
}
/**
* @inheritdoc
*/
protected function getAddress(int $customerId): AddressModelInterface
{
return $this->customerRegistry->retrieve($customerId)->getDefaultBillingAddress();
}
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Order\Create\Billing\Method;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for order billing method form.
*
* @magentoAppArea adminhtml
*/
class FormTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
}
/**
* Checks if billing method form generates contentUpdated event
* to parse elements with data-mage-init attributes.
*/
public function testContentUpdated()
{
/** @var Form $block */
$block = $this->layout->createBlock(Form::class, 'order_billing_method');
$block->setTemplate('Magento_Sales::order/create/billing/method/form.phtml');
$html = $block->toHtml();
$this->assertStringContainsString('mage.apply()', $html);
}
}
@@ -0,0 +1,73 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test class for \Magento\Sales\Block\Adminhtml\Order\Create\Form\AbstractForm
*/
namespace Magento\Sales\Block\Adminhtml\Order\Create\Form;
use Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory;
use Magento\Customer\Api\Data\OptionInterfaceFactory;
use Magento\Customer\Api\Data\ValidationRuleInterfaceFactory;
/**
* Class AbstractTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AbstractTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
*/
public function testAddAttributesToForm()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$objectManager->get(\Magento\Framework\View\DesignInterface::class)->setDefaultDesignTheme();
$arguments = [
$objectManager->get(\Magento\Backend\Block\Template\Context::class),
$objectManager->get(\Magento\Backend\Model\Session\Quote::class),
$objectManager->get(\Magento\Sales\Model\AdminOrder\Create::class),
$objectManager->get(\Magento\Framework\Pricing\PriceCurrencyInterface::class),
$objectManager->get(\Magento\Framework\Data\FormFactory::class),
$objectManager->get(\Magento\Framework\Reflection\DataObjectProcessor::class)
];
/** @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Form\AbstractForm */
$block = $this->getMockForAbstractClass(
\Magento\Sales\Block\Adminhtml\Order\Create\Form\AbstractForm::class,
$arguments
);
$block->setLayout($objectManager->create(\Magento\Framework\View\Layout::class));
$method = new \ReflectionMethod(
\Magento\Sales\Block\Adminhtml\Order\Create\Form\AbstractForm::class,
'_addAttributesToForm'
);
$method->setAccessible(true);
/** @var $formFactory \Magento\Framework\Data\FormFactory */
$formFactory = $objectManager->get(\Magento\Framework\Data\FormFactory::class);
$form = $formFactory->create();
$fieldset = $form->addFieldset('test_fieldset', []);
/** @var \Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory $attributeMetadataFactory */
$attributeMetadataFactory =
$objectManager->create(\Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory::class);
$dateAttribute = $attributeMetadataFactory->create()->setAttributeCode('date')
->setBackendType('datetime')
->setFrontendInput('date')
->setFrontendLabel('Date');
$attributes = ['date' => $dateAttribute];
$method->invoke($block, $attributes, $fieldset);
$element = $form->getElement('date');
$this->assertNotNull($element);
$this->assertNotEmpty($element->getDateFormat());
}
}
@@ -0,0 +1,396 @@
<?php
/**
* Test class for \Magento\Sales\Block\Adminhtml\Order\Create\Form\Account
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Form;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\Session\Quote as SessionQuote;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\Data\Option;
use Magento\Customer\Model\Metadata\Form;
use Magento\Customer\Model\Metadata\FormFactory;
use Magento\Framework\App\RequestInterface as Request;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Model\Quote;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
/**
* Class for test Account
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AccountTest extends TestCase
{
/**
* @var Account
*/
private $accountBlock;
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var SessionQuote|MockObject
*/
private $session;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
parent::setUp();
}
/**
* Test for get form with existing customer
*
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetFormWithCustomer()
{
$customerGroup = 2;
$quote = $this->objectManager->create(Quote::class);
$this->session = $this->getMockBuilder(SessionQuote::class)
->disableOriginalConstructor()
->setMethods(['getCustomerId','getQuote'])
->getMock();
$this->session->method('getQuote')
->willReturn($quote);
$this->session->method('getCustomerId')
->willReturn(1);
/** @var LayoutInterface $layout */
$layout = $this->objectManager->get(LayoutInterface::class);
$this->accountBlock = $layout->createBlock(
Account::class,
'address_block' . rand(),
['sessionQuote' => $this->session]
);
$fixtureCustomerId = 1;
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
/** @var CustomerInterface $customer */
$customer = $customerRepository->getById($fixtureCustomerId);
$customer->setGroupId($customerGroup);
$customerRepository->save($customer);
$expectedFields = ['group_id', 'email'];
$form = $this->accountBlock->getForm();
$this->assertEquals(1, $form->getElements()->count(), "Form has invalid number of fieldsets");
$fieldset = $form->getElements()[0];
$content = $form->toHtml();
$this->assertEquals(count($expectedFields), $fieldset->getElements()->count());
foreach ($fieldset->getElements() as $element) {
$this->assertTrue(
in_array($element->getId(), $expectedFields),
sprintf('Unexpected field "%s" in form.', $element->getId())
);
}
self::assertMatchesRegularExpression(
'/<option value="'.$customerGroup.'".*?selected="selected"\>Wholesale\<\/option\>/is',
$content,
'The Customer Group specified for the chosen customer should be selected.'
);
self::assertStringContainsString(
'value="'.$customer->getEmail().'"',
$content,
'The Customer Email specified for the chosen customer should be input '
);
}
/**
* Tests a case when user defined custom attribute has default value.
*
* @magentoDataFixture Magento/Store/_files/core_second_third_fixturestore.php
* @magentoConfigFixture current_store customer/create_account/default_group 2
* @magentoConfigFixture secondstore_store customer/create_account/default_group 3
*/
public function testGetFormWithUserDefinedAttribute()
{
/** @var StoreManagerInterface $storeManager */
$storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
$secondStore = $storeManager->getStore('secondstore');
$quoteSession = $this->objectManager->get(SessionQuote::class);
$quoteSession->setStoreId($secondStore->getId());
$formFactory = $this->getFormFactoryMock();
$this->objectManager->addSharedInstance($formFactory, FormFactory::class);
/** @var LayoutInterface $layout */
$layout = $this->objectManager->get(LayoutInterface::class);
$accountBlock = $layout->createBlock(
Account::class,
'address_block' . rand()
);
$form = $accountBlock->getForm();
$form->setUseContainer(true);
$content = $form->toHtml();
self::assertMatchesRegularExpression(
'/\<option value="1".*?selected="selected"\>Yes\<\/option\>/is',
$content,
'Default value for user defined custom attribute should be selected.'
);
self::assertMatchesRegularExpression(
'/<option value="3".*?selected="selected"\>Retailer\<\/option\>/is',
$content,
'The Customer Group specified for the chosen store should be selected.'
);
}
/**
* Test for get form with default customer group
*
*/
public function testGetFormWithDefaultCustomerGroup()
{
$customerGroup = 0;
$quote = $this->objectManager->create(Quote::class);
$quote->setCustomerGroupId($customerGroup);
$this->session = $this->getMockBuilder(SessionQuote::class)
->disableOriginalConstructor()
->setMethods(['getCustomerId', 'getQuote'])
->getMock();
$this->session->method('getQuote')
->willReturn($quote);
$this->session->method('getCustomerId')
->willReturn(1);
$formFactory = $this->getFormFactoryMock();
$this->objectManager->addSharedInstance($formFactory, FormFactory::class);
/** @var LayoutInterface $layout */
$layout = $this->objectManager->get(LayoutInterface::class);
$accountBlock = $layout->createBlock(
Account::class,
'address_block' . rand(),
['sessionQuote' => $this->session]
);
$expectedGroupId = 1;
$form = $accountBlock->getForm();
self::assertEquals(
$expectedGroupId,
$form->getElement('group_id')->getValue(),
'The Customer Group specified for the chosen customer should be selected.'
);
}
/**
* Test for get form with customer group based on vat id validation
*
* @dataProvider getDataForVatValidatedCustomer
* @param int $defaultCustomerGroupId
* @param int $vatValidatedCustomerGroupId
* @param array $customerDetails
* @param array $orderDetails
* @return void
*/
public function testGetFormWithVatValidatedCustomerGroup(
int $defaultCustomerGroupId,
int $vatValidatedCustomerGroupId,
array $customerDetails,
array $orderDetails
): void {
$contextMock = $this->getMockBuilder(Context::class)
->disableOriginalConstructor()
->disableOriginalClone()
->getMock();
$requestMock = $this->getMockBuilder(Request::class)
->getMockForAbstractClass();
$contextMock->expects($this->once())
->method('getRequest')
->willReturn($requestMock);
$requestMock->expects($this->any())
->method('getParam')
->willReturn($orderDetails);
$quote = $this->objectManager->create(Quote::class);
$quote->setCustomerGroupId($defaultCustomerGroupId);
$quote->setData($customerDetails);
$this->session = $this->getMockBuilder(SessionQuote::class)
->disableOriginalConstructor()
->setMethods(['getCustomerId', 'getQuote'])
->getMock();
$this->session->method('getQuote')
->willReturn($quote);
$this->session->method('getCustomerId')
->willReturn($customerDetails['customer_id']);
$formFactory = $this->getFormFactoryMock();
$this->objectManager->addSharedInstance($formFactory, FormFactory::class);
/** @var LayoutInterface $layout */
$layout = $this->objectManager->get(LayoutInterface::class);
$accountBlock = $layout->createBlock(
Account::class,
'address_block' . rand(),
[
'context' => $contextMock,
'sessionQuote' => $this->session
]
);
$form = $accountBlock->getForm();
self::assertEquals(
$vatValidatedCustomerGroupId,
$form->getElement('group_id')->getValue(),
'The Customer Group specified for the chosen customer should be selected.'
);
}
/**
* Data provider for vat validated customer group id
*
* @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function getDataForVatValidatedCustomer(): array
{
return [
'Validated customer group id when its set in quote' => [
'defaultCustomerGroupId' => 0,
'vatValidatedCustomerGroupId' => 3,
'customerDetails' => [
'entity_id' => '35',
'store_id' => 1,
'created_at' => '2020-11-09 01:03:35',
'updated_at' => '2020-11-09 05:44:07',
'customer_id' => 1,
'customer_tax_class_id' => '3',
'customer_group_id' => 3,
'customer_email' => 'test@test.com',
'customer_prefix' => null,
'customer_firstname' => null,
'customer_middlename' => null,
'customer_lastname' => null,
'customer_suffix' => null,
'customer_dob' => null,
],
'orderDetails' => [
'account' => [
'group_id' => 3,
'email' => 'test@test.com'
]
]
],
'Validated customer group id when its set in request' => [
'defaultCustomerGroupId' => 0,
'vatValidatedCustomerGroupId' => 3,
'customerDetails' => [
'entity_id' => '35',
'store_id' => 1,
'created_at' => '2020-11-09 01:03:35',
'updated_at' => '2020-11-09 05:44:07',
'customer_id' => 1,
'customer_tax_class_id' => '3',
'customer_group_id' => null,
'customer_email' => 'test@test.com',
'customer_prefix' => null,
'customer_firstname' => null,
'customer_middlename' => null,
'customer_lastname' => null,
'customer_suffix' => null,
'customer_dob' => null,
],
'orderDetails' => [
'account' => [
'group_id' => 3,
'email' => 'test@test.com'
]
]
]
];
}
/**
* Creates a mock for Form object.
*
* @return MockObject
*/
private function getFormFactoryMock(): MockObject
{
/** @var AttributeMetadataInterfaceFactory $attributeMetadataFactory */
$attributeMetadataFactory = $this->objectManager->create(AttributeMetadataInterfaceFactory::class);
$booleanAttribute = $attributeMetadataFactory->create()
->setAttributeCode('boolean')
->setBackendType('boolean')
->setFrontendInput('boolean')
->setDefaultValue('1')
->setFrontendLabel('Yes/No');
/** @var Form|MockObject $form */
$form = $this->getMockBuilder(Form::class)
->disableOriginalConstructor()
->getMock();
$form->method('getUserAttributes')->willReturn([$booleanAttribute]);
$form->method('getSystemAttributes')->willReturn([$this->createCustomerGroupAttribute()]);
$formFactory = $this->getMockBuilder(FormFactory::class)
->disableOriginalConstructor()
->getMock();
$formFactory->method('create')->willReturn($form);
return $formFactory;
}
/**
* Creates a customer group attribute object.
*
* @return AttributeMetadataInterface
*/
private function createCustomerGroupAttribute(): AttributeMetadataInterface
{
/** @var Option $option1 */
$option1 = $this->objectManager->create(Option::class);
$option1->setValue(2);
$option1->setLabel('Wholesale');
/** @var Option $option2 */
$option2 = $this->objectManager->create(Option::class);
$option2->setValue(3);
$option2->setLabel('Retailer');
/** @var AttributeMetadataInterfaceFactory $attributeMetadataFactory */
$attributeMetadataFactory = $this->objectManager->create(AttributeMetadataInterfaceFactory::class);
$attribute = $attributeMetadataFactory->create()
->setAttributeCode('group_id')
->setBackendType('static')
->setFrontendInput('select')
->setOptions([$option1, $option2])
->setIsRequired(true);
return $attribute;
}
}
@@ -0,0 +1,273 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Form;
use Magento\Backend\Model\Session\Quote as QuoteSession;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Directory\Model\ResourceModel\Country\Collection;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Data\Form\Element\Fieldset;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\WebsiteInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\MockObject\MockObject as MockObject;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
*/
class AddressTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var Address
*/
private $block;
/**
* @var QuoteSession|MockObject
*/
private $quoteSession;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->quoteSession = $this->getMockBuilder(QuoteSession::class)
->disableOriginalConstructor()
->setMethods(['getCustomerId', 'getStore', 'getStoreId', 'getQuote'])
->getMock();
$this->block = $this->objectManager->create(
Address::class,
['sessionQuote' => $this->quoteSession]
);
}
/**
* Checks address collection.
*
* @magentoDataFixture Magento/Customer/Fixtures/customer_2_addresses.php
*/
public function testGetAddressCollection()
{
$website = $this->getWebsite('base');
$customer = $this->getCustomer('customer@example.com', (int)$website->getId());
$addresses = $customer->getAddresses();
$this->quoteSession->method('getCustomerId')
->willReturn($customer->getId());
$actual = $this->block->getAddressCollection();
self::assertNotEmpty($actual);
self::assertEquals($addresses, $actual);
}
/**
* Checks address collection output encoded to json.
*
* @magentoDataFixture Magento/Customer/Fixtures/customer_sec_website_2_addresses.php
*/
public function testGetAddressCollectionJson()
{
$website = $this->getWebsite('test');
$customer = $this->getCustomer('customer.web@example.com', (int)$website->getId());
$store = $this->getStore('fixture_second_store');
$this->quoteSession->method('getStore')
->willReturn($store);
$this->quoteSession->method('getCustomerId')
->willReturn($customer->getId());
$addresses = $customer->getAddresses();
$expected = [
0 => [
'firstname' => false,
'lastname' => false,
'company' => false,
'street' => '',
'city' => false,
'country_id' => 'US',
'region' => false,
'region_id' => false,
'postcode' => false,
'telephone' => false,
'vat_id' => false,
],
$addresses[0]->getId() => [
'firstname' => 'John',
'lastname' => 'Smith',
'company' => false,
'street' => 'Green str, 67',
'city' => 'Culver City',
'country_id' => 'US',
'region' => 'California',
'region_id' => 12,
'postcode' => '90230',
'telephone' => '3468676',
'vat_id' => false,
'prefix' => false,
'middlename' => false,
'suffix' => false,
'fax' => false
],
$addresses[1]->getId() => [
'telephone' => '845454465',
'postcode' => '10178',
'country_id' => 'DE',
'city' => 'Berlin',
'street' => 'Tunnel Alexanderpl',
'firstname' => 'John',
'lastname' => 'Smith',
'company' => false,
'region' => false,
'region_id' => 0,
'vat_id' => false,
'prefix' => false,
'middlename' => false,
'suffix' => false,
'fax' => false
]
];
$actual = json_decode($this->block->getAddressCollectionJson(), true);
self::assertEquals($expected, $actual);
}
/**
* Checks one line address formatting
*/
public function testGetAddressAsString()
{
$data = [
'firstname' => 'John',
'lastname' => 'Smith',
'company' => 'Test Company',
'street' => 'Green str, 67',
'city' => 'Culver City',
'country_id' => 'US',
'region' => 'California',
'region_id' => 12,
'postcode' => '90230',
'telephone' => '3468676',
];
$address = $this->objectManager->create(AddressInterface::class, ['data' => $data]);
$expected = 'John Smith, Green str, 67, Culver City, California 90230, United States';
self::assertEquals($expected, $this->block->getAddressAsString($address));
}
public function testGetForm()
{
$expectedFields = [
'prefix',
'firstname',
'middlename',
'lastname',
'suffix',
'company',
'street',
'city',
'country_id',
'region',
'region_id',
'postcode',
'telephone',
'fax',
'vat_id',
];
$form = $this->block->getForm();
self::assertEquals(1, $form->getElements()->count(), 'Form has invalid number of fieldsets');
/** @var Fieldset $fieldset */
$fieldset = $form->getElements()[0];
self::assertEquals(
count($expectedFields),
$fieldset->getElements()->count(),
'Form has invalid number of fields'
);
/** @var AbstractElement $element */
foreach ($fieldset->getElements() as $element) {
self::assertTrue(
in_array($element->getId(), $expectedFields),
sprintf('Unexpected field "%s" in form.', $element->getId())
);
}
/** @var \Magento\Framework\Data\Form\Element\Select $countryIdField */
$countryIdField = $fieldset->getElements()->searchById('country_id');
$actual = Xpath::getElementsCountForXpath('//option', $countryIdField->getElementHtml());
self::assertEquals($this->getNumberOfCountryOptions(), $actual);
}
/**
* Gets customer entity.
*
* @param string $email
* @param int $websiteId
* @return CustomerInterface
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getCustomer(string $email, int $websiteId): CustomerInterface
{
/** @var CustomerRepositoryInterface $repository */
$repository = $this->objectManager->get(CustomerRepositoryInterface::class);
return $repository->get($email, $websiteId);
}
/**
* Gets website by code.
*
* @param string $code
* @return WebsiteInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getWebsite(string $code): WebsiteInterface
{
/** @var WebsiteRepositoryInterface $repository */
$repository = $this->objectManager->get(WebsiteRepositoryInterface::class);
return $repository->get($code);
}
/**
* Gets store by code.
*
* @param string $code
* @return StoreInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getStore(string $code): StoreInterface
{
/** @var StoreRepositoryInterface $repository */
$repository = $this->objectManager->get(StoreRepositoryInterface::class);
return $repository->get($code);
}
/**
* @return int
*/
private function getNumberOfCountryOptions()
{
/** @var Collection $countryCollection */
$countryCollection = $this->objectManager->create(Collection::class);
return count($countryCollection->toOptionArray());
}
}
@@ -0,0 +1,201 @@
<?php
/**
* Test class for Form
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Order\Create;
use Magento\Backend\Model\Session\Quote as QuoteSession;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\RegionInterfaceFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\MockObject\MockObject as MockObject;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class FormTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Form
*/
private $block;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var QuoteSession|MockObject
*/
private $session;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->session = $this->getMockBuilder(QuoteSession::class)
->disableOriginalConstructor()
->setMethods(['getCustomerId', 'getQuote', 'getStoreId', 'getStore', 'getQuoteId'])
->getMock();
$this->session->method('getCustomerId')
->willReturn(1);
$this->session->method('getStoreId')
->willReturn(1);
$store = $this->getMockBuilder(Store::class)
->disableOriginalConstructor()
->setMethods(['getCurrentCurrencyCode'])
->getMock();
$store->method('getCurrentCurrencyCode')
->willReturn('USD');
$this->session->method('getStore')
->willReturn($store);
/** @var LayoutInterface $layout */
$layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $layout->createBlock(
Form::class,
'order_create_block' . random_int(0, PHP_INT_MAX),
['sessionQuote' => $this->session]
);
parent::setUp();
}
/**
* Checks if all needed order's data is correctly returned to the form.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Sales/_files/quote.php
*/
public function testOrderDataJson()
{
$customerId = 1;
$quote = $this->getQuote('test01');
$this->session->method('getQuote')
->willReturn($quote);
$this->session->method('getQuoteId')
->willReturn($quote->getId());
$addressData = $this->getAddressData();
$addressIds = $this->setUpMockAddress($customerId, $addressData);
$expected = [
'customer_id' => $customerId,
'addresses' => [
$addressIds[0] => $addressData[0],
$addressIds[1] => $addressData[1]
],
'store_id' => 1,
'currency_symbol' => '$',
'shipping_method_reseted' => true,
'payment_method' => 'checkmo',
'quote_id' => $quote->getId()
];
self::assertEquals($expected, json_decode($this->block->getOrderDataJson(), true));
}
/**
* Saves customer's addresses.
*
* @param int $customerId
* @param array $addressData
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function setUpMockAddress(int $customerId, array $addressData)
{
/** @var RegionInterfaceFactory $regionFactory */
$regionFactory = $this->objectManager->create(RegionInterfaceFactory::class);
/** @var AddressInterfaceFactory $addressFactory */
$addressFactory = $this->objectManager->create(AddressInterfaceFactory::class);
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = $this->objectManager->create(AddressRepositoryInterface::class);
$region = $regionFactory->create()
->setRegionCode('AL')
->setRegion('Alabama')
->setRegionId(1);
$ids = [];
foreach ($addressData as $data) {
$address = $addressFactory->create(['data' => $data]);
$address->setRegion($region)
->setCustomerId($customerId)
->setIsDefaultBilling(true)
->setIsDefaultShipping(true);
$address = $addressRepository->save($address);
$ids[] = $address->getId();
}
return $ids;
}
/**
* Gets test address data.
*
* @return array
*/
private function getAddressData(): array
{
return [
[
'firstname' => 'John',
'lastname' => 'Smith',
'company' => false,
'street' => 'Green str, 67',
'city' => 'CityM',
'country_id' => 'US',
'region' => 'Alabama',
'region_id' => 1,
'postcode' => '75477',
'telephone' => '3468676',
'vat_id' => false
],
[
'firstname' => 'John',
'lastname' => 'Smith',
'company' => false,
'street' => 'Black str, 48',
'city' => 'CityX',
'country_id' => 'US',
'region' => 'Alabama',
'region_id' => 1,
'postcode' => '47676',
'telephone' => '3234676',
'vat_id' => false,
]
];
}
/**
* Gets quote by ID.
*
* @param string $reservedOrderId
* @return Quote
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getQuote(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $repository */
$repository = $this->objectManager->get(CartRepositoryInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,33 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Order\Create\Giftmessage;
/**
* @magentoAppArea adminhtml
*/
class FormTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoAppIsolation enabled
*/
public function testGetDefaultSenderWithCurrentCustomer()
{
/** Preconditions */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$fixtureCustomerId = 1;
/** @var \Magento\Backend\Model\Session\Quote $backendQuoteSession */
$backendQuoteSession = $objectManager->get(\Magento\Backend\Model\Session\Quote::class);
$backendQuoteSession->setCustomerId($fixtureCustomerId);
/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Giftmessage\Form $block */
$block = $objectManager->create(\Magento\Sales\Block\Adminhtml\Order\Create\Giftmessage\Form::class);
$block->setEntity(new \Magento\Framework\DataObject());
/** SUT execution and assertions */
$this->assertEquals('John Smith', $block->getDefaultSender(), 'Sender name is invalid.');
}
}
@@ -0,0 +1,57 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Order\Create;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class HeaderTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Header */
protected $_block;
protected function setUp(): void
{
$this->_block = Bootstrap::getObjectManager()->create(
\Magento\Sales\Block\Adminhtml\Order\Create\Header::class
);
parent::setUp();
}
/**
* @param int|null $customerId
* @param int|null $storeId
* @param string $expectedResult
* @magentoDataFixture Magento/Customer/_files/customer.php
* @dataProvider toHtmlDataProvider
*/
public function testToHtml($customerId, $storeId, $expectedResult)
{
/** @var \Magento\Backend\Model\Session\Quote $session */
$session = Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session\Quote::class);
$session->setCustomerId($customerId);
$session->setStoreId($storeId);
$this->assertEquals($expectedResult, $this->_block->toHtml());
}
public function toHtmlDataProvider()
{
$customerIdFromFixture = 1;
$defaultStoreView = 1;
return [
'Customer and store' => [
$customerIdFromFixture,
$defaultStoreView,
'Create New Order for John Smith in Default Store View',
],
'No store' => [$customerIdFromFixture, null, 'Create New Order for John Smith'],
'No customer' => [null, $defaultStoreView, 'Create New Order in Default Store View'],
'No customer, no store' => [null, null, 'Create New Order for New Customer']
];
}
}
@@ -0,0 +1,69 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Items;
use Magento\Backend\Model\Session\Quote;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Block\Adminhtml\Order\Create\Items;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Checks order items grid
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class GridTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var Grid */
private $block;
/** @var Quote */
private $session;
/** @var GetQuoteByReservedOrderId */
private $getQuoteByReservedOrderId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
$this->session = $this->objectManager->get(Quote::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Grid::class);
$this->layout->createBlock(Items::class)->setChild('items_grid', $this->block);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testGetItems(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address');
$this->session->setQuoteId($quote->getId());
$items = $this->block->getItems();
$this->assertCount(1, $items);
$this->assertEquals('simple2', reset($items)->getSku());
}
}
@@ -0,0 +1,57 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Shipping;
use Magento\Customer\Model\Address\AddressModelInterface;
use Magento\Framework\View\Element\BlockInterface;
use Magento\Sales\Block\Adminhtml\Order\Create\AbstractAddressFormTest;
/**
* Class checks shipping address form behaviour
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class FormTest extends AbstractAddressFormTest
{
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address_saved.php
*
* @return void
*/
public function testFormValuesExist(): void
{
$this->checkFormValuesExist(1);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testFormValuesAreEmpty(): void
{
$this->checkFormValuesAreEmpty(1);
}
/**
* @inheritdoc
*/
protected function getFormBlock(): BlockInterface
{
return $this->layout->createBlock(Address::class);
}
/**
* @inheritdoc
*/
protected function getAddress(int $customerId): AddressModelInterface
{
return $this->customerRegistry->retrieve($customerId)->getDefaultShippingAddress();
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Create\Sidebar;
use Magento\Backend\Model\Session\Quote;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Model\QuoteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* Check sidebar shopping cart section block
*
* @see \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\Cart
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class CartTest extends TestCase
{
/** @var ObjectManager */
private $objectManager;
/** @var Cart */
private $block;
/** @var Quote */
private $session;
/** @var ProductRepository */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Cart::class);
$this->session = $this->objectManager->get(Quote::class);
$this->productRepository = $this->objectManager->get(ProductRepository::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->session->clearStorage();
$this->objectManager->removeSharedInstance(\Magento\Sales\Model\AdminOrder\Create::class, true);
$this->objectManager->removeSharedInstance(QuoteRepository::class);
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testGetItemCollection(): void
{
$this->session->setCustomerId(1);
$items = $this->block->getItemCollection();
$this->assertCount(1, $items);
$this->assertEquals('simple2', reset($items)->getSku());
}
/**
* @return void
*/
public function testClearShoppingCartButton(): void
{
$confirmation = __('Are you sure you want to delete all items from shopping cart?');
$button = $this->block->getChildBlock('empty_customer_cart_button');
$this->assertEquals(sprintf("order.clearShoppingCart('%s')", $confirmation), $button->getOnclick());
$this->assertEquals(__('Clear Shopping Cart'), $button->getLabel());
}
/**
* @magentoDataFixture Magento/Directory/_files/usd_cny_rate.php
* @magentoDataFixture Magento/Sales/_files/quote_with_two_products_and_customer_and_custom_price.php
*
* @magentoConfigFixture default/currency/options/base USD
* @magentoConfigFixture current_store currency/options/default CNY
* @magentoConfigFixture current_store currency/options/allow CNY,USD
*/
public function testGetItemPriceConvert()
{
$this->session->setCustomerId(1);
$customPrice = $this->block->getItemPrice($this->productRepository->get('simple'));
$this->assertStringContainsString('84.00', $customPrice);
$price = $this->block->getItemPrice($this->productRepository->get('custom-design-simple-product'));
$this->assertStringContainsString('70.00', $price);
}
}
@@ -0,0 +1,86 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Invoice\Create;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks invoiced items grid appearance
*
* @see \Magento\Sales\Block\Adminhtml\Order\Invoice\Create\Items
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class ItemsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Items */
private $block;
/** @var OrderFactory */
private $orderFactory;
/** @var Registry */
private $registry;
/** @var CollectionFactory */
private $invoiceCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Items::class);
$this->orderFactory = $this->objectManager->get(OrderFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->invoiceCollectionFactory = $this->objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_invoice');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/invoice.php
*
* @return void
*/
public function testGetUpdateButtonHtml(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$invoice = $this->invoiceCollectionFactory->create()->setOrderFilter($order)->setPageSize(1)->getFirstItem();
$this->registry->unregister('current_invoice');
$this->registry->register('current_invoice', $invoice);
$this->block->toHtml();
$button = $this->block->getChildBlock('update_button');
$this->assertEquals((string)__('Update Qty\'s'), (string)$button->getLabel());
$this->assertStringContainsString(
sprintf('sales/index/updateQty/order_id/%u/', (int)$order->getEntityId()),
$button->getOnClick()
);
}
}
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\Invoice;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class TotalsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Totals */
private $block;
/** @var OrderFactory */
private $orderFactory;
/** @var Registry */
private $registry;
/** @var CollectionFactory */
private $invoiceCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Totals::class);
$this->orderFactory = $this->objectManager->get(OrderFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->invoiceCollectionFactory = $this->objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_invoice');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_free_shipping_by_coupon_and_invoice.php
*
* @return void
*/
public function testCollectTotals(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$invoice = $this->invoiceCollectionFactory->create()->setOrderFilter($order)->setPageSize(1)->getFirstItem();
$this->registry->unregister('current_invoice');
$this->registry->register('current_invoice', $invoice);
$this->block->toHtml();
$totals = $this->block->getTotals();
$this->assertArrayHasKey('shipping', $totals);
$this->assertEquals('0.0000', $totals['shipping']['value']);
$this->assertEquals('Shipping & Handling (1234567890)', $totals['shipping']['label']);
}
}
@@ -0,0 +1,231 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Phrase;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Block\Adminhtml\Order\Totals\Tax;
use Magento\Sales\Model\Order;
use Magento\Tax\Model\ResourceModel\Sales\Order\Tax\Collection as TaxCollection;
use Magento\Tax\Model\Sales\Order\Tax as SalesTax;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
*/
class TotalsTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $om;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var OrderInterfaceFactory
*/
private $orderFactory;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->om = Bootstrap::getObjectManager();
$this->layout = $this->om->get(LayoutInterface::class);
$this->orderFactory = $this->om->get(OrderInterfaceFactory::class);
}
/**
* Test block totals including tax.
*
* @magentoConfigFixture default_store tax/sales_display/subtotal 2
* @magentoConfigFixture default_store tax/sales_display/shipping 2
* @magentoConfigFixture default_store tax/sales_display/full_summary 1
*
* @magentoDataFixture Magento/Tax/_files/order_with_tax.php
*
* @return void
*/
public function testTotalsInclTax(): void
{
$order = $this->prepareOrderInclTax('100000001');
$blockTotals = $this->getBlockTotals()->setOrder($order);
$this->assertSubtotal($blockTotals->toHtml(), (float) $order->getSubtotal());
$this->assertShipping($blockTotals->toHtml(), (float) $order->getShippingAmount());
$blockTax = $this->getBlockTax();
$blockTotals->setChild('child_tax_block', $blockTax);
$blockTax->initTotals();
/** @var TaxCollection $taxCollection */
$taxCollection = $this->om->get(TaxCollection::class);
$tax = $taxCollection->loadByOrder($order)->getItems();
$tax = array_pop($tax);
$this->assertTaxRate($blockTax->toHtml(), $tax);
$this->assertSubtotal($blockTotals->toHtml(), (float) $order->getSubtotalInclTax());
$this->assertShipping($blockTotals->toHtml(), (float) $order->getShippingInclTax());
}
/**
* Test block totals including canceled amount.
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testTotalCanceled(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$order->cancel();
$blockTotals = $this->getBlockTotals()->setOrder($order);
$this->assertCanceled($blockTotals->toHtml(), $order->getTotalCanceled());
}
/**
* Check if canceled amount present in block.
*
* @param string $blockTotalsHtml
* @param float $amount
* @return void
*/
private function assertCanceled(string $blockTotalsHtml, float $amount): void
{
$this->assertTrue(
$this->isBlockContainsTotalAmount($blockTotalsHtml, __('Total Canceled'), $amount),
'Canceled amount is missing or incorrect.'
);
}
/**
* Check if subtotal amount present in block.
*
* @param string $blockTotalsHtml
* @param float $amount
* @return void
*/
private function assertSubtotal(string $blockTotalsHtml, float $amount): void
{
$this->assertTrue(
$this->isBlockContainsTotalAmount($blockTotalsHtml, __('Subtotal'), $amount),
'Subtotal amount is missing or incorrect.'
);
}
/**
* Check if shipping amount present in block.
*
* @param string $blockTotalsHtml
* @param float $amount
* @return void
*/
private function assertShipping(string $blockTotalsHtml, float $amount): void
{
$this->assertTrue(
$this->isBlockContainsTotalAmount($blockTotalsHtml, __('Shipping & Handling'), $amount),
'Shipping & Handling amount is missing or incorrect.'
);
}
/**
* Check if tax rate present in block.
*
* @param string $blockTaxHtml
* @param SalesTax $tax
* @return void
*/
private function assertTaxRate(string $blockTaxHtml, SalesTax $tax)
{
$this->assertStringContainsString(
$tax->getTitle() . ' (' . (int)$tax->getAmount() . '%)',
$blockTaxHtml
);
}
/**
* Prepare order for test.
*
* @param string $incrementId
* @return Order
*/
private function prepareOrderInclTax(string $incrementId): Order
{
/** @var Order $order */
$order = $this->orderFactory->create()->loadByIncrementId($incrementId);
$order->setSubtotalInclTax(110);
$order->setBaseSubtotalInclTax(110);
$order->setShippingAmount(10);
$order->setBaseShippingAmount(10);
$order->setShippingInclTax(11);
$order->setBaseShippingInclTax(11);
return $order;
}
/**
* Create block totals.
*
* @return Totals
*/
private function getBlockTotals(): Totals
{
/** @var Totals $block */
$block = $this->layout->createBlock(Totals::class, 'block_totals');
$block->setTemplate('Magento_Sales::order/totals.phtml');
return $block;
}
/**
* Create block tax.
*
* @return Tax
*/
private function getBlockTax(): Tax
{
/** @var Tax $block */
$block = $this->layout->createBlock(Tax::class, 'block_tax');
$block->setTemplate('Magento_Sales::order/totals/tax.phtml');
return $block;
}
/**
* Check if amount present in appropriate block node.
*
* @param string $blockTotalsHtml
* @param Phrase $totalLabel
* @param float $totalAmount
* @return bool
*/
private function isBlockContainsTotalAmount(
string $blockTotalsHtml,
Phrase $totalLabel,
float $totalAmount
): bool {
$dom = new \DOMDocument();
$dom->loadHTML($blockTotalsHtml);
$query = sprintf(
"//tr[contains(., '%s')]//span[contains(text(), '%01.2f')]",
$totalLabel,
$totalAmount
);
return (bool) (new \DOMXPath($dom))->query($query)->count();
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order\View;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Sales\Model\Order;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Sales\Model\Order\Address\Renderer as OrderAddressRenderer;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Magento\Sales\Block\Adminhtml\Order\View\AddressInfo
*/
class AddressInfoTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var OrderAddressRenderer
*/
private $orderAddressRenderer;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->orderAddressRenderer = $this->objectManager->get(OrderAddressRenderer::class);
}
/**
* Verify customer address attributes (e.g. Company) are visible on second website order.
*
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
* @magentoDataFixture Magento/Sales/_files/order_on_second_website.php
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
public function testCompanyAddressAttributeVisibleForOrderOnSecondWebsite()
{
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$website = $storeManager->getWebsites(false, true)['base'];
$config = $this->objectManager->get(ReinitableConfigInterface::class);
$config->setValue(
'customer/address/company_show',
'websites',
'',
$website->getId()
);
$orderFixtureStore = $this->objectManager->create(Order::class)->loadByIncrementId('100000001');
$address = $orderFixtureStore->getBillingAddress();
self::assertStringContainsString('Test Company', $this->orderAddressRenderer->format($address, 'html'));
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Order\View;
/**
* Test class for \Magento\Sales\Block\Adminhtml\Order\View\Info
*/
class InfoTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Value for the user defined custom attribute, which is created by attribute_user_defined_customer.php fixture.
*/
const ORDER_USER_DEFINED_ATTRIBUTE_VALUE = 'custom_attr_value';
public function testCustomerGridAction()
{
$layout = $this->_objectManager->get(\Magento\Framework\View\LayoutInterface::class);
/** @var \Magento\Sales\Block\Adminhtml\Order\View\Info $infoBlock */
$infoBlock = $layout->createBlock(
\Magento\Sales\Block\Adminhtml\Order\View\Info::class,
'info_block' . random_int(0, PHP_INT_MAX),
[]
);
$result = $infoBlock->getCustomerAccountData();
$this->assertEquals([], $result, 'Customer has additional account data.');
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*/
public function testGetCustomerGroupName()
{
$layout = $this->_objectManager->get(\Magento\Framework\View\LayoutInterface::class);
/** @var \Magento\Sales\Block\Adminhtml\Order\View\Info $customerGroupBlock */
$customerGroupBlock = $layout->createBlock(
\Magento\Sales\Block\Adminhtml\Order\View\Info::class,
'info_block' . random_int(0, PHP_INT_MAX),
['registry' => $this->_putOrderIntoRegistry()]
);
$result = $customerGroupBlock->getCustomerGroupName();
$this->assertEquals('NOT LOGGED IN', $result);
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
* @magentoDataFixture Magento/Customer/_files/attribute_user_defined_customer.php
*/
public function testGetCustomerAccountData()
{
$layout = $this->_objectManager->get(\Magento\Framework\View\LayoutInterface::class);
$orderData = [
'customer_' . FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_NAME => self::ORDER_USER_DEFINED_ATTRIBUTE_VALUE,
];
/** @var \Magento\Sales\Block\Adminhtml\Order\View\Info $customerGroupBlock */
$customerGroupBlock = $layout->createBlock(
\Magento\Sales\Block\Adminhtml\Order\View\Info::class,
'info_block' . random_int(0, PHP_INT_MAX),
['registry' => $this->_putOrderIntoRegistry($orderData)]
);
$this->assertEquals(
[
200 => [
'label' => FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_FRONTEND_LABEL,
'value' => self::ORDER_USER_DEFINED_ATTRIBUTE_VALUE,
],
],
$customerGroupBlock->getCustomerAccountData()
);
}
/**
* @param array $additionalOrderData
* @return \Magento\Framework\Registry|\PHPUnit\Framework\MockObject\MockObject
*/
protected function _putOrderIntoRegistry(array $additionalOrderData = [])
{
$registry = $this->getMockBuilder(\Magento\Framework\Registry::class)->disableOriginalConstructor()->getMock();
$order = $this->_objectManager->get(
\Magento\Sales\Model\Order::class
)->load(
'100000001'
)->setData(
array_merge(['customer_group_id' => 0], $additionalOrderData)
);
$registry->expects($this->any())->method('registry')->with('current_order')->willReturn($order);
return $registry;
}
}
@@ -0,0 +1,115 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml\Order;
use Magento\Backend\Model\Search\AuthorizationMock;
use Magento\Framework\Authorization;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Checks order create block
*
* @see \Magento\Sales\Block\Adminhtml\Order\View
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class ViewTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var Registry */
private $registry;
/** @var OrderFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->addSharedInstance(
$this->objectManager->get(AuthorizationMock::class),
Authorization::class
);
$this->registry = $this->objectManager->get(Registry::class);
$this->orderFactory = $this->objectManager->get(OrderFactory::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('sales_order');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testInvoiceButton(): void
{
$this->registerOrder('100000001');
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
'//button[@id=\'order_invoice\']',
$this->layout->createBlock(View::class)->getButtonsHtml()
)
);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_bundle_and_invoiced.php
*
* @return void
*/
public function testInvoiceButtonIsNotVisible(): void
{
$this->registerOrder('100000001');
$this->assertEmpty(
Xpath::getElementsCountForXpath(
'//button[@id=\'order_invoice\']',
$this->layout->createBlock(View::class)->getButtonsHtml()
)
);
}
/**
* Register order
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(string $orderIncrementId): void
{
$order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);
$this->registry->unregister('sales_order');
$this->registry->register('sales_order', $order);
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Adminhtml\Report\Filter\Form;
/**
* @magentoAppArea adminhtml
*/
class CouponTest extends \PHPUnit\Framework\TestCase
{
/**
* Layout
*
* @var \Magento\Framework\View\LayoutInterface
*/
protected $_layout;
protected function setUp(): void
{
parent::setUp();
$this->_layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\View\LayoutInterface::class);
}
/**
* @covers \Magento\Sales\Block\Adminhtml\Report\Filter\Form\Coupon::_afterToHtml
*/
public function testAfterToHtml()
{
/** @var $block \Magento\Sales\Block\Adminhtml\Report\Filter\Form\Coupon */
$block = $this->_layout->createBlock(\Magento\Sales\Block\Adminhtml\Report\Filter\Form\Coupon::class);
$block->setFilterData(new \Magento\Framework\DataObject());
$html = $block->toHtml();
$expectedStrings = [
'FormElementDependenceController',
'sales_report_rules_list',
'sales_report_price_rule_type',
];
foreach ($expectedStrings as $expectedString) {
$this->assertStringContainsString($expectedString, $html);
}
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Adminhtml;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
/**
* Test class for \Magento\Sales\Block\Adminhtml\Totals
*/
class TotalsTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/** @var LayoutInterface */
private $layout;
/** @var Totals */
private $block;
/** @var OrderFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->layout = $this->_objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Totals::class, 'totals_block');
$this->orderFactory = $this->_objectManager->get(OrderFactory::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_free_shipping_by_coupon.php
*/
public function testShowShippingCoupon()
{
/** @var Order $order */
$order = $this->orderFactory->create();
$order->loadByIncrementId('100000001');
$this->block->setOrder($order);
$this->block->toHtml();
$shippingTotal = $this->block->getTotal('shipping');
$this->assertNotFalse($shippingTotal, 'Shipping method is absent on the total\'s block.');
$this->assertStringContainsString(
'1234567890',
$shippingTotal->getLabel(),
'Coupon code is absent in the shipping method label name.'
);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Order;
class CommentsTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Sales\Block\Order\Comments
*/
protected $_block;
protected function setUp(): void
{
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Sales\Block\Order\Comments::class
);
}
/**
* @param string $commentedEntity
* @param string $expectedClass
* @dataProvider getCommentsDataProvider
*/
public function testGetComments($commentedEntity, $expectedClass)
{
$commentedEntity = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create($commentedEntity);
$this->_block->setEntity($commentedEntity);
$comments = $this->_block->getComments();
$this->assertInstanceOf($expectedClass, $comments);
}
/**
* @return array
*/
public function getCommentsDataProvider()
{
return [
[
\Magento\Sales\Model\Order\Invoice::class,
\Magento\Sales\Model\ResourceModel\Order\Invoice\Comment\Collection::class,
],
[
\Magento\Sales\Model\Order\Creditmemo::class,
\Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment\Collection::class
],
[
\Magento\Sales\Model\Order\Shipment::class,
\Magento\Sales\Model\ResourceModel\Order\Shipment\Comment\Collection::class
]
];
}
/**
*/
public function testGetCommentsWrongEntityException()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$entity = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$this->_block->setEntity($entity);
$this->_block->getComments();
}
}
@@ -0,0 +1,251 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Creditmemo;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for view creditmemo items block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ItemsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var LayoutInterface */
private $layout;
/** @var Items */
private $block;
/** @var CreditmemoInterface */
private $creditmemo;
/** @var Registry */
private $registry;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var PageFactory */
private $pageFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Items::class, 'block');
$this->creditmemo = $this->objectManager->get(CreditmemoInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
parent::tearDown();
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetTotalsHtml(): void
{
$childBlock = $this->layout->addBlock(
Text::class,
'creditmemo_totals',
'block'
);
$expectedHtml = '<b>Any html</b>';
$this->assertEmpty($childBlock->getCreditmemo());
$this->assertNotEquals($expectedHtml, $this->block->getTotalsHtml($this->creditmemo));
$childBlock->setText($expectedHtml);
$actualHtml = $this->block->getTotalsHtml($this->creditmemo);
$this->assertSame($this->creditmemo, $childBlock->getCreditmemo());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetCommentsHtml(): void
{
$childBlock = $this->layout->addBlock(
Text::class,
'creditmemo_comments',
'block'
);
$expectedHtml = '<b>Any html</b>';
$this->assertEmpty($childBlock->getEntity());
$this->assertEmpty($childBlock->getTitle());
$this->assertNotEquals($expectedHtml, $this->block->getCommentsHtml($this->creditmemo));
$childBlock->setText($expectedHtml);
$actualHtml = $this->block->getCommentsHtml($this->creditmemo);
$this->assertSame($this->creditmemo, $childBlock->getEntity());
$this->assertNotEmpty($childBlock->getTitle());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testDisplayingCreditmemos(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$blockHtml = $this->renderCreditmemoItemsBlock();
$this->assertCreditmemosBlock($order, $blockHtml);
}
/**
* Assert creditmemos block.
*
* @param OrderInterface $order
* @param string $blockHtml
* @return void
*/
private function assertCreditmemosBlock(OrderInterface $order, string $blockHtml): void
{
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@href, 'sales/order/printCreditmemo/order_id/%s')]/span[contains(text(), '%s')]",
$order->getId(),
__('Print All Refunds')
),
$blockHtml
),
sprintf('%s button was not found.', __('Print All Refunds'))
);
$this->assertNotCount(0, $order->getCreditmemosCollection(), 'Creditmemos collection is empty');
foreach ($order->getCreditmemosCollection() as $creditmemo) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Refund #') . $creditmemo->getIncrementId()
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Refund #') . $creditmemo->getIncrementId())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@href, 'sales/order/printCreditmemo/creditmemo_id/%s')]"
. "/span[contains(text(), '%s')]",
$creditmemo->getId(),
__('Print Refund')
),
$blockHtml
),
sprintf('%s button for #%s was not found.', __('Print Refund'), $creditmemo->getIncrementId())
);
$this->assertCreditmemoItems($creditmemo, $blockHtml);
}
}
/**
* Assert creditmemo items list.
*
* @param CreditmemoInterface $creditmemo
* @param string $html
* @return void
*/
private function assertCreditmemoItems(CreditmemoInterface $creditmemo, string $html): void
{
$this->assertNotCount(0, $creditmemo->getItemsCollection(), 'Creditmemo items collection is empty');
$fieldsToCheck = [
'name' => "/td[contains(@class, 'name')]/strong[contains(text(), '%s')]",
'sku' => "/td[contains(@class, 'sku') and contains(text(), '%s')]",
'price' => "/td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'qty' => "/td[contains(@class, 'qty') and contains(text(), '%d')]",
'row_total' => "/td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
'discount_amount' => "/td[contains(@class, 'discount')]/span[contains(text(), '%01.2f')]",
];
foreach ($creditmemo->getItemsCollection() as $item) {
$rowXpath = sprintf(
"//table[@id='my-refund-table-%s']//tr[@id='order-item-row-%s']",
$creditmemo->getId(),
$item->getId()
);
foreach ($fieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($rowXpath . $xpath, $item->getData($key)), $html),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
}
/**
* Render creditmemo items block.
*
* @return string
*/
private function renderCreditmemoItemsBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_creditmemo',
]);
$page->getLayout()->generateXml();
$creditmemoItemsBlock = $page->getLayout()->getBlock('creditmemo_items')->unsetChild('creditmemo_totals');
$creditmemoItemsBlock->getRequest()->setRouteName('sales')->setControllerName('order')
->setActionName('creditmemo');
return $creditmemoItemsBlock->toHtml();
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Creditmemo;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for view creditmemo totals block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class TotalsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Totals */
private $block;
/** @var OrderInterfaceFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Totals::class)
->setTemplate('Magento_Sales::order/totals.phtml');
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testCreditmemoTotalsBlock(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$creditmemo = $order->getCreditmemosCollection()->getFirstItem();
$this->assertNotNull($creditmemo->getId());
$blockHtml = $this->block->setOrder($order)->setCreditmemo($creditmemo)->toHtml();
$message = '"%s" for creditmemo wasn\'t found or not equals to %01.2f';
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Subtotal'),
$creditmemo->getSubtotal()
),
$blockHtml
),
sprintf($message, __('Subtotal'), $creditmemo->getSubtotal())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Shipping & Handling'),
$creditmemo->getShippingAmount()
),
$blockHtml
),
sprintf($message, __('Shipping & Handling'), $creditmemo->getShippingAmount())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//tr[contains(@class, 'grand_total') and contains(.//strong, '%s')]"
. "//span[contains(text(), '%01.2f')]",
__('Grand Total'),
$creditmemo->getGrandTotal()
),
$blockHtml
),
sprintf($message, __('Grand Total'), $creditmemo->getGrandTotal())
);
}
}
@@ -0,0 +1,180 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order;
use Magento\Customer\Model\Session;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for customer order grid.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class HistoryTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Session */
private $customerSession;
/** @var History */
private $block;
/** @var OrderInterfaceFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->customerSession = $this->objectManager->get(Session::class);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(History::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerSession->logout();
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testCustomerOrderGridWithoutOrders(): void
{
$this->customerSession->loginById(1);
$this->assertStringContainsString(
(string)$this->block->getEmptyOrdersMessage(),
strip_tags($this->block->toHtml())
);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testCustomerOrderGridWithOrder(): void
{
$this->customerSession->loginById(1);
$this->assertCustomerOrderGrid(['100000001'], $this->block->toHtml());
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Sales/_files/orders_with_customer.php
*
* @return void
*/
public function testCustomerOrderGridWithSomeOrders(): void
{
$this->customerSession->loginById(1);
$ordersToCheck = ['100000002', '100000003', '100000004', '100000005', '100000006'];
$this->assertCustomerOrderGrid($ordersToCheck, $this->block->toHtml());
}
/**
* Assert customer order grid.
*
* @param array $ordersToCheck
* @param string $blockHtml
* @return void
*/
private function assertCustomerOrderGrid(array $ordersToCheck, string $blockHtml): void
{
foreach ($ordersToCheck as $orderIncrementId) {
$order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);
$rowXpath = sprintf("//td[contains(@class,'id') and contains(text(), '%s')]", $order->getRealOrderId());
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$rowXpath . "/following-sibling::td[contains(@class, 'date') and contains(text(), '%s')]",
$this->block->formatDate($order->getCreatedAt())
),
$blockHtml
),
sprintf('Created date for order #%s wasn\'t found in row.', $orderIncrementId)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$rowXpath . "/following-sibling::td[contains(@class, 'total')]/span[contains(text(), '%s')]",
$order->getTotal()
),
$blockHtml
),
sprintf(
'Order Totals for order #%s wasn\'t found or not equal to "%s" in row.',
$orderIncrementId,
$order->getTotal()
)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$rowXpath . "/following-sibling::td[contains(@class, 'status') and contains(text(), '%s')]",
$order->getStatusLabel()
),
$blockHtml
),
sprintf(
'Order status for order #%s wasn\'t found or not equal to "%s" in row.',
$orderIncrementId,
$order->getStatusLabel()
)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$rowXpath . "/following-sibling::td/a[contains(@href, 'sales/order/view/order_id/%s')]"
. "/span[contains(text(), '%s')]",
$order->getId(),
__('View Order')
),
$blockHtml
),
sprintf('View order button for order #%s wasn\'t found.', $orderIncrementId)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$rowXpath . "/following-sibling::td/a[contains(@data-post,"
. "'sales\/order\/reorder\/order_id\/%s')]/span[contains(text(), '%s')]",
$order->getId(),
__('Reorder')
),
$blockHtml
),
sprintf('Reorder button for order #%s wasn\'t found.', $orderIncrementId)
);
}
}
}
@@ -0,0 +1,115 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Info;
use Magento\Customer\Model\Session;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Test for order action buttons.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class ButtonsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var Session */
private $customerSession;
/** @var OrderInterface */
private $order;
/** @var Buttons */
private $block;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->customerSession = $this->objectManager->get(Session::class);
$this->order = $this->objectManager->get(OrderInterface::class);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Buttons::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
$this->customerSession->logout();
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testDisplayingOrderActionButtons(): void
{
$this->customerSession->loginById(1);
$order = $this->order->loadByIncrementId('100000001');
$this->registerOrder($order);
$blockHtml = $this->block->toHtml();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@data-post, 'sales\/order\/reorder\/order_id\/%s')]/span[contains(text(), '%s')]",
$order->getId(),
__('Reorder')
),
$blockHtml
),
sprintf('%s button wasn\'t found.', __('Reorder'))
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@href, 'sales/order/print/order_id/%s')]/span[contains(text(), '%s')]",
$order->getId(),
__('Print Order')
),
$blockHtml
),
sprintf('%s button wasn\'t found.', __('Print Order'))
);
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,172 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for order info block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class InfoTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var CountryFactory */
private $countryFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->countryFactory = $this->objectManager->get(CountryFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testOrderStatus(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$block = $this->layout->createBlock(Info::class)->setTemplate('Magento_Sales::order/order_status.phtml');
$this->assertStringContainsString((string)__($order->getStatusLabel()), strip_tags($block->toHtml()));
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testOrderDate(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$block = $this->layout->createBlock(Info::class)->setTemplate('Magento_Sales::order/order_date.phtml');
$this->assertStringContainsString(
(string)__('Order Date: %1', $block->formatDate($order->getCreatedAt(), \IntlDateFormatter::LONG)),
strip_tags($block->toHtml())
);
}
/**
* @magentoDataFixture Magento/Sales/_files/customer_order_with_two_items.php
*
* @return void
*/
public function testOrderInformation(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$blockHtml = $this->layout->createBlock(Info::class)->toHtml();
$this->assertOrderAddress($order->getShippingAddress(), $blockHtml);
$this->assertOrderAddress($order->getBillingAddress(), $blockHtml);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'box-order-shipping-method') and contains(.//span, '%s')]"
. "//div[contains(text(), '%s')]",
__('Shipping Method'),
$order->getShippingDescription()
),
$blockHtml
),
'Shipping method for order wasn\'t found.'
);
}
/**
* Assert order address.
*
* @param OrderAddressInterface $address
* @param string $html
* @return void
*/
private function assertOrderAddress(OrderAddressInterface $address, string $html): void
{
$addressBoxXpath = sprintf("//div[contains(@class, 'box-order-%s-address')]", $address->getAddressType())
. "//address[contains(., '%s')]";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getName()), $html),
sprintf('Customer name for %s address wasn\'t found.', $address->getAddressType())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$addressBoxXpath,
$this->countryFactory->create()->loadByCode($address->getData('country_id'))->getName()
),
$html
),
sprintf('Country for %s address wasn\'t found.', $address->getAddressType())
);
$attributes = ['company', 'street', 'city', 'region', 'postcode', 'telephone'];
foreach ($attributes as $key) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getData($key)), $html),
sprintf('%s for %s address wasn\'t found.', $key, $address->getAddressType())
);
}
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,245 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Invoice;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\Data\InvoiceInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for view invoice items block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ItemsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var Items */
private $block;
/** @var InvoiceInterfaceFactory */
private $invoiceFactory;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var PageFactory */
private $pageFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Items::class, 'block');
$this->invoiceFactory = $this->objectManager->get(InvoiceInterfaceFactory::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
parent::tearDown();
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetInvoiceTotalsHtml(): void
{
$childBlock = $this->layout->addBlock(Text::class, 'invoice_totals', 'block');
$expectedHtml = '<b>Any html</b>';
$this->assertEmpty($childBlock->getInvoice());
$invoice = $this->invoiceFactory->create();
$this->assertNotEquals($expectedHtml, $this->block->getInvoiceTotalsHtml($invoice));
$childBlock->setText($expectedHtml);
$actualHtml = $this->block->getInvoiceTotalsHtml($invoice);
$this->assertSame($invoice, $childBlock->getInvoice());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetInvoiceCommentsHtml(): void
{
$childBlock = $this->layout->addBlock(
Text::class,
'invoice_comments',
'block'
);
$expectedHtml = '<b>Any html</b>';
$this->assertEmpty($childBlock->getEntity());
$this->assertEmpty($childBlock->getTitle());
$invoice = $this->invoiceFactory->create();
$this->assertNotEquals($expectedHtml, $this->block->getInvoiceCommentsHtml($invoice));
$childBlock->setText($expectedHtml);
$actualHtml = $this->block->getInvoiceCommentsHtml($invoice);
$this->assertSame($invoice, $childBlock->getEntity());
$this->assertNotEmpty($childBlock->getTitle());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testDisplayingInvoices(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$blockHtml = $this->renderInvoiceItemsBlock();
$this->assertInvoicesBlock($order, $blockHtml);
}
/**
* Assert invoices block.
*
* @param OrderInterface $order
* @param string $blockHtml
* @return void
*/
private function assertInvoicesBlock(OrderInterface $order, string $blockHtml): void
{
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@href, 'sales/order/printInvoice/order_id/%s')]/span[contains(text(), '%s')]",
$order->getId(),
__('Print All Invoices')
),
$blockHtml
),
sprintf('%s button was not found.', __('Print All Invoices'))
);
$this->assertNotCount(0, $order->getInvoiceCollection(), 'Invoice collection is empty');
foreach ($order->getInvoiceCollection() as $invoice) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Invoice #') . $invoice->getIncrementId()
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Invoice #') . $invoice->getIncrementId())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//a[contains(@href, 'sales/order/printInvoice/invoice_id/%s')]/span[contains(text(), '%s')]",
$invoice->getId(),
__('Print Invoice')
),
$blockHtml
),
sprintf('%s button for #%s was not found.', __('Print Invoice'), $invoice->getIncrementId())
);
$this->assertInvoiceItems($invoice, $blockHtml);
}
}
/**
* Assert invoice items list.
*
* @param InvoiceInterface $invoice
* @param string $blockHtml
* @return void
*/
private function assertInvoiceItems(InvoiceInterface $invoice, string $blockHtml): void
{
$this->assertNotCount(0, $invoice->getItemsCollection(), 'Invoice items collection is empty');
$fieldsToCheck = [
'name' => "/td[contains(@class, 'name')]/strong[contains(text(), '%s')]",
'sku' => "/td[contains(@class, 'sku') and contains(text(), '%s')]",
'price' => "/td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'qty' => "/td[contains(@class, 'qty')]/span[contains(text(), '%d')]",
'row_total' => "/td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
];
foreach ($invoice->getItemsCollection() as $item) {
$itemRowXpath = sprintf(
"//table[@id='my-invoice-table-%s']//tr[@id='order-item-row-%s']",
$invoice->getId(),
$item->getId()
);
foreach ($fieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($itemRowXpath . $xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
}
/**
* Render invoice items block.
*
* @return string
*/
private function renderInvoiceItemsBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_invoice',
]);
$page->getLayout()->generateXml();
$invoiceItemsBlock = $page->getLayout()->getBlock('invoice_items')->unsetChild('invoice_totals');
$invoiceItemsBlock->getRequest()->setRouteName('sales')->setControllerName('order')->setActionName('invoice');
return $invoiceItemsBlock->toHtml();
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Invoice;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for view invoice totals block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class TotalsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Totals */
private $block;
/** @var OrderInterfaceFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Totals::class)
->setTemplate('Magento_Sales::order/totals.phtml');
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_free_shipping_by_coupon_and_invoice.php
*
* @return void
*/
public function testCollectTotals(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$invoice = $order->getInvoiceCollection()->getFirstItem();
$this->block->setOrder($order);
$this->block->setInvoice($invoice);
$this->block->toHtml();
$totals = $this->block->getTotals();
$this->assertArrayHasKey('shipping', $totals);
$this->assertEquals('0.0000', $totals['shipping']['value']);
$this->assertEquals('Shipping & Handling (1234567890)', $totals['shipping']['label']);
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testInvoiceTotalsBlock(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$invoice = $order->getInvoiceCollection()->getFirstItem();
$this->assertNotNull($invoice->getId());
$blockHtml = $this->block->setOrder($order)->setInvoice($invoice)->toHtml();
$message = '"%s" for invoice wasn\'t found or not equals to %01.2f';
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Subtotal'),
$invoice->getSubtotal()
),
$blockHtml
),
sprintf($message, __('Subtotal'), $invoice->getSubtotal())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Shipping & Handling'),
$invoice->getShippingAmount()
),
$blockHtml
),
sprintf($message, __('Shipping & Handling'), $invoice->getShippingAmount())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//tr[contains(@class, 'grand_total') and contains(.//strong, '%s')]"
. "//span[contains(text(), '%01.2f')]",
__('Grand Total'),
$invoice->getGrandTotal()
),
$blockHtml
),
sprintf($message, __('Grand Total'), $invoice->getGrandTotal())
);
}
}
@@ -0,0 +1,272 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\Item\Renderer;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for default renderer order items.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class DefaultRendererTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var DefaultRenderer */
private $block;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var PageFactory */
private $pageFactory;
/** @var Registry */
private $registry;
/**
* @var array
*/
private $defaultFieldsToCheck = [
'name' => "//td[contains(@class, 'name')]/strong[contains(text(), '%s')]",
'sku' => "//td[contains(@class, 'sku') and contains(text(), '%s')]",
'qty' => "//td[contains(@class, 'qty') and contains(text(), '%d')]",
];
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(DefaultRenderer::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/shipment_for_order_with_customer.php
*
* @return void
*/
public function testDisplayingShipmentItem(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$shipment = $order->getShipmentsCollection()->getFirstItem();
$this->assertNotNull($shipment->getId());
$item = $shipment->getAllItems()[0] ?? null;
$this->assertNotNull($item);
$blockHtml = $this->block->setTemplate('Magento_Sales::order/shipment/items/renderer/default.phtml')
->setItem($item)->toHtml();
foreach ($this->defaultFieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testCreditmemoItemTotalAmount(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$creditmemo = $order->getCreditmemosCollection()->getFirstItem();
$this->assertNotNull($creditmemo->getId());
$item = $creditmemo->getItemsCollection()->getFirstItem();
$this->assertNotNull($item->getId());
$this->assertEquals(10.00, $this->block->getTotalAmount($item));
}
/**
* @magentoDataFixture Magento/Sales/_files/customer_order_with_two_items.php
*
* @return void
*/
public function testPrintOrderItem(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$item = $order->getItemsCollection()->getFirstItem();
$this->assertNotNull($item->getId());
$block = $this->getBlock('sales_order_print', 'sales.order.print.renderers.default');
$this->assertNotFalse($block);
$blockHtml = $block->setItem($item)->toHtml();
$fieldsToCheck = [
'name' => "//td[contains(@class, 'name')]/strong[contains(text(), '%s')]",
'sku' => "//td[contains(@class, 'sku') and contains(text(), '%s')]",
'price' => "//td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'qty_ordered' => "//td[contains(@class, 'qty')]//span[contains(text(), '" . __('Ordered')
. "')]/following-sibling::span[contains(text(), '%d')]",
'row_total' => "//td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
];
foreach ($fieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testPrintInvoiceItem(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$invoice = $order->getInvoiceCollection()->getFirstItem();
$this->assertNotNull($invoice->getId());
$item = $invoice->getItemsCollection()->getFirstItem();
$this->assertNotNull($item->getId());
$block = $this->getBlock('sales_order_printinvoice', 'sales.order.print.invoice.renderers.default');
$this->assertNotFalse($block);
$blockHtml = $block->setItem($item)->toHtml();
$additionalFields = [
'price' => "//td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'qty' => "//td[contains(@class, 'qty')]/span[contains(text(), '%d')]",
'row_total' => "//td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
];
$this->defaultFieldsToCheck = array_merge($this->defaultFieldsToCheck, $additionalFields);
foreach ($this->defaultFieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
/**
* @magentoDataFixture Magento/Sales/_files/shipment_for_order_with_customer.php
*
* @return void
*/
public function testPrintShipmentItem(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$shipment = $order->getShipmentsCollection()->getFirstItem();
$this->assertNotNull($shipment->getId());
$item = $shipment->getAllItems()[0] ?? null;
$this->assertNotNull($item);
$block = $this->getBlock('sales_order_printshipment', 'sales.order.print.shipment.renderers.default');
$this->assertNotFalse($block);
$blockHtml = $block->setItem($item)->toHtml();
foreach ($this->defaultFieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testPrintCreditmemoItem(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$creditmemo = $order->getCreditmemosCollection()->getFirstItem();
$this->assertNotNull($creditmemo->getId());
$item = $creditmemo->getItemsCollection()->getFirstItem();
$this->assertNotNull($item->getId());
$block = $this->getBlock('sales_order_printcreditmemo', 'sales.order.print.creditmemo.renderers.default');
$this->assertNotFalse($block);
$blockHtml = $block->setItem($item)->toHtml();
$additionalFields = [
'price' => "//td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'row_total' => "//td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
'discount_amount' => "//td[contains(@class, 'discount')]/span[contains(text(), '%01.2f')]",
];
$this->defaultFieldsToCheck = array_merge($this->defaultFieldsToCheck, $additionalFields);
foreach ($this->defaultFieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//td[contains(@class, 'total')]/span[contains(text(), '%01.2f')]",
$this->block->getTotalAmount($item)
),
$blockHtml
),
sprintf('Item total wasn\'t found or not equals to %s.', $this->block->getTotalAmount($item))
);
}
/**
* Get block.
*
* @param string $handle
* @param string $blockName
* @return AbstractBlock
*/
private function getBlock(string $handle, string $blockName): AbstractBlock
{
$page = $this->pageFactory->create();
$page->addHandle(['default', $handle]);
$page->getLayout()->generateXml();
return $page->getLayout()->getBlock($blockName);
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,242 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Model\ResourceModel\Order\Item\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\Theme\Block\Html\Pager;
use PHPUnit\Framework\TestCase;
/**
* Tests order items block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ItemsTest extends TestCase
{
/** @var Items */
private $block;
/** @var LayoutInterface */
private $layout;
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var PageFactory */
private $pageFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testGetOrderItems(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->block = $this->layout->createBlock(Items::class);
$this->assertCount(1, $this->block->getItems());
}
/**
* @magentoDataFixture Magento/Sales/_files/order_configurable_product.php
*
* @return void
*/
public function testGetPagerCountConfigurable(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->prepareBlockWithPager();
/** @var Pager $pagerBlock */
$pagerBlock = $this->block->getChildBlock('sales_order_item_pager');
$this->assertCount(1, $pagerBlock->getCollection()->getItems());
}
/**
* @magentoConfigFixture default/sales/orders/items_per_page 3
* @magentoDataFixture Magento/Sales/_files/order_item_list.php
*
* @return void
*/
public function testPagerIsDisplayed(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->prepareBlockWithPager();
$this->assertTrue($this->block->isPagerDisplayed());
}
/**
* @magentoDataFixture Magento/Sales/_files/order_item_list.php
*
* @return void
*/
public function testPagerIsNotDisplayed(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->prepareBlockWithPager();
$this->assertFalse($this->block->isPagerDisplayed());
$this->assertEmpty(preg_replace('/\s+/', '', strip_tags($this->block->getPagerHtml())));
}
/**
* @magentoConfigFixture default/sales/orders/items_per_page 3
* @magentoDataFixture Magento/Sales/_files/order_item_list.php
*
* @return void
*/
public function testGetPagerHtml(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->prepareBlockWithPager();
$this->assertNotEmpty(preg_replace('/\s+/', '', strip_tags($this->block->getPagerHtml())));
$this->assertTrue($this->block->isPagerDisplayed());
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testGetOrder(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$this->block = $this->layout->createBlock(Items::class, 'items_block');
$this->assertEquals($order, $this->block->getOrder());
}
/**
* @magentoDataFixture Magento/Sales/_files/customer_order_with_two_items.php
*
* @return void
*/
public function testDisplayingOrderItems(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$blockHtml = $this->renderOrderItemsBlock();
$this->assertOrderItems($order->getItemsCollection(), $blockHtml);
}
/**
* Render order items block.
*
* @return string
*/
private function renderOrderItemsBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_view',
]);
$page->getLayout()->generateXml();
$orderItemsBlock = $page->getLayout()->getBlock('order_items')->unsetChild('order_totals');
return $orderItemsBlock->toHtml();
}
/**
* Assert order items list.
*
* @param Collection $orderItems
* @param string $blockHtml
* @return void
*/
private function assertOrderItems(Collection $orderItems, string $blockHtml): void
{
$this->assertNotCount(0, $orderItems, 'Order items collection is empty');
$fieldsToCheck = [
'name' => "/td[contains(@class, 'name')]/strong[contains(text(), '%s')]",
'sku' => "/td[contains(@class, 'sku') and contains(text(), '%s')]",
'price' => "/td[contains(@class, 'price')]//span[contains(text(), '%01.2f')]",
'qty_ordered' => "/td[contains(@class, 'qty')]//span[contains(text(), '" . __('Ordered')
. "')]/following-sibling::span[contains(text(), '%d')]",
'row_total' => "/td[contains(@class, 'subtotal')]//span[contains(text(), '%01.2f')]",
];
foreach ($orderItems as $item) {
$itemRowXpath = sprintf("//tr[@id='order-item-row-%s']", $item->getItemId());
foreach ($fieldsToCheck as $key => $xpath) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($itemRowXpath . $xpath, $item->getData($key)), $blockHtml),
sprintf('Item %s wasn\'t found or not equals to %s.', $key, $item->getData($key))
);
}
}
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
/**
* Create items block with pager
*/
private function prepareBlockWithPager(): void
{
$this->block = $this->layout->createBlock(Items::class, 'items_block');
$this->layout->addBlock(
$this->objectManager->get(Pager::class),
'sales_order_item_pager',
'items_block'
);
$this->block->setLayout($this->layout);
}
}
@@ -0,0 +1,270 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\PrintOrder;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\CreditmemoInterfaceFactory;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\Data\OrderPaymentInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for print creditmemo block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CreditmemoTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var CreditmemoInterfaceFactory */
private $creditmemoFactory;
/** @var PageFactory */
private $pageFactory;
/** @var CountryFactory */
private $countryFactory;
/** @var OrderPaymentInterfaceFactory */
private $orderPaymentFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->creditmemoFactory = $this->objectManager->get(CreditmemoInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->countryFactory = $this->objectManager->get(CountryFactory::class);
$this->orderPaymentFactory = $this->objectManager->create(OrderPaymentInterfaceFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
$this->registry->unregister('current_creditmemo');
parent::tearDown();
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetTotalsHtml(): void
{
$order = $this->orderFactory->create();
$this->registerOrder($order);
$payment = $this->orderPaymentFactory->create();
$payment->setMethod('checkmo');
$order->setPayment($payment);
$block = $this->layout->createBlock(Creditmemo::class, 'block');
$childBlock = $this->layout->addBlock(Text::class, 'creditmemo_totals', 'block');
$expectedHtml = '<b>Any html</b>';
$creditmemo = $this->creditmemoFactory->create();
$this->assertEmpty($childBlock->getCreditmemo());
$this->assertNotEquals($expectedHtml, $block->getTotalsHtml($creditmemo));
$childBlock->setText($expectedHtml);
$actualHtml = $block->getTotalsHtml($creditmemo);
$this->assertSame($creditmemo, $childBlock->getCreditmemo());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testPrintCreditmemo(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$creditmemo = $order->getCreditmemosCollection()->getFirstItem();
$this->assertNotNull($creditmemo->getId());
$this->registerOrder($order);
$this->registerCreditmemo($creditmemo);
$blockHtml = $this->renderPrintCreditmemoBlock();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Refund #%1', $creditmemo->getIncrementId())
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Refund #%1', $creditmemo->getIncrementId()))
);
$this->assertOrderInformation($order, $blockHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/refunds_for_items.php
*
* @return void
*/
public function testOrderInformation(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$block = $this->layout->createBlock(Creditmemo::class);
$orderDate = $block->formatDate($order->getCreatedAt(), \IntlDateFormatter::LONG);
$templates = [
'Order status' => [
'template' => 'Magento_Sales::order/order_status.phtml',
'expected_data' => (string)__($order->getStatusLabel()),
],
'Order date' => [
'template' => 'Magento_Sales::order/order_date.phtml',
'expected_data' => (string)__('Order Date: %1', $orderDate),
],
];
foreach ($templates as $key => $data) {
$this->assertStringContainsString(
$data['expected_data'],
strip_tags($block->setTemplate($data['template'])->toHtml()),
sprintf('%s wasn\'t found.', $key)
);
}
}
/**
* Assert order information block.
*
* @param OrderInterface $order
* @param string $html
* @return void
*/
private function assertOrderInformation(OrderInterface $order, string $html): void
{
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
"//div[contains(@class, 'block-order-details-view')]"
. "//strong[contains(text(), '" . __('Order Information') . "')]",
$html
),
__('Order Information') . ' title wasn\'t found.'
);
foreach ([$order->getShippingAddress(), $order->getBillingAddress()] as $address) {
$addressBoxXpath = sprintf("//div[contains(@class, 'box-order-%s-address')]", $address->getAddressType())
. "//address[contains(., '%s')]";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getName()), $html),
sprintf('Customer name for %s address wasn\'t found.', $address->getAddressType())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$addressBoxXpath,
$this->countryFactory->create()->loadByCode($address->getData('country_id'))->getName()
),
$html
),
sprintf('Country for %s address wasn\'t found.', $address->getAddressType())
);
$attributes = ['company', 'street', 'city', 'region', 'postcode', 'telephone'];
foreach ($attributes as $key) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getData($key)), $html),
sprintf('%s for %s address wasn\'t found.', $key, $address->getAddressType())
);
}
}
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'box-order-shipping-method') and contains(.//strong, '%s')]"
. "//div[contains(text(), '%s')]",
__('Shipping Method'),
$order->getShippingDescription()
),
$html
),
'Shipping method for order wasn\'t found.'
);
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
/**
* Register creditmemo in registry.
*
* @param CreditmemoInterface $creditmemo
* @return void
*/
private function registerCreditmemo(CreditmemoInterface $creditmemo): void
{
$this->registry->unregister('current_creditmemo');
$this->registry->register('current_creditmemo', $creditmemo);
}
/**
* Render print creditmemo block.
*
* @return string
*/
private function renderPrintCreditmemoBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_printcreditmemo',
]);
$page->getLayout()->generateXml();
$printCreditmemoBlock = $page->getLayout()->getBlock('sales.order.print.creditmemo');
$this->assertNotFalse($printCreditmemoBlock);
return $printCreditmemoBlock->toHtml();
}
}
@@ -0,0 +1,301 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\PrintOrder;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\InvoiceInterfaceFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\Data\OrderPaymentInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for print invoice block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class InvoiceTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var InvoiceInterfaceFactory */
private $invoiceFactory;
/** @var PageFactory */
private $pageFactory;
/** @var CountryFactory */
private $countryFactory;
/** @var OrderPaymentInterfaceFactory */
private $orderPaymentFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->invoiceFactory = $this->objectManager->get(InvoiceInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->countryFactory = $this->objectManager->get(CountryFactory::class);
$this->orderPaymentFactory = $this->objectManager->create(OrderPaymentInterfaceFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
$this->registry->unregister('current_invoice');
parent::tearDown();
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testGetInvoiceTotalsHtml(): void
{
$order = $this->orderFactory->create();
$this->registerOrder($order);
$payment = $this->orderPaymentFactory->create();
$payment->setMethod('checkmo');
$order->setPayment($payment);
$block = $this->layout->createBlock(Invoice::class, 'block');
$childBlock = $this->layout->addBlock(Text::class, 'invoice_totals', 'block');
$expectedHtml = '<b>Any html</b>';
$invoice = $this->invoiceFactory->create();
$this->assertEmpty($childBlock->getInvoice());
$this->assertNotEquals($expectedHtml, $block->getInvoiceTotalsHtml($invoice));
$childBlock->setText($expectedHtml);
$actualHtml = $block->getInvoiceTotalsHtml($invoice);
$this->assertSame($invoice, $childBlock->getInvoice());
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testPrintInvoice(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$invoice = $order->getInvoiceCollection()->getFirstItem();
$this->assertNotNull($invoice->getId());
$this->assertTrue(is_numeric($invoice->getIncrementId()));
$this->registerOrder($order);
$this->registerInvoice($invoice);
$blockHtml = $this->renderPrintInvoiceBlock();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Invoice #%1', $invoice->getIncrementId())
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Invoice #%1', $invoice->getIncrementId()))
);
$this->assertOrderInformation($order, $blockHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testPrintInvoiceWithStringPrefix(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$invoice = $order->getInvoiceCollection()->getFirstItem();
$this->assertNotNull($invoice->getId());
// set text prefix to increment id
$invoice->setIncrementId('prefix-' . $invoice->getIncrementId());
$this->assertFalse(is_numeric($invoice->getIncrementId()));
$this->registerOrder($order);
$this->registerInvoice($invoice);
$blockHtml = $this->renderPrintInvoiceBlock();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Invoice #%1', $invoice->getIncrementId())
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Invoice #%1', $invoice->getIncrementId()))
);
$this->assertOrderInformation($order, $blockHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/invoices_for_items.php
*
* @return void
*/
public function testOrderInformation(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$block = $this->layout->createBlock(Invoice::class);
$orderDate = $block->formatDate($order->getCreatedAt(), \IntlDateFormatter::LONG);
$templates = [
'Order status' => [
'template' => 'Magento_Sales::order/order_status.phtml',
'expected_data' => (string)__($order->getStatusLabel()),
],
'Order date' => [
'template' => 'Magento_Sales::order/order_date.phtml',
'expected_data' => (string)__('Order Date: %1', $orderDate),
],
];
foreach ($templates as $key => $data) {
$this->assertStringContainsString(
$data['expected_data'],
strip_tags($block->setTemplate($data['template'])->toHtml()),
sprintf('%s wasn\'t found.', $key)
);
}
}
/**
* Assert order information block.
*
* @param OrderInterface $order
* @param string $html
* @return void
*/
private function assertOrderInformation(OrderInterface $order, string $html): void
{
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
"//div[contains(@class, 'block-order-details-view')]"
. "//strong[contains(text(), '" . __('Order Information') . "')]",
$html
),
__('Order Information') . ' title wasn\'t found.'
);
foreach ([$order->getShippingAddress(), $order->getBillingAddress()] as $address) {
$addressBoxXpath = sprintf("//div[contains(@class, 'box-order-%s-address')]", $address->getAddressType())
. "//address[contains(., '%s')]";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getName()), $html),
sprintf('Customer name for %s address wasn\'t found.', $address->getAddressType())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$addressBoxXpath,
$this->countryFactory->create()->loadByCode($address->getData('country_id'))->getName()
),
$html
),
sprintf('Country for %s address wasn\'t found.', $address->getAddressType())
);
$attributes = ['company', 'street', 'city', 'region', 'postcode', 'telephone'];
foreach ($attributes as $key) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getData($key)), $html),
sprintf('%s for %s address wasn\'t found.', $key, $address->getAddressType())
);
}
}
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'box-order-shipping-method') and contains(.//strong, '%s')]"
. "//div[contains(text(), '%s')]",
__('Shipping Method'),
$order->getShippingDescription()
),
$html
),
'Shipping method for order wasn\'t found.'
);
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
/**
* Register invoice in registry.
*
* @param InvoiceInterface $invoice
* @return void
*/
private function registerInvoice(InvoiceInterface $invoice): void
{
$this->registry->unregister('current_invoice');
$this->registry->register('current_invoice', $invoice);
}
/**
* Render print invoice block.
*
* @return string
*/
private function renderPrintInvoiceBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_printinvoice',
]);
$page->getLayout()->generateXml();
$printInvoiceBlock = $page->getLayout()->getBlock('sales.order.print.invoice');
$this->assertNotFalse($printInvoiceBlock);
return $printInvoiceBlock->toHtml();
}
}
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Block\Order\PrintOrder;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\State;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\ViewModel\Header\LogoPathResolver as LogoPathResolverSales;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Theme\Block\Html\Header\Logo;
use Magento\Theme\ViewModel\Block\Html\Header\LogoPathResolver as LogoPathResolverDefault;
use PHPUnit\Framework\TestCase;
class LogoTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var WriteInterface
*/
private $mediaDirectory;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$filesystem = $this->objectManager->get(Filesystem::class);
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->objectManager->get(State::class)
->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
Bootstrap::getInstance()
->loadArea(\Magento\Framework\App\Area::AREA_FRONTEND);
}
/**
* @magentoConfigFixture default_store design/header/logo_src default/logo.jpg
* @magentoConfigFixture default_store sales/identity/logo_html default/logo_sales.jpg
* @throws \Magento\Framework\Exception\FileSystemException
*/
public function testGetLogoSrc(): void
{
$host = 'http://localhost/media/';
$defaultLogoFile= 'logo.jpg';
$defaultPath = 'logo/default/' . $defaultLogoFile;
$salesLogoFile = 'logo_sales.jpg';
$salesPath = 'sales/store/logo_html/default/' . $salesLogoFile;
$this->mediaDirectory->writeFile($defaultPath, '');
$this->mediaDirectory->writeFile($salesPath, '');
$blockArguments = ['data' =>
['logoPathResolver' => $this->objectManager->get(LogoPathResolverDefault::class)]
];
/** @var Logo $block */
$block = $this->objectManager->create(LayoutInterface::class)
->createBlock(Logo::class, 'logo', $blockArguments);
$this->assertSame($host . $defaultPath, $block->getLogoSrc());
$blockArguments = ['data' =>
['logoPathResolver' => $this->objectManager->get(LogoPathResolverSales::class)]
];
/** @var Logo $block */
$block = $this->objectManager->create(LayoutInterface::class)
->createBlock(Logo::class, 'logo', $blockArguments);
$this->assertSame($host . $salesPath, $block->getLogoSrc());
$this->mediaDirectory->delete($defaultPath);
$this->mediaDirectory->delete($salesPath);
}
/**
* Checks that fallback to header logo works fine
*
* @magentoConfigFixture default_store design/header/logo_src default/logo.jpg
* @throws \Magento\Framework\Exception\FileSystemException
*/
public function testGetLogoSrcWithFallback(): void
{
$host = 'http://localhost/media/';
$defaultLogoFile = 'logo.jpg';
$defaultPath = 'logo/default/' . $defaultLogoFile;
$this->mediaDirectory->writeFile($defaultPath, '');
$blockArguments = ['data' =>
['logoPathResolver' => $this->objectManager->get(LogoPathResolverDefault::class)]
];
/** @var Logo $block */
$block = $this->objectManager->create(LayoutInterface::class)
->createBlock(Logo::class, 'logo', $blockArguments);
$this->assertSame($host . $defaultPath, $block->getLogoSrc());
$blockArguments = ['data' =>
['logoPathResolver' => $this->objectManager->get(LogoPathResolverSales::class)]
];
/** @var Logo $block */
$block = $this->objectManager->create(LayoutInterface::class)
->createBlock(Logo::class, 'logo', $blockArguments);
$this->assertSame($host . $defaultPath, $block->getLogoSrc());
$this->mediaDirectory->delete($defaultPath);
}
}
@@ -0,0 +1,237 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order\PrintOrder;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for print shipment block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ShipmentTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var LayoutInterface */
private $layout;
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var PageFactory */
private $pageFactory;
/** @var CountryFactory */
private $countryFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
$this->pageFactory = $this->objectManager->get(PageFactory::class);
$this->countryFactory = $this->objectManager->get(CountryFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('current_order');
$this->registry->unregister('current_shipment');
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/shipment_for_two_items.php
*
* @return void
*/
public function testPrintShipment(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$this->registerOrder($order);
$shipment = $order->getShipmentsCollection()->getFirstItem();
$this->assertNotNull($shipment->getId());
$this->registerOrder($order);
$this->registerShipment($shipment);
$blockHtml = $this->renderPrintShipmentBlock();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'order-title')]/strong[contains(text(), '%s')]",
__('Shipment #%1', $shipment->getIncrementId())
),
$blockHtml
),
sprintf('Title for %s was not found.', __('Shipment #%1', $shipment->getIncrementId()))
);
$this->assertOrderInformation($order, $blockHtml);
}
/**
* @magentoDataFixture Magento/Sales/_files/shipment_for_order_with_customer.php
*
* @return void
*/
public function testOrderInformation(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$block = $this->layout->createBlock(Shipment::class);
$orderDate = $block->formatDate($order->getCreatedAt(), \IntlDateFormatter::LONG);
$templates = [
'Order status' => [
'template' => 'Magento_Sales::order/order_status.phtml',
'expected_data' => (string)__($order->getStatusLabel()),
],
'Order date' => [
'template' => 'Magento_Sales::order/order_date.phtml',
'expected_data' => (string)__('Order Date: %1', $orderDate),
],
];
foreach ($templates as $key => $data) {
$this->assertStringContainsString(
$data['expected_data'],
strip_tags($block->setTemplate($data['template'])->toHtml()),
sprintf('%s wasn\'t found.', $key)
);
}
}
/**
* Assert order information block.
*
* @param OrderInterface $order
* @param string $html
* @return void
*/
private function assertOrderInformation(OrderInterface $order, string $html): void
{
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
"//div[contains(@class, 'block-order-details-view')]"
. "//strong[contains(text(), '" . __('Order Information') . "')]",
$html
),
__('Order Information') . ' title wasn\'t found.'
);
foreach ([$order->getShippingAddress(), $order->getBillingAddress()] as $address) {
$addressBoxXpath = ($address->getAddressType() == 'shipping')
? "//div[contains(@class, 'box-order-shipping-address')]//address[contains(., '%s')]"
: "//div[contains(@class, 'box-order-billing-address')]//address[contains(., '%s')]";
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getName()), $html),
sprintf('Customer name for %s address wasn\'t found.', $address->getAddressType())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
$addressBoxXpath,
$this->countryFactory->create()->loadByCode($address->getData('country_id'))->getName()
),
$html
),
sprintf('Country for %s address wasn\'t found.', $address->getAddressType())
);
$attributes = ['company', 'street', 'city', 'region', 'postcode', 'telephone'];
foreach ($attributes as $key) {
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(sprintf($addressBoxXpath, $address->getData($key)), $html),
sprintf('%s for %s address wasn\'t found.', $key, $address->getAddressType())
);
}
}
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//div[contains(@class, 'box-order-shipping-method') and contains(.//strong, '%s')]"
. "//div[contains(text(), '%s')]",
__('Shipping Method'),
$order->getShippingDescription()
),
$html
),
'Shipping method for order wasn\'t found.'
);
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
/**
* Register shipment in registry.
*
* @param ShipmentInterface $shipment
* @return void
*/
private function registerShipment(ShipmentInterface $shipment): void
{
$this->registry->unregister('current_shipment');
$this->registry->register('current_shipment', $shipment);
}
/**
* Render print shipment block.
*
* @return string
*/
private function renderPrintShipmentBlock(): string
{
$page = $this->pageFactory->create();
$page->addHandle([
'default',
'sales_order_printshipment',
]);
$page->getLayout()->generateXml();
$printShipmentBlock = $page->getLayout()->getBlock('sales.order.print.shipment');
$this->assertNotFalse($printShipmentBlock);
return $printShipmentBlock->toHtml();
}
}
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Layout;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for print shipment block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class PrintShipmentTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var Layout */
private $layout;
/** @var OrderInterfaceFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/shipment_for_order_with_customer.php
*
* @return void
*/
public function testOrderInformation(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->registerOrder($order);
$block = $this->layout->createBlock(PrintShipment::class);
$orderDate = $block->formatDate($order->getCreatedAt(), \IntlDateFormatter::LONG);
$templates = [
'Order status' => [
'template' => 'Magento_Sales::order/order_status.phtml',
'expected_data' => (string)__($order->getStatusLabel()),
],
'Order date' => [
'template' => 'Magento_Sales::order/order_date.phtml',
'expected_data' => (string)__('Order Date: %1', $orderDate),
],
];
foreach ($templates as $key => $data) {
$this->assertStringContainsString(
$data['expected_data'],
strip_tags($block->setTemplate($data['template'])->toHtml()),
sprintf('%s wasn\'t found.', $key)
);
}
}
/**
* Register order in registry.
*
* @param OrderInterface $order
* @return void
*/
private function registerOrder(OrderInterface $order): void
{
$this->registry->unregister('current_order');
$this->registry->register('current_order', $order);
}
}
@@ -0,0 +1,131 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Block\Order;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\Context;
use Magento\Framework\View\Element\Text;
use Magento\Framework\View\Layout;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use PHPUnit\Framework\TestCase;
/**
* Tests for order totals block.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
*/
class TotalsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Layout */
private $layout;
/** @var Totals */
private $block;
/** @var OrderInterfaceFactory */
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Totals::class, 'block');
$this->orderFactory = $this->objectManager->get(OrderInterfaceFactory::class);
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testToHtmlChildrenInitialized(): void
{
$this->block->setOrder($this->orderFactory->create())->setTemplate('order/totals.phtml');
$context = $this->objectManager->get(Context::class);
$childOne = $this->getMockBuilder(Text::class)
->setMethods(['initTotals'])
->setConstructorArgs([$context])
->getMock();
$childOne->expects($this->once())->method('initTotals');
$this->layout->addBlock($childOne, 'child1', 'block');
$childTwo = $this->getMockBuilder(Text::class)
->setMethods(['initTotals'])
->setConstructorArgs([$context])
->getMock();
$childTwo->expects($this->once())->method('initTotals');
$this->layout->addBlock($childTwo, 'child2', 'block');
$childThree = $this->getMockBuilder(Text::class)
->setMethods(['initTotals'])
->setConstructorArgs([$context])
->getMock();
$childThree->expects($this->once())->method('initTotals');
$this->layout->addBlock($childThree, 'child3', 'block');
$this->block->toHtml();
}
/**
* @magentoDataFixture Magento/Sales/_files/customer_order_with_two_items.php
*
* @return void
*/
public function testOrderTotalsBlock(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000555');
$blockHtml = $this->block->setTemplate('Magento_Sales::order/totals.phtml')->setOrder($order)->toHtml();
$message = '"%s" for order wasn\'t found or not equals to %01.2f';
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Subtotal'),
$order->getSubtotal()
),
$blockHtml
),
sprintf($message, __('Subtotal'), $order->getSubtotal())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//th[contains(text(), '%s')]/following-sibling::td/span[contains(text(), '%01.2f')]",
__('Shipping & Handling'),
$order->getShippingAmount()
),
$blockHtml
),
sprintf($message, __('Shipping & Handling'), $order->getShippingAmount())
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
sprintf(
"//tr[contains(@class, 'grand_total') and contains(.//strong, '%s')]"
. "//span[contains(text(), '%01.2f')]",
__('Grand Total'),
$order->getGrandTotal()
),
$blockHtml
),
sprintf($message, __('Grand Total'), $order->getGrandTotal())
);
}
}