This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,128 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Block\Adminhtml\Order;
use Magento\Backend\Block\Template;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\ShipmentTrackInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\Sales\Api\OrderRepositoryInterface;
/**
* Class verifies packaging popup.
*
* @magentoAppArea adminhtml
*/
class AddToPackageTest extends TestCase
{
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Registry
*/
private $registry;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->orderRepository = $this->objectManager->get(OrderRepositoryInterface::class);
}
/**
* Test that Packaging popup renders
*
* @magentoDataFixture Magento/Shipping/_files/shipping_with_carrier_data.php
*/
public function testGetCommentsHtml(): void
{
$expectedNeedle = "packaging.setItemQtyCallback(function(itemId){
var item = $$('[name=\"shipment[items]['+itemId+']\"]')[0],
itemTitle = $('order_item_' + itemId + '_title');
if (!itemTitle && !item) {
return 0;
}
if (item && !isNaN(item.value)) {
return item.value;
}
});";
$this->assertStringContainsString($expectedNeedle, $this->getHtml());
}
/**
* Verify currency code on custom value field
*
* @magentoDataFixture Magento/Shipping/_files/shipping_with_carrier_data_different_currency_code.php
*/
public function testGetCurrencyCodeCustomValue()
{
$template = '/<span class="customs-value-currency">\s*?(?<currency>[A-Za-z]+)\s*?<\/span>/';
$matches = [];
preg_match($template, $this->getHtml(), $matches);
$currency = $matches['currency'] ?? null;
$this->assertEquals('FR', $currency);
}
/**
* Get html for packaging popup
*
* @return string
*/
private function getHtml()
{
/** @var Template $block */
$block = $this->objectManager->get(Packaging::class);
$order = $this->getOrderByIncrementId('100000001');
/** @var ShipmentTrackInterface $track */
$shipment = $order->getShipmentsCollection()->getFirstItem();
$this->registry->register('current_shipment', $shipment);
$block->setTemplate('Magento_Shipping::order/packaging/popup.phtml');
$block->setNameInLayout('test');
return $block->toHtml();
}
/**
* Loads order entity by provided order increment ID.
*
* @param string $incrementId
* @return OrderInterface
*/
private function getOrderByIncrementId(string $incrementId) : OrderInterface
{
/** @var SearchCriteria $searchCriteria */
$searchCriteria = $this->objectManager->get(SearchCriteriaBuilder::class)
->addFilter('increment_id', $incrementId)
->create();
$items = $this->orderRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Shipping\Block;
class ItemsTest extends \PHPUnit\Framework\TestCase
{
public function testGetCommentsHtml()
{
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$block = $layout->createBlock(\Magento\Shipping\Block\Items::class, 'block');
$childBlock = $layout->addBlock(\Magento\Framework\View\Element\Text::class, 'shipment_comments', 'block');
$shipment = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Sales\Model\Order\Shipment::class
);
$expectedHtml = '<b>Any html</b>';
$this->assertEmpty($childBlock->getEntity());
$this->assertEmpty($childBlock->getTitle());
$this->assertNotEquals($expectedHtml, $block->getCommentsHtml($shipment));
$childBlock->setText($expectedHtml);
$actualHtml = $block->getCommentsHtml($shipment);
$this->assertSame($shipment, $childBlock->getEntity());
$this->assertNotEmpty($childBlock->getTitle());
$this->assertEquals($expectedHtml, $actualHtml);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Controller\Adminhtml\Order\Shipment;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Data\Form\FormKey;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Abstract backend shipment test.
*/
class AbstractShipmentControllerTest extends AbstractBackendController
{
/**
* @var TransportBuilderMock
*/
protected $transportBuilder;
/**
* @var OrderRepository
*/
protected $orderRepository;
/**
* @var FormKey
*/
protected $formKey;
/**
* @var string
*/
protected $resource = 'Magento_Sales::shipment';
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilder = $this->_objectManager->get(TransportBuilderMock::class);
$this->orderRepository = $this->_objectManager->get(OrderRepository::class);
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* @param string $incrementalId
* @return OrderInterface|null
*/
protected function getOrder(string $incrementalId)
{
/** @var SearchCriteria $searchCriteria */
$searchCriteria = $this->_objectManager->create(SearchCriteriaBuilder::class)
->addFilter(OrderInterface::INCREMENT_ID, $incrementalId)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
/** @var OrderInterface|null $order */
$order = reset($orders);
return $order;
}
/**
* @param OrderInterface $order
* @return ShipmentInterface
*/
protected function getShipment(OrderInterface $order): ShipmentInterface
{
/** @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Collection $shipmentCollection */
$shipmentCollection = $this->_objectManager->create(
\Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory::class
)->create();
/** @var ShipmentInterface $shipment */
$shipment = $shipmentCollection
->setOrderFilter($order)
->setPageSize(1)
->getFirstItem();
return $shipment;
}
}
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Controller\Adminhtml\Order\Shipment;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies shipment add comment functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/shipment.php
*/
class AddCommentTest extends AbstractShipmentControllerTest
{
/**
* @var string
*/
protected $uri = 'backend/admin/order_shipment/addComment';
/**
* @return void
*/
public function testSendEmailOnShipmentCommentAdd(): void
{
$comment = 'Test Shipment Comment';
$order = $this->prepareRequest(
[
'comment' => ['comment' => $comment, 'is_customer_notified' => true],
]
);
$this->dispatch('backend/admin/order_shipment/addComment');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString($comment, $html);
$message = $this->transportBuilder->getSentMessage();
$subject =__('Update to your %1 shipment', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($order->getCustomerName()),
new RegularExpression(
sprintf(
"/Your order #%s has been updated with a status of.*%s/",
$order->getIncrementId(),
$order->getFrontendStatusLabel()
)
),
new StringContains($comment)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $messageConstraint);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest(['comment', ['comment' => 'Comment']]);
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest(['comment', ['comment' => 'Comment']]);
parent::testAclNoAccess();
}
/**
* @param array $params
* @return \Magento\Sales\Api\Data\OrderInterface|null
*/
private function prepareRequest(array $params = [])
{
$order = $this->getOrder('100000001');
$shipment = $this->getShipment($order);
$this->getRequest()->setMethod('POST');
$this->getRequest()->setParams(
[
'id' => $shipment->getEntityId(),
'form_key' => $this->formKey->getFormKey(),
]
);
$data = $params ?? [];
$this->getRequest()->setPostValue($data);
return $order;
}
}
@@ -0,0 +1,334 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Controller\Adminhtml\Order\Shipment\Save;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Shipping\Controller\Adminhtml\Order\Shipment\AbstractShipmentControllerTest;
use Magento\Framework\Escaper;
/**
* Test cases related to check that shipment creates as expected or proper error message appear.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*
* @see \Magento\Shipping\Controller\Adminhtml\Order\Shipment\Save::execute
*/
class CreateShipmentForOrderTest extends AbstractShipmentControllerTest
{
/**
* @var Escaper
*/
private $escaper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
}
/**
* Assert that shipment created successfully.
*
* @magentoDataFixture Magento/Sales/_files/order_with_two_order_items_with_simple_product.php
* @dataProvider dataForCreateShipmentDataProvider
*
* @param array $dataForBuildPostData
* @param array $expectedShippedQtyBySku
* @return void
*/
public function testCreateOrderShipment(array $dataForBuildPostData, array $expectedShippedQtyBySku): void
{
$postData = $this->createPostData($dataForBuildPostData);
$order = $this->orderRepository->get($postData['order_id']);
$shipment = $this->getShipment($order);
$this->assertNull($shipment->getEntityId());
$this->performShipmentCreationRequest($postData);
$this->assertCreateShipmentRequestSuccessfullyPerformed((int)$order->getEntityId());
$createdShipment = $this->getShipment($order);
$this->assertNotNull($createdShipment->getEntityId());
$shipmentItems = $createdShipment->getItems();
$this->assertCount(count($expectedShippedQtyBySku), $shipmentItems);
foreach ($shipmentItems as $shipmentItem) {
$this->assertEquals($expectedShippedQtyBySku[$shipmentItem->getSku()], $shipmentItem->getQty());
}
}
/**
* Data for create full or partial order shipment POST data.
*
* @return array
*/
public function dataForCreateShipmentDataProvider(): array
{
return [
'create_full_shipment' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 5,
'custom-design-simple-product' => 5,
],
'comment_text' => 'Create full shipment',
],
[
'simple' => 5,
'custom-design-simple-product' => 5,
],
],
'create_partial_shipment' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 3,
'custom-design-simple-product' => 2,
],
'comment_text' => 'Create partial shipment',
],
[
'simple' => 3,
'custom-design-simple-product' => 2,
],
],
'create_shipment_for_one_of_product' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 4,
'custom-design-simple-product' => 0,
],
'comment_text' => 'Create partial shipment',
],
[
'simple' => 4,
],
],
'create_shipment_qty_more_that_ordered' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 150,
'custom-design-simple-product' => 5,
],
'comment_text' => 'Create partial shipment',
],
[
'simple' => 5,
'custom-design-simple-product' => 5,
],
],
'create_shipment_qty_less_that_zero' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => -10,
'custom-design-simple-product' => 5,
],
'comment_text' => 'Create partial shipment',
],
[
'custom-design-simple-product' => 5,
],
],
'create_shipment_without_counts' => [
[
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [],
'comment_text' => 'Create partial shipment',
],
[
'simple' => 5,
'custom-design-simple-product' => 5,
],
],
];
}
/**
* Assert that body contains 404 error and forwarded to no-route if
* requested POST data is empty.
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testCreateOrderShipmentWithoutPostData(): void
{
$this->performShipmentCreationRequest([]);
$this->assert404NotFound();
}
/**
* Assert that if we doesn't send order_id it will forwarded to no-rout and contains error 404.
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testCreateOrderShipmentWithoutOrderId(): void
{
$dataToSend = [
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 2,
],
'comment_text' => 'Create full shipment',
];
$postData = $this->createPostData($dataToSend);
unset($postData['order_id']);
$this->performShipmentCreationRequest($postData);
$this->assert404NotFound();
}
/**
* Assert that if we send POST data with wrong order item ids we got error message.
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testCreateOrderShipmentWithWrongItemsIds(): void
{
$orderId = $this->getOrder('100000001')->getEntityId();
$postData = [
'order_id' => $orderId,
'shipment' =>
[
'items' => [
678678 => 4
],
],
];
$this->performShipmentCreationRequest($postData);
$this->assertCreateShipmentRequestWithError(
"Shipment Document Validation Error(s):\nYou can't create a shipment without products.",
"admin/order_shipment/new/order_id/{$orderId}"
);
}
/**
* Assert that if we send POST data with alphabet order item count we got error message.
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
*
* @return void
*/
public function testCreateOrderShipmentWithAlphabetQty(): void
{
$dataToSend = [
'order_increment_id' => '100000001',
'items_count_to_ship_by_sku' => [
'simple' => 'test_letters',
],
'comment_text' => 'Create full shipment',
];
$postData = $this->createPostData($dataToSend);
$this->performShipmentCreationRequest($postData);
$this->assertCreateShipmentRequestWithError(
"Shipment Document Validation Error(s):\nYou can't create a shipment without products.",
"admin/order_shipment/new/order_id/{$postData['order_id']}"
);
}
/**
* @inheritdoc
*/
public function assert404NotFound()
{
$this->assertEquals('noroute', $this->getRequest()->getControllerName());
$this->assertStringContainsString('404 Error', $this->getResponse()->getBody());
$this->assertStringContainsString('Page not found', $this->getResponse()->getBody());
}
/**
* Set POST data and type POST to request
* and perform request by path backend/admin/order_shipment/save.
*
* @param array $postData
* @return void
*/
private function performShipmentCreationRequest(array $postData): void
{
$this->getRequest()->setPostValue($postData)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/admin/order_shipment/save');
}
/**
* Assert that after create shipment session message manager
* contain message "The shipment has been created." and redirect to sales/order/view is created.
*
* @param int $orderId
* @return void
*/
private function assertCreateShipmentRequestSuccessfullyPerformed(int $orderId): void
{
$this->assertSessionMessages(
$this->equalTo([(string)__('The shipment has been created.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('sales/order/view/order_id/' . $orderId));
}
/**
* Assert that session message manager contain provided error message and
* redirect created if it was provided.
*
* @param string $message
* @param string|null $redirect
* @param bool $isNeedEscapeMessage
* @return void
*/
private function assertCreateShipmentRequestWithError(
string $message,
?string $redirect = null,
bool $isNeedEscapeMessage = true
): void {
$assertMessage = $isNeedEscapeMessage
? $this->escaper->escapeHtml((string)__($message)) : (string)__($message);
$this->assertSessionMessages(
$this->equalTo([$assertMessage]),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains($redirect));
}
/**
* Create POST data for create shipment for order.
*
* @param array $dataForBuildPostData
* @return array
*/
private function createPostData(array $dataForBuildPostData): array
{
$result = [];
$order = $this->getOrder($dataForBuildPostData['order_increment_id']);
$result['order_id'] = (int)$order->getEntityId();
$shipment = [];
$shipment['items'] = [];
foreach ($order->getItems() as $orderItem) {
if (!isset($dataForBuildPostData['items_count_to_ship_by_sku'][$orderItem->getSku()])) {
continue;
}
$shipment['items'][$orderItem->getItemId()]
= $dataForBuildPostData['items_count_to_ship_by_sku'][$orderItem->getSku()];
}
if (empty($shipment['items'])) {
unset($shipment['items']);
}
$shipment['comment_text'] = $dataForBuildPostData['comment_text'];
$result['shipment'] = $shipment;
return $result;
}
}
@@ -0,0 +1,117 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Controller\Adminhtml\Order\Shipment;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies shipment creation functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/order.php
*/
class SaveTest extends AbstractShipmentControllerTest
{
/**
* @var string
*/
protected $resource = 'Magento_Sales::ship';
/**
* @var string
*/
protected $uri = 'backend/admin/order_shipment/save';
/**
* @return void
*/
public function testSendEmailOnShipmentSave(): void
{
$tracking = [
[
'number' => 'some_racking_number',
'title' => 'some_tracking_title',
'carrier_code' => 'carrier_code'
]
];
$order = $this->prepareRequest(['shipment' => ['send_email' => true], 'tracking' => $tracking]);
$this->dispatch('backend/admin/order_shipment/save');
$this->assertSessionMessages(
$this->equalTo([(string)__('The shipment has been created.')]),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('sales/order/view/order_id/' . $order->getEntityId()));
$shipment = $this->getShipment($order);
$message = $this->transportBuilder->getSentMessage();
$subject = __('Your %1 order has shipped', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($order->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $shipment->getStore()->getFrontendName()
),
new StringContains(
"Your Shipment #{$shipment->getIncrementId()} for Order #{$order->getIncrementId()}"
),
new StringContains(
'some_tracking_title'
),
new StringContains(
'some_racking_number'
),
new StringContains(
'shipping/tracking/popup?hash='
)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $messageConstraint);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
/**
* @param array $params
* @return \Magento\Sales\Api\Data\OrderInterface|null
*/
private function prepareRequest(array $params = [])
{
$order = $this->getOrder('100000001');
$this->getRequest()->setMethod('POST');
$this->getRequest()->setParams(
[
'order_id' => $order->getEntityId(),
'form_key' => $this->formKey->getFormKey(),
]
);
$this->getRequest()->setPostValue($params);
return $order;
}
}
@@ -0,0 +1,158 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Shipping\Helper;
use Magento\Store\Model\StoreManagerInterface;
class DataTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Shipping\Helper\Data
*/
private $helper;
protected function setUp(): void
{
$this->helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Shipping\Helper\Data::class
);
}
/**
* @param string $modelName
* @param string $getIdMethod
* @param int $entityId
* @param string $code
* @param string $expected
* @dataProvider getTrackingPopupUrlBySalesModelDataProvider
*/
public function testGetTrackingPopupUrlBySalesModel($modelName, $getIdMethod, $entityId, $code, $expected)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$constructArgs = [];
if (\Magento\Sales\Model\Order\Shipment::class === $modelName) {
$orderRepository = $this->getMockOrderRepository($code);
$constructArgs['orderRepository'] = $orderRepository;
} elseif (\Magento\Sales\Model\Order\Shipment\Track::class === $modelName) {
$shipmentRepository = $this->getMockShipmentRepository($code);
$constructArgs['shipmentRepository'] = $shipmentRepository;
}
$model = $objectManager->create($modelName, $constructArgs);
$model->{$getIdMethod}($entityId);
if (\Magento\Sales\Model\Order::class === $modelName) {
$model->setProtectCode($code);
}
if (\Magento\Sales\Model\Order\Shipment\Track::class === $modelName) {
$model->setParentId(1);
}
$actual = $this->helper->getTrackingPopupUrlBySalesModel($model);
$this->assertEquals($expected, $actual);
}
/**
* From the admin panel with custom URL we should have generated frontend URL
*
* @param string $modelName
* @param string $getIdMethod
* @param int $entityId
* @param string $code
* @param string $expected
* @magentoAppArea adminhtml
* @magentoConfigFixture admin_store web/unsecure/base_link_url http://admin.localhost/
* @dataProvider getTrackingPopupUrlBySalesModelDataProvider
*/
public function testGetTrackingPopupUrlBySalesModelFromAdmin($modelName, $getIdMethod, $entityId, $code, $expected)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->create(StoreManagerInterface::class);
$storeManager->reinitStores();
$constructArgs = [];
if (\Magento\Sales\Model\Order\Shipment::class === $modelName) {
$orderRepository = $this->getMockOrderRepository($code);
$constructArgs['orderRepository'] = $orderRepository;
} elseif (\Magento\Sales\Model\Order\Shipment\Track::class === $modelName) {
$shipmentRepository = $this->getMockShipmentRepository($code);
$constructArgs['shipmentRepository'] = $shipmentRepository;
}
$model = $objectManager->create($modelName, $constructArgs);
$model->{$getIdMethod}($entityId);
if (\Magento\Sales\Model\Order::class === $modelName) {
$model->setProtectCode($code);
}
if (\Magento\Sales\Model\Order\Shipment\Track::class === $modelName) {
$model->setParentId(1);
}
//Frontend URL should be used there
$actual = $this->helper->getTrackingPopupUrlBySalesModel($model);
$this->assertEquals($expected, $actual);
}
/**
* @param $code
* @return \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject
*/
private function getMockOrderRepository($code)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$order = $objectManager->create(\Magento\Sales\Model\Order::class);
$order->setProtectCode($code);
$orderRepository = $this->createMock(\Magento\Sales\Api\OrderRepositoryInterface::class);
$orderRepository->expects($this->atLeastOnce())->method('get')->willReturn($order);
return $orderRepository;
}
/**
* @param $code
* @return \Magento\Sales\Model\Order\ShipmentRepository|\PHPUnit\Framework\MockObject\MockObject
*/
private function getMockShipmentRepository($code)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$orderRepository = $this->getMockOrderRepository($code);
$shipmentArgs = ['orderRepository' => $orderRepository];
$shipment = $objectManager->create(\Magento\Sales\Model\Order\Shipment::class, $shipmentArgs);
$shipmentRepository = $this->createPartialMock(\Magento\Sales\Model\Order\ShipmentRepository::class, ['get']);
$shipmentRepository->expects($this->atLeastOnce())->method('get')->willReturn($shipment);
return $shipmentRepository;
}
/**
* @return array
*/
public function getTrackingPopupUrlBySalesModelDataProvider()
{
return [
[\Magento\Sales\Model\Order::class,
'setId',
42,
'abc',
'http://localhost/index.php/shipping/tracking/popup?hash=b3JkZXJfaWQ6NDI6YWJj',
],
[\Magento\Sales\Model\Order\Shipment::class,
'setId',
42,
'abc',
'http://localhost/index.php/shipping/tracking/popup?hash=c2hpcF9pZDo0MjphYmM%7E'
],
[\Magento\Sales\Model\Order\Shipment\Track::class,
'setEntityId',
42,
'abc',
'http://localhost/index.php/shipping/tracking/popup?hash=dHJhY2tfaWQ6NDI6YWJj'
]
];
}
}
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Shipping\Model;
use Magento\Framework\DataObject;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Shipping\Model\Rate\Result;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Abstract class for testing shipping carriers.
*/
abstract class CollectRatesAbstract extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Shipping
*/
protected $shipping;
/**
* @var string
*/
protected $carrier = '';
/**
* @var string
*/
protected $errorMessage = '';
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->shipping = $this->objectManager->get(Shipping::class);
}
/**
* Tests that an error message is displayed when the shipping method is enabled and not applicable.
*
* @return void
*/
public function testCollectRatesWhenShippingCarrierIsAvailableAndNotApplicable()
{
$result = $this->shipping->collectRatesByAddress($this->getAddress(), $this->carrier);
$rate = $this->getRate($result->getResult());
static::assertEquals($this->carrier, $rate->getData('carrier'));
static::assertEquals($this->errorMessage, $rate->getData('error_message'));
}
/**
* Tests that shipping rates don't return when the shipping method is disabled and not applicable.
*
* @return void
*/
public function testCollectRatesWhenShippingCarrierIsNotAvailableAndNotApplicable()
{
$result = $this->shipping->collectRatesByAddress($this->getAddress(), $this->carrier);
$rate = $this->getRate($result->getResult());
static::assertNull($rate);
}
/**
* Returns customer address.
*
* @return DataObject
*/
private function getAddress(): DataObject
{
$address = $this->objectManager->create(
DataObject::class,
[
'data' => [
'region_id' => 'CA',
'postcode' => '11111',
'lastname' => 'John',
'firstname' => 'Doe',
'street' => 'Some street',
'city' => 'Los Angeles',
'email' => 'john.doe@example.com',
'telephone' => '11111111',
'country_id' => 'US',
'item_qty' => 1,
],
]
);
return $address;
}
/**
* Returns shipping rate by the result.
*
* @param Result $result
* @return Method|Error
*/
private function getRate(Result $result)
{
$rates = $result->getAllRates();
return array_pop($rates);
}
}
@@ -0,0 +1,86 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Shipping\Model;
use Magento\Framework\DataObject;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Shipping\Model\Rate\Result;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Contains list of tests for Shipping model
*/
class ShippingTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Shipping
*/
private $model;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->get(Shipping::class);
}
/**
* Checks shipping rates processing by address.
* @covers \Magento\Shipping\Model\Shipping::collectRatesByAddress
* @return Result
*/
public function testCollectRatesByAddress()
{
$address = $this->objectManager->create(DataObject::class, [
'data' => [
'region_id' => 'CA',
'postcode' => '11111',
'lastname' => 'John',
'firstname' => 'Doe',
'street' => 'Some street',
'city' => 'Los Angeles',
'email' => 'john.doe@example.com',
'telephone' => '11111111',
'country_id' => 'US',
'item_qty' => 1
]
]);
/** @var Shipping $result */
$result = $this->model->collectRatesByAddress($address, 'flatrate');
static::assertInstanceOf(Shipping::class, $result);
return $result->getResult();
}
/**
* Checks shipping rate details for processed address.
* @covers \Magento\Shipping\Model\Shipping::collectRatesByAddress
* @param Result $result
* @depends testCollectRatesByAddress
* @magentoConfigFixture carriers/flatrate/active 1
* @magentoConfigFixture carriers/flatrate/price 5.00
*/
public function testCollectRates(Result $result)
{
$rates = $result->getAllRates();
static::assertNotEmpty($rates);
/** @var Method $rate */
$rate = array_pop($rates);
static::assertInstanceOf(Method::class, $rate);
static::assertEquals('flatrate', $rate->getData('carrier'));
static::assertEquals(5, $rate->getData('price'));
}
}
@@ -0,0 +1,49 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\ShipmentFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Framework\DB\Transaction;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order_with_customer.php');
$objectManager = Bootstrap::getObjectManager();
/** @var Transaction $transaction */
$transaction = $objectManager->get(Transaction::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$product = $productRepository->get('simple');
/** @var Order $order */
$order = $objectManager->get(OrderInterfaceFactory::class)->create()->loadByIncrementId('100000001');
$order->setShippingDescription('UPS Next Day Air')
->setShippingMethod('ups_11')
->setShippingAmount(0)
->setCouponCode('1234567890')
->setDiscountDescription('1234567890');
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $objectManager->create(OrderRepositoryInterface::class);
$orderRepository->save($order);
$shipmentItems = [];
foreach ($order->getItems() as $orderItem) {
$shipmentItems[$orderItem->getId()] = $orderItem->getQtyOrdered();
}
$tracking = [
'carrier_code' => 'ups',
'title' => 'United Parcel Service',
'number' => '987654321'
];
$shipment = $objectManager->get(ShipmentFactory::class)->create($order, $shipmentItems, [$tracking]);
$shipment->register();
$transaction->addObject($shipment)->addObject($order)->save();
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\ShipmentFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Framework\DB\Transaction;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order_with_customer.php');
$objectManager = Bootstrap::getObjectManager();
/** @var Transaction $transaction */
$transaction = $objectManager->get(Transaction::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get('simple');
/** @var Order $order */
$order = $objectManager->get(OrderInterfaceFactory::class)->create()->loadByIncrementId('100000001');
$order->setShippingDescription('UPS Next Day Air')
->setShippingMethod('ups_11')
->setOrderCurrencyCode('FR')
->setShippingAmount(0)
->setCouponCode('1234567890')
->setDiscountDescription('1234567890');
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $objectManager->create(OrderRepositoryInterface::class);
$orderRepository->save($order);
$shipmentItems = [];
foreach ($order->getItems() as $orderItem) {
$shipmentItems[$orderItem->getId()] = $orderItem->getQtyOrdered();
}
$tracking = [
'carrier_code' => 'ups',
'title' => 'United Parcel Service',
'number' => '987654321',
];
$shipment = $objectManager->get(ShipmentFactory::class)->create($order, $shipmentItems, [$tracking]);
$shipment->register();
$transaction->addObject($shipment)->addObject($order)->save();
@@ -0,0 +1,9 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order_with_customer_rollback.php');
@@ -0,0 +1,9 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order_with_customer_rollback.php');
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\ShipmentTrackRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Shipment;
use Magento\Sales\Model\Order\Shipment\Track;
use Magento\Sales\Model\Order\ShipmentFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order.php');
$objectManager = Bootstrap::getObjectManager();
$order = $objectManager->get(OrderInterfaceFactory::class)->create()->loadByIncrementId('100000001');
/** @var Order $order */
$items = [];
foreach ($order->getItems() as $orderItem) {
$items[$orderItem->getId()] = $orderItem->getQtyOrdered();
}
/** @var Shipment $shipment */
$shipment = $objectManager->get(ShipmentFactory::class)->create($order, $items);
$shipment->setPackages([['1'], ['2']]);
$shipment->setShipmentStatus(Shipment::STATUS_NEW);
$shipment->save();
/** @var Track $track */
$track = $objectManager->create(Track::class);
$track->setOrderId($order->getId());
$track->setParentId($shipment->getId());
$track->setTitle('Shipment Title');
$track->setCarrierCode(Track::CUSTOM_CARRIER_CODE);
$track->setTrackNumber('track_number');
$track->setDescription('Description of shipment');
/** @var ShipmentTrackRepositoryInterface $shipmentTrackRepository */
$shipmentTrackRepository = $objectManager->get(ShipmentTrackRepositoryInterface::class);
$shipmentTrackRepository->save($track);
@@ -0,0 +1,29 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Registry;
use Magento\Shipping\Model\Order\Track;
use Magento\Shipping\Model\ResourceModel\Order\Track\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/order_rollback.php');
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$trackCollection = Bootstrap::getObjectManager()->create(Collection::class);
/** @var $track Track */
foreach ($trackCollection as $track) {
$track->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);